Privileged vs Unprivileged Access Levels-Embedded C Training in Hyderabad

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

Example 05 — Source Code Deep-Dive

Privileged vs Unprivileged Access Levels

How the CONTROL register’s nPRIV bit separates trusted kernel code from untrusted user tasks — the foundation of embedded OS security and memory protection.

1. Overview

The 005_access_levels project extends the operation modes demo by adding privilege control. It demonstrates:

  1. Starting in privileged Thread Mode (default after reset)
  2. Downgrading to unprivileged Thread Mode by setting CONTROL.nPRIV = 1
  3. Triggering an interrupt → processor enters Handler Mode (always privileged)
  4. Handler Mode can access all system registers even though Thread Mode was unprivileged

This is the exact mechanism used by an RTOS to isolate user tasks from the kernel.

2. Source Code — Annotated

#include <stdio.h>
#include <stdint.h>

void generate_interrupt()
{
    uint32_t *pSTIR  = (uint32_t*)0xE000EF00;
    uint32_t *pISER0 = (uint32_t*)0xE000E100;
    *pISER0 |= (1 << 3);    /* Enable IRQ3 */
    *pSTIR = (3 & 0x1FF);   /* Trigger IRQ3 */
}

/* --- DOWNGRADE TO UNPRIVILEGED THREAD MODE ---
 * This modifies CONTROL.bit0 (nPRIV):
 *   0 = Privileged Thread Mode (default after reset)
 *   1 = Unprivileged Thread Mode
 *
 * Read-Modify-Write pattern: MRS → ORR → MSR
 */
void change_access_level_unpriv(void)
{
    __asm volatile ("MRS R0, CONTROL");      /* Read CONTROL into R0 */
    __asm volatile ("ORR R0, R0, #0x01");    /* Set bit0 (nPRIV=1) */
    __asm volatile ("MSR CONTROL, R0");      /* Write back */
    /* NOTE: An ISB should follow MSR CONTROL per ARM spec */
}

/* Starts as THREAD MODE + PRIVILEGED */
int main(void)
{
    printf("In thread mode : before interrupt\n");

    /* After this call: Thread Mode is now UNPRIVILEGED */
    change_access_level_unpriv();

    /* Attempting to access privileged resources here would fault.
     * E.g., writing to NVIC ISER0 from unprivileged code
     * would cause a UsageFault (if MPU configured to deny it). */

    /* But generate_interrupt() writes to STIR (privileged resource).
     * In this example WITHOUT MPU, the hardware still allows it
     * because MPU is not configured. The nPRIV bit only restricts
     * access IF an MPU region is configured to enforce it. */
    generate_interrupt();

    printf("In thread mode : after interrupt\n");
    for(;;);
}

/* Handler Mode ISR — ALWAYS privileged regardless of Thread Mode level */
void RTC_WKUP_IRQHandler(void)
{
    printf("In handler mode : ISR\n");
    /* Here: CONTROL.nPRIV is still 1 (set earlier) but
     * IPSR != 0 (we're in Handler Mode) so this is privileged */
}

/* HardFault would fire if unprivileged code violated MPU regions */
void HardFault_Handler(void)
{
    printf("Hard fault detected\n");
    while(1);
}

3. ARM Cortex-M4 Privilege Model

Diagram: 3. ARM Cortex-M4 Privilege Model

Privileged Mode

  • Access all system registers (CONTROL, PRIMASK, BASEPRI, FAULTMASK)
  • Access all NVIC registers (ISER, ICER, IPR, STIR)
  • Access all SCB registers (SHCSR, CCR, VTOR)
  • Configure MPU regions
  • Enable/disable interrupts (CPSID/CPSIE)
  • Write MSR CONTROL

Unprivileged Mode

  • Cannot write to CONTROL register
  • Cannot access NVIC directly (unless CCR.USERSETMPEND=1)
  • Cannot write PRIMASK, BASEPRI, FAULTMASK
  • Limited to user-accessible memory (MPU enforced)
  • Cannot use MSR for most system registers
  • Can read APSR, IPSR, EPSR

CONTROL Register — nPRIV Bit Detail

BitFieldValueMeaning
0nPRIV0Thread Mode is Privileged — full access to all system resources. Default after reset.
0nPRIV1Thread Mode is Unprivileged — restricted access. MPU can enforce additional memory protection.
One-way street: Unprivileged Thread Mode code CANNOT set nPRIV back to 0 (privileged). An unprivileged task cannot elevate itself back to privileged. The only way to return to privileged Thread Mode is through an SVC call — the SVC handler runs in privileged Handler Mode and can clear nPRIV before returning to Thread Mode.

4. Privilege Level Transitions

/* ----------------------------------------------------------------
 * PRIVILEGE TRANSITIONS in ARM Cortex-M4
 * ----------------------------------------------------------------
 *
 * 1. RESET → Thread Mode Privileged (nPRIV=0, SPSEL=0)
 *
 * 2. Privileged Thread Mode → Unprivileged Thread Mode:
 *    MSR CONTROL, #1  (set nPRIV=1)
 *    [CANNOT go back without SVC!]
 *
 * 3. Any Thread Mode → Handler Mode (exception):
 *    Exception fires → CPU enters Handler Mode (always privileged)
 *    CONTROL.nPRIV is NOT changed (still reflects Thread Mode level)
 *    but IPSR != 0 indicates Handler Mode
 *
 * 4. Handler Mode → Privileged Thread Mode:
 *    Clear CONTROL.nPRIV=0 in SVC/PendSV handler, then BX EXC_RETURN
 *
 * 5. Handler Mode → Unprivileged Thread Mode:
 *    Leave CONTROL.nPRIV=1, then BX EXC_RETURN
 *
 * ---------------------------------------------------------------- */

/* Upgrade from unprivileged to privileged (only from SVC handler!) */
void SVC_Handler_Upgrade(void)
{
    /* We're in Handler Mode (privileged) — can modify CONTROL */
    __asm volatile ("MRS R0, CONTROL");
    __asm volatile ("BIC R0, R0, #0x01");   /* Clear nPRIV bit */
    __asm volatile ("MSR CONTROL, R0");
    __asm volatile ("ISB");
    /* When we return from SVC, Thread Mode will be privileged again */
}

5. MPU Interaction with Privilege Levels

The Memory Protection Unit (MPU) is the hardware mechanism that gives the nPRIV bit real enforcement power. Without MPU configuration, the nPRIV bit alone doesn’t prevent access to most memory regions — it only restricts special register access.

ScenarionPRIVMPU RegionResult
Access system register (NVIC)1 (unpriv)N/AHardFault — system registers always restricted for unprivileged
Access Flash (code)1 (unpriv)No MPUAllowed — default no-MPU allows all memory
Access SRAM (data)1 (unpriv)Region set to PRIV_RW/UNPRIV_NOMemManage fault — MPU blocks it
Access SRAM (data)1 (unpriv)Region set to FULL_ACCESSAllowed — MPU permits unprivileged access
Access peripheral1 (unpriv)Region set to UNPRIV_ROWrite causes MemManage fault; read allowed

Basic MPU Configuration Example

/* MPU Register Addresses */
#define MPU_CTRL   (*(volatile uint32_t*)0xE000ED94)
#define MPU_RNR    (*(volatile uint32_t*)0xE000ED98)
#define MPU_RBAR   (*(volatile uint32_t*)0xE000ED9C)
#define MPU_RASR   (*(volatile uint32_t*)0xE000EDA0)

/* Allow unprivileged code to access only 0x20000000–0x20000FFF (4KB) */
void MPU_Configure_UserRAM(void)
{
    MPU_RNR  = 0;                    /* Configure region 0 */
    MPU_RBAR = 0x20000000;           /* Base address */
    MPU_RASR =
        (0b011 << 24) |  /* AP = 011: Privileged RW, Unprivileged RW */
        (0b001 << 19) |  /* TEX = 001, S=0, C=1, B=0: Normal memory, cached */
        (11 << 1)    |   /* SIZE = 11 → 2^(11+1) = 4KB */
        (1 << 0);         /* ENABLE */

    MPU_CTRL = (1 << 0) | (1 << 2); /* ENABLE | PRIVDEFENA */
}

6. Usage in an RTOS Context

In a real RTOS (like FreeRTOS with MPU support), the privilege model works as follows:

/* --- RTOS Kernel (privileged) ---
 * Runs in privileged Thread Mode or Handler Mode.
 * Sets up MPU regions for each task before switching to it. */

/* --- RTOS User Task (unprivileged) ---
 * Runs in unprivileged Thread Mode (CONTROL.nPRIV=1).
 * Can only access memory regions the RTOS grants it.
 * To use a system service (UART, timer config), it calls SVC. */

/* --- SVC Handler (privileged Handler Mode) ---
 * Receives the service request from the unprivileged task.
 * Validates parameters, executes the privileged operation.
 * Returns result to the task stack frame (via R0 in the saved frame). */

void User_Task(void)
{
    /* This code runs in UNPRIVILEGED Thread Mode */
    int result = syscall_add(10, 20);  /* triggers SVC internally */
    /* Cannot directly touch NVIC, SysTick, MPU etc. */
}

int syscall_add(int a, int b)
{
    int res;
    __asm volatile ("SVC #1");   /* SVC #1 = addition service */
    __asm volatile ("MOV %0, R0" : "=r"(res));
    return res;
    /* SVC Handler receives this, does a+b, returns via stack frame */
}

7. Interview Questions & Answers

Q1. What is the difference between privileged and unprivileged access levels in ARM Cortex-M4?
ARM Cortex-M4 has two privilege levels for Thread Mode: Privileged and Unprivileged.

Privileged Thread Mode: Can access all system resources — NVIC, SCB, CONTROL, PRIMASK, MPU, SYSTICK registers. Can write to CONTROL register to change privilege or stack pointer selection. Default after reset.

Unprivileged Thread Mode: Cannot write to most system registers. If MPU is configured, is restricted to specific memory regions. Cannot access core special registers (PRIMASK, BASEPRI, FAULTMASK) via MSR. Cannot directly configure NVIC.

Handler Mode (any ISR) is always privileged regardless of the nPRIV setting. This is a hardware invariant.
Q2. How do you switch from privileged to unprivileged Thread Mode?
Set bit 0 (nPRIV) of the CONTROL register using MSR:
__asm volatile ("MRS R0, CONTROL");
__asm volatile ("ORR R0, R0, #0x01");  /* nPRIV = 1 */
__asm volatile ("MSR CONTROL, R0");
__asm volatile ("ISB");               /* mandatory pipeline flush */
The code itself can do this — transitioning from privileged to unprivileged is allowed. The reverse (unprivileged to privileged) is NOT allowed directly; it must go through an SVC call.
Q3. How does an unprivileged task regain privilege?
An unprivileged Thread Mode task cannot directly write to CONTROL (that would be a privilege violation). The only way is via an SVC (Supervisor Call) instruction. SVC #N triggers an exception → processor enters Handler Mode (always privileged). The SVC handler, running in privileged Handler Mode, can then: (1) validate the request, (2) set CONTROL.nPRIV=0, (3) use BX EXC_RETURN to return to privileged Thread Mode.

This is the same model used in Linux: a user-space process calls a system call (int 0x80/syscall), the kernel runs in privileged mode, executes the service, and returns to user space. The SVC mechanism on ARM is the ARM-equivalent of a Linux system call.
Q4. What happens when unprivileged code tries to access a privileged register?
The behaviour depends on what is accessed:

1. Writing CONTROL via MSR: Generates a UsageFault (NOCP or INVSTATE in UFSR, or may escalate to HardFault if UsageFault not enabled).
2. Writing NVIC registers (ISER, IPR etc.) without USERSETMPEND: May cause a BusFault or be silently ignored depending on the bus implementation.
3. Accessing an MPU-protected memory region: Generates a MemManage fault (DACCVIOL or IACCVIOL in MMFSR).
4. Writing PRIMASK/BASEPRI: UsageFault.

If the corresponding fault handler is not enabled (SHCSR), these escalate to HardFault.
Q5. Why does the ARM architecture have two privilege levels instead of one?
Separation of privilege is fundamental to operating system security and reliability:

1. Isolation: A buggy or malicious user task cannot corrupt the OS kernel or other tasks’ memory (with MPU configured).
2. Controlled access: Hardware resources (timers, DMA, NVIC) are only configurable by trusted kernel code. User tasks request services through a controlled interface (SVC = system call).
3. Fault containment: A fault in an unprivileged task generates a MemManage fault that the RTOS can catch and handle (kill the task). Without privilege separation, a runaway task could corrupt everything.
4. Certification: Safety-critical standards (DO-178C, IEC 61508, ISO 26262) require software partitioning with protection between safety and non-safety tasks.
Q6. In the example, after calling change_access_level_unpriv(), can the unprivileged code still write to STIR?
In this specific example: yes, but only because the MPU is not configured. Without MPU, the nPRIV bit restricts access to core CPU registers (CONTROL, PRIMASK etc.) via the MSR instruction, but it does NOT automatically restrict access to peripheral registers accessed via regular memory reads/writes.

STIR is at 0xE000EF00, which is in the PPB (Private Peripheral Bus, 0xE0000000–0xE00FFFFF). Access to the PPB from unprivileged code behaviour is implementation-defined. On Cortex-M4, unprivileged access to NVIC/SCS registers (0xE000E000–0xE000EFFF) may be silently ignored or cause a fault.

To properly enforce that unprivileged code cannot trigger interrupts, you must: (1) configure an MPU region covering 0xE000E000–0xE000FFFF as privileged-only, and (2) have a HardFault/MemManage handler to catch violations.
Q7. What is the MPU and how does it work with privilege levels?
The MPU (Memory Protection Unit) is a hardware unit that divides the address space into up to 8 (or 16 on some implementations) regions. For each region you define: base address, size (power of 2, minimum 32 bytes), and access permissions for privileged vs unprivileged code (read/write/execute or none). If code running at a certain privilege level tries to access a region in a way that violates its permissions, the MPU generates a MemManage fault.

Without MPU: nPRIV only restricts MSR-based access to system registers.
With MPU: nPRIV + MPU enforces full memory isolation — each task can only access its own stack, its own data, and explicitly shared regions.

FreeRTOS-MPU and Zephyr both use exactly this model to provide RTOS-level memory protection on Cortex-M4 microcontrollers.
Q8. What is the relationship between privilege level and stack pointer selection?
They are controlled by different bits in the CONTROL register and are independent:
• CONTROL.bit0 (nPRIV): 0=privileged, 1=unprivileged (Thread Mode only)
• CONTROL.bit1 (SPSEL): 0=MSP used in Thread Mode, 1=PSP used in Thread Mode

An RTOS typically sets BOTH bits for user tasks: CONTROL = 0x03 → unprivileged + PSP. This means:
• The task is unprivileged (isolated from system registers and MPU-protected regions)
• The task uses PSP (Process Stack Pointer), which is its own isolated stack
• The kernel scheduler uses MSP for its own stack
• On exception entry with PSP active, the hardware saves the stack frame on PSP, and the ISR runs with MSP — cleanly separating kernel and user stacks.

Need Help or More Information?

Questions about this free C programming course, embedded C training or career guidance? Get in touch.

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *