Inside an RTOS kernel
Task control blocks, ready lists, the tick and the context switch.
Opening the black box
Interviewers who ask "how does an RTOS work?" want to hear that you understand it is not magic: a few data structures, a tick interrupt and a context switch. This lesson builds a working model of a small preemptive kernel, the kind FreeRTOS, Zephyr and others implement.
The task control block
Every task has a task control block (TCB): the kernel's record of it.
typedef struct tcb {
uint32_t *sp; /* saved stack pointer: MUST be first (the context switch finds it here) */
uint8_t priority;
uint8_t state; /* READY, BLOCKED, SUSPENDED */
uint32_t wake_tick; /* when a delayed task becomes ready again */
struct tcb *next; /* links in the ready list or a wait list */
void *waiting_on; /* the semaphore, queue or mutex it is blocked on */
const char *name;
uint32_t *stack_base; /* for overflow checking */
} tcb_t;
Creating a task allocates a stack and a TCB, and fakes an exception frame on the new stack, as if the task had been interrupted just before its first instruction: PC set to the task function, LR to an exit handler, xPSR with the Thumb bit set. The first context switch to it then "returns" into the task.
Ready lists and choosing the next task
The scheduler must find the highest-priority ready task quickly, whatever the number of tasks. FreeRTOS keeps one list of ready tasks per priority level, plus a bitmap of which levels are non-empty. Finding the highest ready priority is then a count-leading-zeros instruction (CLZ on Arm): constant time.
#include <stdio.h>
#include <stdint.h>
#define PRIORITIES 8
typedef struct task { const char *name; int prio; struct task *next; } task_t;
static task_t *ready[PRIORITIES]; /* one FIFO list per priority */
static uint32_t ready_bits; /* bit p set when ready[p] is non-empty */
static void make_ready(task_t *t) {
t->next = NULL;
task_t **p = &ready[t->prio];
while (*p) p = &(*p)->next; /* append: round robin within a priority */
*p = t;
ready_bits |= 1u << t->prio;
}
static task_t *pick_next(void) {
if (!ready_bits) return NULL;
int top = 31 - __builtin_clz(ready_bits); /* highest set bit: one CLZ instruction on Arm */
task_t *t = ready[top];
ready[top] = t->next;
if (!ready[top]) ready_bits &= ~(1u << top);
return t;
}
int main(void) {
task_t idle = { "idle", 0 }, logger = { "logger", 2 }, comms = { "comms", 5 }, motor = { "motor", 5 };
make_ready(&idle); make_ready(&logger); make_ready(&comms); make_ready(&motor);
for (int i = 0; i < 4; i++) { task_t *t = pick_next(); printf("run %s (priority %d)\n", t->name, t->prio); }
return 0;
}
Tasks of equal priority are taken in FIFO order; re-appending the running task at the end of its list at each tick is round-robin time slicing.
Blocking and delayed lists
A task that calls vTaskDelay(10) is removed from the ready list and inserted, sorted by wake time, into a delayed list. Each tick the kernel checks the head of that list (constant time, since it is sorted) and moves expired tasks back to the ready lists.
A task blocking on a semaphore or queue goes onto that object's wait list, ordered by priority, and usually also onto the delayed list if it gave a timeout. Giving the semaphore takes the highest-priority waiter off the wait list and makes it ready; if it outranks the running task, a context switch is requested.
The tick
The SysTick interrupt, typically 1 kHz:
- increments the tick count
- moves tasks whose delay has expired to the ready lists
- if time slicing, rotates the current priority's ready list
- if a higher-priority task is now ready, pends a context switch
Tickless idle: when every task is blocked, the kernel calculates when the next one wakes, programs a low-power timer for that moment, stops SysTick and sleeps; on wake-up it corrects the tick count.
The context switch
On Cortex-M the switch runs in the PendSV handler at the lowest priority (see the exception model lesson):
PendSV_Handler:
mrs r0, psp @ current task's stack pointer
stmdb r0!, {r4-r11} @ save the registers the hardware did not stack
ldr r1, =current_tcb
ldr r2, [r1]
str r0, [r2] @ current_tcb->sp = r0
push {r1, lr}
bl scheduler_pick_next @ updates current_tcb
pop {r1, lr}
ldr r2, [r1]
ldr r0, [r2] @ r0 = new task's saved sp
ldmia r0!, {r4-r11} @ restore its registers
msr psp, r0
bx lr @ exception return pops r0-r3, r12, lr, pc, xPSR
(Real kernels also save and restore FPU registers s16–s31 when the task used the FPU, and mask interrupts around the list manipulation.)
The hardware stacked half the registers on exception entry; the handler saves the other half and swaps stack pointers. Returning from the exception then restores the new task's registers, so execution continues in a different task.
Critical sections inside the kernel
Kernel lists are shared between tasks and interrupts, so every manipulation is a critical section. On M3 and above, FreeRTOS raises BASEPRI to configMAX_SYSCALL_INTERRUPT_PRIORITY instead of disabling all interrupts, so higher-priority interrupts (that never call the kernel) are never delayed. That is why interrupts that call ...FromISR functions must have a priority at or below that level.
Priority inheritance, implemented
When a task blocks on a mutex held by a lower-priority task, the kernel:
- records the holder in the mutex
- raises the holder's priority to the waiter's (moving its TCB to the higher ready list)
- on release, restores the holder's original priority and gives the mutex to the highest-priority waiter
Chains (A waits on B, B waits on C) require propagating the boost, which some simple kernels do not do completely.
Memory
- Static allocation (
xTaskCreateStatic): the application provides TCB and stack memory; nothing can fail at run time. Preferred for safety-related systems. - Dynamic from a kernel heap (FreeRTOS
heap_1toheap_5):heap_1never frees;heap_4coalesces free blocks;heap_5spans several RAM regions. - Stack overflow detection: checking the stack pointer at each switch, or a canary pattern at the stack's end, or an MPU guard region.
Pitfall: Calling a blocking kernel function before
vTaskStartScheduler(), or from an interrupt, corrupts the kernel's lists, and the crash appears much later in an unrelated task. UseFromISRAPIs from interrupts and keep initialisation that blocks inside a task.
Interview question: Walk through what happens when an interrupt gives a semaphore that a high-priority task is waiting on.
Answer: The ISR calls xSemaphoreGiveFromISR, which, inside a critical section, takes the highest-priority waiter off the semaphore's wait list (and off the delayed list if it had a timeout), puts it on the ready list for its priority and sets the woken flag if it outranks the interrupted task. portYIELD_FROM_ISR then pends PendSV. When the ISR and any other interrupts finish, PendSV runs at the lowest priority, saves the interrupted task's remaining registers on its stack, stores its stack pointer in its TCB, selects the high-priority task, restores its registers and stack pointer, and exception return resumes it inside xSemaphoreTake.
Interview question: Why should RTOS kernel critical sections use BASEPRI rather than disabling all interrupts?
Answer: Disabling all interrupts with PRIMASK delays every interrupt, including time-critical ones that never use the kernel, for the length of each kernel critical section. Raising BASEPRI to the kernel's maximum syscall priority masks only the interrupts that are allowed to call kernel APIs, which are the only ones that could corrupt kernel data, while higher-priority interrupts keep zero added latency. It is not available on Cortex-M0, where PRIMASK must be used.
Build it: the kernel's ready list
This is step 5, the last of the module project. A certified medical RTOS must pick the next task in constant time, however many tasks are ready, so the time from an interrupt to the motor task running has a fixed upper bound. Build the structure that does it: a ready list indexed by a priority bitmap.
Lab: An O(1) ready list with a priority bitmap
There are 32 priority levels (31 is the most urgent). Each level has a FIFO list of ready tasks (provided as small arrays), and one 32-bit bitmap has bit p set exactly when level p has at least one ready task.
ready_add(task, p)appends a task to the end of levelpand sets its bit.ready_remove(task, p)takes the task out of levelp(wherever it is in the list, keeping the order of the others), and clears the bit if the level is now empty. It returns false if the task was not there.pick_next()returns the task at the front of the highest non-empty level, or -1 if nothing is ready. Find that level in constant time with31 - __builtin_clz(bitmap)(the bitmap must not be 0 for that), not with a loop over 32 levels.rotate(p)is called on each tick: the task at the front of levelpmoves to the back, so tasks of equal priority take turns (round robin).
Going deeper
Interview question: How would you explain to an auditor how your RTOS switches tasks?
Answer: A timer interrupt (or a blocking call) asks the scheduler to run; the scheduler picks the highest-priority ready task; the context switch (often in PendSV on Cortex-M) saves the current task's registers on its stack, stores its stack pointer, loads the next task's stack pointer and restores its registers. Show the worst-case switch time measured on the target and the priority rules.
Interview question: What does the idle task do, and why must it never block?
Answer: The idle task runs at the lowest priority when no other task is ready, so the scheduler always has something to run. It often frees memory of deleted tasks, calls an idle hook, and enters low-power sleep, or in tickless mode computes the next wake-up and stops the tick. If it blocked, there would be moments with no ready task at all and the scheduler would have nothing to switch to.
Interview question: Why are delayed lists kept sorted by wake time?
Answer: So the tick interrupt only needs to look at the head of the list: if the first task's wake time has not been reached, none has, and the check is constant time however many tasks are delayed. The cost moves to insertion, which happens in task context when a task blocks. FreeRTOS also keeps a second delayed list for wake times past the tick counter's overflow and swaps the lists when the counter wraps.
Explain it: In your own words, explain how an RTOS switches from one task to another on a Cortex-M.
Answer: Something makes a higher-priority task ready: a tick, a semaphore given by an interrupt or another task. The kernel pends the PendSV exception, which runs at the lowest priority once other interrupts have finished. Entering PendSV, the hardware has already pushed half the current task's registers onto its own stack; the handler pushes the rest, saves the resulting stack pointer in the task's control block, asks the scheduler for the highest-priority ready task, loads that task's saved stack pointer, pops its saved registers and returns from the exception. The hardware then pops the remaining registers from the new task's stack, so execution continues exactly where that task last stopped.