Skip to content
systemcoding.dev
RTOS

Trigger a context switch by setting PENDSVSET in SCB->ICSR

Request a context switch on Cortex-M by writing SCB_ICSR_PENDSVSET_Msk to SCB->ICSR, then DSB and ISB, using CMSIS-Core.

2 min read
Summarize in AI

This is how a Cortex-M kernel asks for a context switch: it does not call the switcher, it pends an exception. Writing SCB_ICSR_PENDSVSET_Msk to SCB->ICSR sets the PendSV pending bit (bit 28), and the core takes the exception as soon as nothing of higher priority is active.

yield.cc
#include "core_cm4.h"

static inline void request_context_switch(void)
{
    SCB->ICSR = SCB_ICSR_PENDSVSET_Msk;   // set PendSV pending
    __DSB();                              // make the write visible
    __ISB();                              // flush the pipeline
}

Only the PENDSVSET bit has an effect when you write the register, because most other bits are read-only or write-one-to-act, so a plain assignment is the documented form and not a read-modify-write. Do not use |=: reading ICSR returns status bits such as VECTACTIVE, and writing back a stale PENDSTSET or PENDSVCLR would set or clear something you did not intend.

The barriers matter when you call this from thread code and expect the switch before the next line. DSB makes the store complete, and ISB makes the core refetch, so the exception is taken at the next instruction boundary rather than a few instructions later. If you call it from inside an ISR, the switch is deferred until that ISR and every other higher-priority handler returns, which is exactly the property a kernel wants. The register and its bit layout are in the Cortex-M4 Generic User Guide (see the System Control Block section at developer.arm.com, document DUI0553).

Also inKernels
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.