</>EmbeddedInterview

What are SVC and PendSV used for?

HardMicrocontrollers & ARM Cortex-M

Short answer: SVC (Supervisor Call) is a synchronous exception triggered by the SVC #n instruction; unprivileged code uses it to request privileged services, and RTOSes use it to start the first task. PendSV (Pendable Service) is an asynchronous exception triggered by software setting a bit in SCB->ICSR; it is given the lowest priority, so it runs only after all other interrupts have finished, which makes it the right place for an RTOS to perform context switches.

SVC

  • Executes immediately (synchronously) at the SVC instruction; it cannot be pended.
  • The handler can read the SVC number from the instruction (((uint8_t *)frame[6])[-2]) and arguments from the stacked R0–R3, and return a result in the stacked R0.
  • Uses: system calls from unprivileged tasks (with the MPU), starting the scheduler (FreeRTOS vPortSVCHandler restores the first task), secure/non-secure gateways in some designs.
  • Calling SVC from a handler with equal or higher priority (or with interrupts masked) causes a HardFault, because a synchronous exception cannot wait.

PendSV

  • Set pending with SCB->ICSR = SCB_ICSR_PENDSVSET_Msk;.
  • Configured to the lowest priority: if an ISR wakes a higher-priority task, it pends PendSV; the switch happens only when all ISRs (including nested ones) have completed, so the switch never interrupts an ISR and needs to save only task context.
  • The handler saves R4–R11 (and S16–S31 if the task used the FPU) onto the current task's stack (PSP), stores PSP in the task's TCB, picks the next task, restores its registers and PSP, and returns with EXC_RETURN = thread mode/PSP.

SysTick provides the RTOS tick: its handler updates time, wakes delayed tasks, and pends PendSV if a higher-priority task became ready or a time slice ended.

Why not switch context directly in SysTick or in the ISR? If an ISR pre-empted another ISR, switching tasks there would return to a different task while the first ISR is still unfinished, corrupting the stack. Deferring to the lowest-priority PendSV avoids this and also coalesces several switch requests into one.