RTOS Internals

Three tasks share one chip’s memory, and nothing stops one stack from growing into the next. Size each stack from its measured high-water mark plus an interrupt frame, and the 3 a.m. corruption stops.

Learn what a real-time operating system does under the hood on an Arm Cortex-M chip: how tasks get stacks, how the kernel switches between them, and why interrupts follow their own rules.

Pick Task B, then shrink its stack until the yellow mark crosses the end. Watch Task A’s counter go wrong. Then turn on FP context and see each nested interrupt cost 104 bytes. After that we build, piece by piece, everything underneath.

You need a little C and the idea of an interrupt (a signal that makes the chip pause its work and run a short routine). We build the rest from zero.

Built from primary sources: Arm’s application note DAI0298A on lazy stacking, the FreeRTOS Kernel Book and kernel source, and the Zephyr documentation. Prerequisites: Reset to main(), Embedded RTOS.

Run three tasks in one RAM

Blue is stack in use. The yellow tick is the high-water mark, the deepest the stack ever got. Red is bytes written past the end of a stack.

640 B
6 calls
1 level

A model, not a chip. Stack sizes, call-frame sizes (A 48 B, B 64 B, C 40 B) and the idle depth are made up. The sizes of the interrupt frames are real: 32 B (8 words) without a floating-point context and 104 B (26 words) with one, per Arm DAI0298A. The kernel pushes 36 B more when it parks a task (r4 to r11 and r14), and 64 B more (s16 to s31) with a floating-point context, as in the FreeRTOS Cortex-M4F port.

Chapter 0

The Task That Died at 3 a.m.

Follow one stack overflow from its quiet cause to its distant symptom, and learn the sum that sizes a stack so it never happens

A weather station sits on a pole on a hill. A small chip runs it on a battery. Three tasks share the chip: a control task that counts the minutes and moves a vent, a radio task that sends data home, and a sensor task. For months it works. Then, about once a week, around 3 a.m., the vent jumps to a wrong position, and a few hours later the chip resets itself.

The team reads the control code for a month. It is fine. The bug is not there. The radio task, which sleeps all night and wakes up for one long message, reaches a little deeper into memory than the team ever tested. It writes past the end of its own stack, into the control task’s counter. (The station and the team are a made-up story. The mechanism is real.)

This chapter explains that mechanism with the instrument at the top of the page, and ends with the sum that prevents it. First, a few words need defining.

What a stack is

When a function runs, it needs room for its local variables and for the address to return to. That room is a stack frame. A stack is a block of memory where frames pile up: a call puts a new frame on top, and a return takes it off. Think of a pile of trays. You only ever touch the top one.

On an Arm Cortex-M chip, the pile grows toward lower addresses. The first frame sits at the high end of the block. Each deeper call sits below it. A program that calls six functions deep has six frames stacked down from the top.

An RTOS gives every task its own stack

A real-time operating system (RTOS) is a small piece of code that lets several tasks share one core. A task is a function that runs forever, as if it owned the chip. The kernel pauses one task and resumes another, many times a second. Each task was in the middle of its own calls when it was paused, so each one needs its own pile of trays.

So the kernel carves one stack for each task out of RAM and places them side by side. Look at the strip in the instrument: Task C, Task A, Task B, low address to high. Nothing separates them. A basic Cortex-M chip does not stop one task from writing into the next one’s memory. Write past the low end of B’s stack and you land in the top of A’s, where A keeps its oldest frame and, here, its counter.

Three things pile up on a task’s stack

The call chain is the first. It is the frames of the functions the task has called and not yet left. In the instrument, the call depth slider sets how many, and each frame has a size. A routine that formats a text line can use hundreds of bytes on its own.

The second is the exception frame. When an interrupt fires, the hardware itself pushes eight registers onto the stack before any of your code runs: r0 to r3, r12, the link register, the program counter and the status register. That is 8 words of 4 bytes each, 32 bytes. If the task has used the floating-point unit, the hardware also reserves room for 16 more registers (s0 to s15) and the floating-point status register, plus one spare word. The frame becomes 26 words, 104 bytes. Arm’s application note DAI0298A describes both layouts.

The third is the saved context. When the kernel pauses a task, it parks the registers the hardware did not save: r4 to r11 and the exception-return code, 9 words, 36 bytes. With a floating-point context it also parks s16 to s31, another 64 bytes. Chapter 2 walks through exactly how.

Read the instrument as a sum

Try it above

Go back up to the instrument and turn FP context on and off with Task B selected. Watch the read-out change by the same amount each time. The sum below is what it computes.

6 calls

Toy call frames of 64 B. The 32 B, 104 B, 36 B and 64 B terms are real, from Arm DAI0298A and the FreeRTOS Cortex-M4F port. The first interrupt always costs one frame on the task stack; each extra nesting level costs one more, on ports where interrupts share the task stack.

The sum

Now the sizing rule fits on one line. A task’s stack must hold its deepest call chain, plus one exception frame for the first interrupt and one more for each nested level, plus the saved context, plus a margin for what you did not measure.

S
The stack size you must give the task, in bytes.
C
The deepest call chain: the sum of the frame sizes along the worst path through the code.
F
One exception frame: 32 B without a floating-point context, 104 B with one.
n
How many interrupt levels can nest on this stack. It is 0 when all interrupts run on a separate stack.
X
The saved context the kernel parks: 36 B, or 100 B with a floating-point context.
m
A margin you choose, for code paths and library calls you did not measure.

Task B: 384 + 32 × 2 + 36 = 484 B  →  with FP context: 384 + 104 × 2 + 100 = 692 B (call chain 6 × 64 B, one nested level)

A single floating-point multiply somewhere in Task B moved the answer from 484 B to 692 B, which is 208 B more. A stack of 640 B was safe in the first case and 52 B short in the second. Nobody changed the stack size. Someone changed the compiler flags.

Why the symptom is far from the cause

An overflow does not fail where it happens. The radio task writes into the control task’s memory, and the chip carries on. The damage appears only when the control task next reads its counter, which might be hours later. The only clue is a variable that changed when no code of yours changed it.

So you measure. When FreeRTOS creates a task, it fills the whole stack with the byte 0xA5. This is stack painting. Every byte the task later uses loses its paint. The high-water mark is the amount of paint that survived at the far end: the least free space the stack has ever had. The call uxTaskGetStackHighWaterMark() returns it, in words, not bytes. The closer it is to zero, the closer the task came to overflowing.

c/* FreeRTOSConfig.h: INCLUDE_uxTaskGetStackHighWaterMark must be 1 */
void vMonitorTask(void *arg) {
    for (;;) {
        UBaseType_t freeWords = uxTaskGetStackHighWaterMark(NULL);  /* NULL: this task */
        printf("free: %lu B\n", (unsigned long)freeWords * sizeof(StackType_t));
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

FreeRTOS can also check for you at run time. With configCHECK_FOR_STACK_OVERFLOW set to 1, the kernel checks, at each context switch, that the saved stack pointer is still inside the stack. Setting it to 2 also tests whether the paint at the far end is intact. Both checks run only at a switch, so a task that overflows and recovers between two switches can slip past. The Kernel Book says so plainly. A hardware guard does better: a region of the memory protection unit (MPU) placed at the end of the stack faults the instant anything touches it. Zephyr’s thread documentation describes such a guard.

Put the pieces together and you get the fix. Run the system through its worst cases. Read the high-water mark of each task. Set the stack to the used amount plus a margin. Add a guard if the chip has an MPU. Re-measure whenever the compiler flags, the libraries or the interrupt set change.

The road

  1. Superloop, cooperative, preemptive: when you need an RTOS at all, and what it costs.
  2. The context switch: PendSV, the two stack pointers and the registers the kernel parks.
  3. Tick, tickless and timers: why a sleeping chip wakes 1,000 times a second.
  4. Queues and the FromISR rule: how an interrupt hands work to a task, and the priority limit.
  5. Mutexes and priority inversion: the lock that made a spacecraft reset itself.
  6. Zephyr’s model: devicetree and Kconfig on a small chip.
  7. Moving bare-metal code to an RTOS: shared globals become races.
  8. Field guide: the numbers, a checklist and the sizing sum as code.
A radio task overflows its stack. Hours later, a different task reads a wrong value. Which measurement finds the cause fastest?

Chapter 1

Superloop, Cooperative, Preemptive

Compare three ways to share one core, and work out how long an urgent event waits under each

A heating controller has one job loop. It reads a temperature sensor, sends a reading by radio, writes a log line to flash, and redraws a small display. Then it starts again. Now add a rule: when someone presses the emergency button, the controller must react within 5 milliseconds. How long does the button wait?

The answer depends on how the chip shares its one core between jobs. There are three common designs. Each gives a different answer, and each costs something different. (The controller and its job times are a made-up example. The three designs are real.)

The superloop

A superloop is the simplest design: one endless loop that calls each job in turn. Interrupts do only the urgent, tiny part, such as setting a flag. The loop sees the flag the next time it comes round and does the real work.

cvolatile bool button_flag;                 /* set by the interrupt handler */
void EXTI0_IRQHandler(void) { button_flag = true; }

int main(void) {
    for (;;) {
        read_sensor();        /*  1 ms */
        send_radio();         /*  8 ms */
        write_flash_log();    /* 20 ms */
        update_display();     /*  5 ms */
        if (button_flag) { button_flag = false; handle_button(); }
    }
}

This design has real strengths. There is one stack, so no sizing puzzle like Chapter 0. There is no kernel to learn. The timing is easy to reason about. The weakness is just as clear: the button waits for the whole pass. Here that pass is 1 + 8 + 20 + 5 = 34 ms.

Cooperative scheduling

A cooperative kernel splits the jobs into tasks, each with its own stack and priority. A task runs until it chooses to give up the core, by waiting for something or by yielding. Then the kernel picks the highest-priority task that is ready. In FreeRTOS, setting configUSE_PREEMPTION to 0 gives this behaviour.

The button task now waits only for the current job to end, not for the whole pass. That is up to 20 ms, when the flash write is running. Better, but still not 5 ms.

Preemptive scheduling

A preemptive kernel can take the core away from a running task without asking. The FreeRTOS Kernel Book defines it exactly: as soon as a task with a higher priority becomes ready, the kernel moves the running task back to the ready state and runs the higher one. This can happen at any moment, not only at the tick. Tasks of equal priority take turns, one tick each, which the book calls time slicing.

Now the button task, at the top priority, starts almost at once: the kernel’s switch time plus its own work. The price is everything in this lesson. Every task needs a stack (Chapter 0). Every switch costs time (Chapter 2). Tasks can now interrupt each other in the middle of a data update (Chapter 7). And a lock can invert priorities (Chapter 5).

Press the button at any moment

The bars show what the core does over two passes. The purple line is the button press. The yellow line is the wait. Choose a model, then drag the press time and the flash-write length.

10 ms
20 ms

Illustrative job times: sensor 1 ms, radio 8 ms, flash write as set, display 5 ms, button handler 0.5 ms, deadline 5 ms. The 0.02 ms switch time for the preemptive case is a stand-in; Chapter 2 shows how to measure the real one.

Reading the three answers

With the default settings, press the button at 10 ms. The flash write is running: it began at 9 ms and ends at 29 ms. A superloop waits until the pass ends at 34 ms: a wait of 24 ms. A cooperative kernel waits until the flash write ends at 29 ms: a wait of 19 ms. A preemptive kernel starts the handler at once. The 5 ms deadline is missed twice and met once.

Those waits give a short rule for each design. In a superloop, the worst wait is one full pass. In a cooperative kernel, it is the longest job between yields. In a preemptive kernel, it is the switch time plus any work of equal or higher priority that is already running. The full proof of that last claim is response-time analysis, which a later lesson in this track on deadlines and schedulability covers.

When the superloop is enough

Many shipping products are superloops. It works when the longest pass is shorter than the tightest deadline, when there are only a few jobs, and when no job has to wait for a slow event. Before you reach for a kernel, try splitting long jobs into short steps: write the flash log 256 bytes per pass instead of 4 kilobytes. You have then built a small cooperative scheduler by hand, and it costs nothing.

An RTOS pays off when jobs wait for different events, when deadlines differ by orders of magnitude, or when several people write code that must not block each other. The kernel gives each job a stack, a priority and the right to wait.

The failure mode: timing that was never re-derived

A common story is a team that moves a superloop to a preemptive RTOS and sees every test pass. In the field, under heavy radio traffic, the display freezes for a second and the log shows gaps. The symptom appears only under load.

The cause is that priorities now decide who runs. A task that used to finish in 20 ms may be preempted again and again by busier tasks, so its finishing time grows with the load. The superloop had hidden that coupling. You find it by measuring each task’s worst response time under the heaviest load: toggle a pin at the start and end of each task and read the pulses on a scope or logic analyser. You fix it by choosing priorities from deadlines and by bounding the work in the high-priority tasks.

A superloop has a 34 ms pass, and a button must be handled in 5 ms. Which change helps without adding a kernel?

Chapter 2

The Context Switch, Step by Step

Watch the kernel park one task and wake another, and count every word it moves

You are reading a book and the phone rings. You put in a bookmark, answer, and later find the page again. A task needs the same service. When the kernel pauses it, the task must come back later exactly as it was, with every number it held in its hands.

The core’s “hands” are its registers: a few dozen tiny, very fast storage slots inside the core. A Cortex-M core has r0 to r12 for working values, a stack pointer, a link register that holds a return address, a program counter that holds the next instruction, and a status register. The set of values in them is the task’s context. A context switch saves one task’s context and loads another’s.

Two stack pointers

A Cortex-M core has two stack pointers. The main stack pointer (MSP) is used by the reset code and by every exception handler. The process stack pointer (PSP) is free for the operating system. A kernel makes each task run on PSP, and points PSP at that task’s own stack.

This split has a payoff. To switch tasks, the kernel only has to change where PSP points. The stacks themselves never move. And the interrupt handlers share the one MSP stack, so no task stack has to be big enough for every handler. (This is the setting behind the switch in the instrument at the top.)

Why the switch happens in PendSV

The kernel often decides to switch inside the tick interrupt or inside another interrupt. It cannot switch right there: the interrupt it is inside must finish first. So Arm gives it an exception made for this job, PendSV (pendable service call). The kernel sets it to the lowest interrupt priority. It then pends it: it sets a flag that says “run PendSV when nothing more urgent is running”.

You can see this in the FreeRTOS Cortex-M4F port. The tick handler increments the tick count. If that makes a higher-priority task ready, it writes one bit, portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT, and returns. When every other interrupt has finished, PendSV runs, and the real work starts.

Who saves what

Two parties share the saving. When any exception starts, the hardware pushes eight registers on the stack in use, PSP for a task: r0 to r3, r12, lr, pc and xPSR. Arm’s calling rules let any function overwrite r0 to r3 and r12, so these are the ones that must be saved. That is the exception frame from Chapter 0: 8 words, 32 bytes.

The rest is the kernel’s job. The registers r4 to r11 are callee-saved: a normal function promises to give them back unchanged, but an exception does not make that promise. So PendSV pushes r4 to r11 itself, and also r14, which holds a code called EXC_RETURN. That is 9 words, 36 bytes. Then it stores the new stack pointer in the task’s control block, the kernel’s record for that task.

Floating point adds one more rule. Bit 4 of EXC_RETURN is 0 when the interrupted code used the floating-point unit, so the frame has room for s0 to s15 and the floating-point status register: 26 words in all. Arm’s DAI0298A explains that the hardware may stack lazily: it reserves the room but writes the registers only if a handler actually uses floating point. The kernel still saves s16 to s31, 16 more words, by hand.

Switch from Task X to Task Y

Each step pushes or pops one block of words. Press Next step until Task Y runs. Turn on FP context and run it again.

Word counts are real: hardware frame 8 words (26 with a floating-point context), kernel block 9 words (25 with s16 to s31), as in Arm DAI0298A and the FreeRTOS Cortex-M4F PendSV handler. The call frames and the order of steps are simplified. Assumes Task X has used the floating-point unit.

The real handler

Here is the heart of the FreeRTOS PendSV handler for the Cortex-M4F port, trimmed to the lines that matter. Match each line to a step above.

arm asm  mrs   r0, psp                 @ r0 = task X's stack pointer
  ldr   r3, =pxCurrentTCB
  ldr   r2, [r3]                 @ r2 = X's control block
  tst   r14, #0x10              @ EXC_RETURN bit 4: did X use the FPU?
  it    eq
  vstmdbeq r0!, {s16-s31}        @ if so, push s16..s31 (16 words)
  stmdb r0!, {r4-r11, r14}       @ push r4..r11 and EXC_RETURN (9 words)
  str   r0, [r2]                 @ save X's new top of stack
  mov   r0, #MAX_SYSCALL_PRIORITY
  msr   basepri, r0              @ mask interrupts at or below the kernel limit
  bl    vTaskSwitchContext      @ the scheduler picks task Y
  mov   r0, #0
  msr   basepri, r0              @ unmask
  ldr   r1, [r3]
  ldr   r0, [r1]                 @ r0 = Y's saved stack pointer
  ldmia r0!, {r4-r11, r14}       @ pop Y's r4..r11 and EXC_RETURN
  tst   r14, #0x10
  it    eq
  vldmiaeq r0!, {s16-s31}        @ pop s16..s31 if Y uses the FPU
  msr   psp, r0                 @ PSP now points into Y's stack
  bx    r14                     @ exception return: hardware pops Y's frame and runs Y

The listing simplifies two details: the real code passes the priority limit through an assembler operand and saves r0 and r3 around the call. Read the whole file in the FreeRTOS-Kernel repository under portable/GCC/ARM_CM4F.

One more detail connects to Chapter 0. A brand-new task has never run, so it has nothing to restore. When the kernel creates it, pxPortInitialiseStack() builds a fake saved context on the new stack: a start status word, the address of the task function as the program counter, and the task’s argument in r0. The first switch to that task pops the fake context, and the task begins at its first line.

The cost, and how to measure it

With no floating point, one switch moves 17 words out and 17 words in, 68 bytes each way. With a floating-point context it moves 51 words each way, 204 bytes. The time depends on the chip, the memory speed and the scheduler’s own work, so measure it on your target before you quote any figure.

The cost matters because the tick can trigger a switch. Say a switch takes c cycles on a core running at f hertz, and the tick fires r times a second. The fraction of time lost is r × c / f. With a made-up 300 cycles at 80 MHz, a 1 kHz tick loses 1,000 × 300 / 80,000,000 = 0.375%. A 100 kHz tick would lose 37.5%.

Measure it two ways. Set a spare pin high at the first line of PendSV and low at the last, and read the pulse width on a scope or logic analyser. Or read the core’s cycle counter (the DWT unit’s CYCCNT register) at both points and subtract.

On real hardware. Use an STM32 Nucleo-L476RG. Add a GPIO toggle at the start and end of the PendSV handler, run two tasks that yield to each other, and measure the pulse with and without the FPU enabled. Compare it with the 17-word and 51-word counts above.

A task that uses floating point is switched out. How many words does the switch push onto its stack in total, hardware and kernel together?

Chapter 3

Tick, Tickless and Software Timers

Find out why a chip that is “asleep” wakes a thousand times a second, and how the kernel learns to stay asleep

A sensor node wakes once every 100 milliseconds, reads a value, and goes back to sleep. The datasheet promises a battery life of many months. In the lab, the battery lasts a few weeks. The engineer clips a current meter on the supply and sees a pattern nobody put there: a thin spike of current every single millisecond, all night.

Something wakes the chip 1,000 times a second, and it is not the application. It is the kernel’s own clock. (The node and its currents are a made-up example. The pattern is a well-known one.)

The tick

A kernel needs a sense of time. It counts ticks: regular beats from a hardware timer. On Cortex-M the usual timer is SysTick, a 24-bit counter built into the core. FreeRTOS sets configTICK_RATE_HZ, often 1,000, so a tick lasts 1 ms.

At every beat, the tick interrupt runs. It adds one to the tick count and checks the lists of delayed tasks. If a task’s delay just ran out, the task becomes ready. If tasks of equal priority share the core, the interrupt also pends PendSV so they take turns, which the Kernel Book calls time slicing. So vTaskDelay(10) means “wake me after ten beats”, and the tick rate sets how fine that delay can be: at 100 Hz, the shortest wait is up to 10 ms.

WFI does not mean “stay asleep”

When no task is ready, the kernel runs its idle task. A good idle task executes the WFI instruction, “wait for interrupt”. The core stops fetching instructions and gates its clock, and the current drops. It resumes when any interrupt arrives.

But the tick is an interrupt. Each beat ends the sleep. The core wakes, runs the tick handler for a few microseconds, finds nothing to do, runs the idle task, and executes WFI again. The chip is asleep most of the time, but it cannot enter a deeper sleep, and every beat costs a little energy.

Read the current trace

The trace shows 12 ms of supply current. The tall block is the node doing its real work. Choose how the kernel idles, then drag the work period.

100 ms

Illustrative numbers, not a datasheet: running 10 mA, WFI sleep 1 mA, deep sleep 0.02 mA, each tick costs 20 microseconds of running current, each unit of work runs 2 ms. Tick spikes are drawn wider than 20 microseconds so you can see them. Measure your own chip before you quote any figure.

Tickless idle

The fix is to stop the beat when nothing needs it. With configUSE_TICKLESS_IDLE set to 1, the idle task asks the kernel how long until the next task is due. If that is at least configEXPECTED_IDLE_TIME_BEFORE_SLEEP ticks (default 2), the port code does four things. It stops SysTick. It reloads SysTick to fire after the whole idle time. It executes WFI. And on waking, for any reason, it reads how long it slept and jumps the tick count forward with vTaskStepTick(). The kernel then believes time never stopped.

There is a limit. SysTick is 24 bits, so its largest reload is 16,777,215 counts. At a core clock of 80 MHz and a 1 kHz tick, one tick is 80,000 counts, so the port can suppress at most 16,777,215 / 80,000 = 209 ticks, about 209 ms. After that it wakes once and sleeps again. A hook, configPRE_SLEEP_PROCESSING(), lets you choose a deeper sleep mode. On many chips the deep modes stop the core clock, and SysTick stops with it. Then the port must use a low-power timer instead, such as the one your vendor provides. Read your chip’s reference manual for which timers keep running.

Tickless is not free. Time kept this way drifts a little, because the clock is stopped and restarted. The port code says so itself. And a chip in deep sleep takes longer to wake.

Software timers and the daemon task

A software timer calls one of your functions after a delay, or every so often, without you creating a task for it. Behind the scenes, FreeRTOS runs a single timer daemon task (also called the timer service task). Every software timer callback runs inside that one task.

You set three things in FreeRTOSConfig.h: configTIMER_TASK_PRIORITY, configTIMER_QUEUE_LENGTH and configTIMER_TASK_STACK_DEPTH. The last one is in words, not bytes. Your calls to start, stop or reset a timer do not touch the timer directly. They put a command on the timer command queue, and the daemon takes it from there.

Two consequences matter. First, a callback must never block, for example by waiting on a queue, because that would block the daemon and every other timer with it. Second, the daemon’s stack must hold the deepest call chain of any callback, using the sum from Chapter 0. A callback that calls printf can quietly need far more than the default.

cstatic void vBlink(TimerHandle_t t) {
    HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);   /* short, never blocks */
}
TimerHandle_t h = xTimerCreate("blink", pdMS_TO_TICKS(500), pdTRUE, NULL, vBlink);
xTimerStart(h, 0);   /* sends a command to the daemon's queue */

The failure mode, as symptom, measurement and fix

Symptom: the battery dies weeks early, though the code sleeps “all the time”. Measurement: put a power profiler or a current meter on the supply and look for evenly spaced spikes at the tick rate. Fix: turn on tickless idle, lower the tick rate if your delays allow it, and batch work so the chip has one long idle stretch instead of many short ones.

On real hardware. On an STM32 Nucleo-L476RG, measure the current across the board’s IDD jumper header with a source meter or a power profiler. Compare a build with the tick at 1 kHz against one with configUSE_TICKLESS_IDLE set to 1. Count the spikes in a 100 ms window. The saved energy should match the arithmetic in the read-out above, scaled to your real currents.

An RTOS node runs WFI in its idle task, and the current trace shows a spike every 1 ms. What is the most likely cause, and the fix?

Chapter 4

Queues, Semaphores and the FromISR Rule

Hand work from an interrupt to a task safely, and learn which interrupts may talk to the kernel at all

A serial port receives bytes at 115,200 bits per second. Each byte takes ten bits on the wire (a start bit, eight data bits, a stop bit), so one byte arrives every 10 / 115,200 = 86.8 microseconds. The chip raises an interrupt for each one. The program must read the byte before the next arrives, or it loses data. But understanding a whole command line takes milliseconds.

An interrupt handler must therefore be tiny: grab the byte and get out. A task does the slow parsing. The question is how the handler hands the byte to the task. The answer is a queue, and the rules for using it from an interrupt are the subject of this chapter.

The queue: a mailbox that copies

A queue is a fixed-size first-in, first-out line. FreeRTOS queues copy each item by value into the queue’s own storage. The sender keeps its variable. The receiver gets its own copy. Nobody shares a pointer to a stack that may vanish.

A task that reads an empty queue does not spin. It enters the Blocked state, and the kernel runs something else. When an item arrives, the kernel moves the task to Ready. Blocking is how an RTOS waits without burning power or time.

Why an interrupt needs a different call

An interrupt handler is not a task. It has no task context to put to sleep, so it can never block. A normal xQueueSend() may block when the queue is full, so it is forbidden in an interrupt. FreeRTOS gives every such function a twin that never blocks: xQueueSendFromISR(). All twins end in FromISR.

The twin has one extra parameter. Sending an item may wake a task that is more urgent than the one the interrupt interrupted. The call sets a flag to say so. At the end of the handler you pass the flag to portYIELD_FROM_ISR(), which pends PendSV (Chapter 2). When the handler returns, the switch to the urgent task happens at once, not at the next tick.

cQueueHandle_t rxQ;                                  /* xQueueCreate(64, sizeof(uint8_t)) */

void USART2_IRQHandler(void) {
    BaseType_t woken = pdFALSE;
    uint8_t b = (uint8_t)USART2->RDR;                /* read clears the interrupt */
    xQueueSendFromISR(rxQ, &b, &woken);          /* copies b; never blocks */
    portYIELD_FROM_ISR(woken);                  /* switch now if a higher task woke */
}

void vParseTask(void *arg) {
    uint8_t b;
    for (;;) {
        if (xQueueReceive(rxQ, &b, portMAX_DELAY) == pdPASS) parse_byte(b);
    }
}

A binary semaphore is a queue of length one with no data: a flag that an interrupt gives and a task takes. It signals “something happened” and carries no payload. A counting semaphore remembers how many events arrived. For the lightest signal, FreeRTOS also offers task notifications, which the Kernel Book covers in its own chapter.

Interrupt priorities, with real numbers

There is one more rule, and it is the one that causes the most support requests. The Kernel Book calls wrong interrupt priorities the number one cause of FreeRTOS support requests.

The Cortex-M interrupt controller allows up to eight bits for each interrupt’s priority. A chip maker implements only some of them, always the top ones. ST’s device headers for the STM32F4 and the STM32L4 define __NVIC_PRIO_BITS as 4, so there are 16 levels, 0 to 15. And the scale runs backwards: a lower number means more urgent. Priority 0 is the highest.

Because only the top four bits count, a priority of 5 is stored as 5 shifted left by four: binary 0101 0000, which is 0x50, or 80. Some libraries do that shift for you. CMSIS’s NVIC_SetPriority(irq, 5) takes the plain 5. Other places want the shifted byte. FreeRTOS’s own constant is the shifted kind.

The limit that protects the kernel

The kernel protects its own data, such as the queue lists, with short critical sections. On Cortex-M3 and later it does this without switching all interrupts off. It writes a value into BASEPRI, a register that masks every interrupt whose priority is equal to it or less urgent. The value it writes is configMAX_SYSCALL_INTERRUPT_PRIORITY (newer ports call it configMAX_API_CALL_INTERRUPT_PRIORITY). The PendSV handler in Chapter 2 does exactly that around the scheduler.

The effect is a dividing line. Interrupts at the limit or less urgent are masked inside a critical section, so they can safely call FromISR functions. Interrupts more urgent than the limit are never masked. They run at any moment, even in the middle of a kernel update. So they must never call the kernel. They are the right place for work with very strict timing, such as motor control.

Place the line, find the broken interrupt

Each row is one of 16 priorities. More urgent is at the top. Drag the kernel limit, then move the UART interrupt. Turn on the critical section to see what BASEPRI masks.

5 (0x50)
7 (0x70)

The 4 implemented priority bits are real for the STM32F4 and STM32L4 families (CMSIS device headers). The five interrupts and their priorities are illustrative. The tick and PendSV sit at the least urgent level, as FreeRTOS requires of configKERNEL_INTERRUPT_PRIORITY.

The failure mode

Suppose the UART interrupt sits at priority 3, more urgent than the limit of 5. It calls xQueueSendFromISR(). Usually that works. But if a task is halfway through changing the queue’s list inside a critical section, the UART interrupt is not masked. It runs and edits the same list. Now the list is corrupt. The Kernel Book says exactly this: the critical sections become ineffective, and the result is intermittent failures.

The symptom is a lost byte or a hang once in a few million calls. The measurement is the configASSERT() that the Cortex-M ports run when the scheduler starts and inside each FromISR call: with it defined, the wrong priority stops the program at once. The fix is to move the interrupt to the limit or below, or to stop it calling the kernel. Note too that on reset every interrupt defaults to priority 0, the most urgent. An interrupt whose priority you never set is automatically in the danger zone.

On real hardware. On an STM32 Nucleo-L476RG, use USART2 on the virtual COM port. Set its priority above the limit on purpose, define configASSERT() to stop in a loop, and watch the first FromISR call land in it. Then fix the priority and measure the ISR with a GPIO pin.

On a chip with 4 priority bits, configMAX_SYSCALL_INTERRUPT_PRIORITY is set to priority 5. A timer interrupt at priority 2 calls xQueueSendFromISR(). What is wrong?

Chapter 5

Mutexes and Priority Inversion

See how a lock can make your most urgent task wait for your least urgent one, and what priority inheritance does about it

On 4 July 1997, a small robot rover landed on Mars. Soon after, its main computer began to reset itself. The spacecraft ran the VxWorks real-time operating system. Three tasks mattered. A very high-priority task managed an information bus. A low-priority task collected weather data and used the same bus. In between sat a long-running medium-priority task for communications.

The bus was guarded by a lock. The weather task took the lock, and the bus task needed it, so the bus task waited. Then the communications task became ready. It outranked the weather task, so it ran for a long time. The weather task could not run to release the lock. The bus task could not run without the lock. A watchdog timer noticed the bus task had missed its work and reset the system. Engineers found the cause on a copy of the machine on the ground. The lock’s priority-inheritance option had been left off. They turned it on by sending a short program to the spacecraft. (This account follows Rapita Systems’ write-up of the incident.)

Two tools that look alike

A binary semaphore is a flag with two states, taken or given. Its job is signalling: an interrupt gives it, and a task takes it. Any task or interrupt may give it. Chapter 4 used one this way.

A mutex (short for mutual exclusion) is a lock. Its job is protecting data that two tasks share. The task that takes it is its owner, and only the owner should give it back. The FreeRTOS Kernel Book says the two are very similar. The difference that matters is that mutexes include a basic priority inheritance mechanism and binary semaphores do not. And because inheritance changes task priorities, a mutex must never be used from an interrupt handler.

Priority inversion

A high-priority task is supposed to win any contest for the core. Priority inversion is the case where it does not. The high task waits for a lock that a low task holds. That wait is unavoidable but short: the low task will finish its critical section and release the lock.

It becomes serious when a medium-priority task joins. The medium task outranks the low one, so it takes the core, and the low task stops before it can release the lock. Now the high task waits for the low task, and the low task waits for the medium task, for as long as the medium task wants to run. The Kernel Book calls this unbounded priority inversion.

Priority inheritance

The cure is simple to say. While a high-priority task waits for a mutex, the owner temporarily inherits the high priority. The low task now outranks the medium task, so it runs, finishes its critical section and gives the lock back. Its own priority drops back at that moment. The wait is no longer unbounded. It is as long as the critical section and no longer.

Trace the high task’s wait

Rows are tasks. A filled bar means running. A yellow bar means blocked on the lock. Pink on the Low row means it holds the lock. Choose the lock kind, then lengthen the medium task’s burst.

10 ms
6 ms

A made-up schedule in 0.1 ms steps: Low takes the lock at 0 ms, High arrives at 2 ms and needs the lock for 1 ms, Medium arrives at 3 ms and runs without the lock. High must finish within 8 ms of arriving. The shape is the one in the Mars Pathfinder account; the numbers are not.

Worked through, step by step

With the defaults (critical section 6 ms, medium burst 10 ms), the semaphore trace goes like this. Low runs from 0 and takes the lock. At 2 ms, High arrives, tries to take the lock, and blocks. Low has 4 ms of critical section left and runs for 1 ms. At 3 ms, Medium arrives and takes the core for 10 ms. Low resumes at 13 ms and needs its last 3 ms, so it releases at 16 ms. High takes the lock, uses it for 1 ms, and finishes at 17 ms. It waited 14 ms for a lock it needed for 1.

With a mutex, High blocks at 2 ms and Low inherits its priority. Low outranks Medium, runs its last 4 ms, and releases at 6 ms. High finishes at 7 ms, only 5 ms after arriving. Medium runs afterwards. The wait is the 4 ms critical section, regardless of what Medium does.

The failure mode: inversion that shows up only under load

Symptom: the high-priority task misses a deadline once in a while, and only when the system is busy. Measurement: record a trace with an RTOS tracing tool, such as Percepio Tracealyzer or SEGGER SystemView. Look for the high task in the Blocked state while a lower, medium task runs. Fix: use a mutex with priority inheritance, not a binary semaphore, for shared data. Keep critical sections short. Better still, avoid sharing: give the data one owner task and pass messages through a queue.

Inheritance is a patch, not a proof. The Kernel Book is blunt about this: it does not fix priority inversion, it limits its damage, and it complicates timing analysis, so you should not rely on it for correctness. The full maths of blocking time and of the protocols that bound it belong to the lesson on deadlines and schedulability that comes later in this track.

Two more traps

The first is deadlock. Task 1 takes lock A and then waits for lock B. Task 2 took B and waits for A. Neither can move. The usual cure is to take locks always in the same order. The second is the semaphore-as-mutex mistake in reverse: using a mutex to signal from an interrupt does not work, because an interrupt has no task identity to be the owner.

On real hardware. On an STM32 Nucleo-L476RG, build the three tasks above. Toggle one pin per task whenever it runs. Create the lock once with xSemaphoreCreateBinary() and once with xSemaphoreCreateMutex(). A logic analyser on the three pins shows the same picture as the trace above.

The high task waits for a lock held by the low task, while a medium task runs for a long time. What does a priority-inheritance mutex change?

Chapter 6

Zephyr’s Model: Devicetree and Kconfig on a Small Chip

Learn how another RTOS decides at build time which hardware exists, and why a node that is switched off never becomes a driver

You have a working FreeRTOS program for one board. Your team now wants it on a second board with a different chip. In FreeRTOS, you hunt through the code for every register address and pin number. Zephyr takes another route. It keeps a written description of the hardware next to the code, and the build reads that description to decide what exists.

Zephyr is three things at once: a kernel, a build system, and a hardware description. The kernel part you already know. This chapter covers the other two. We keep it short: the concepts of Chapters 0 to 5 hold in Zephyr, and the names change.

The same ideas, with different names

IdeaFreeRTOSZephyr
A taskxTaskCreatek_thread_create or K_THREAD_DEFINE
Stack for a taska depth in wordsK_THREAD_STACK_DEFINE, a size in bytes
Measure the high-water markuxTaskGetStackHighWaterMarkk_thread_stack_space_get
Wait for timevTaskDelayk_sleep
QueuexQueueSendk_msgq_put
Signal and lockbinary semaphore, mutexk_sem, k_mutex
Software timerxTimerCreatek_timer

Two details differ in a way you can feel. Zephyr priorities are integers where a lower number is more urgent, and a negative number marks a cooperative thread that keeps the core until it blocks. A zero or positive number marks a preemptible thread. And the stack-space call needs two options switched on, CONFIG_INIT_STACKS and CONFIG_THREAD_STACK_INFO, which is Zephyr’s stack painting. Zephyr can also place a write-protected guard region just before a stack to catch overflows, the hardware guard from Chapter 0.

Devicetree: the hardware, written down

A devicetree is a text file that describes hardware as a tree of nodes. A node can stand for a chip, a bus, or a sensor on that bus. Each node has properties such as its address and its compatible string, a name that says which driver can run it. Zephyr uses devicetree to describe the hardware on its supported boards and the initial configuration of that hardware.

The important point is when it is used. Linux reads a devicetree blob while it boots, at run time, and the Linux device model lesson later in this track covers that. Zephyr reads it at build time. The build joins the board’s file with your overlay files, then runs scripts that turn the tree and its bindings (YAML files describing what each node may contain) into a C header, devicetree_generated.h. Your code reads it through macros. Nothing parses a tree on the chip. That is why it suits a part with a few hundred kilobytes of flash.

Kconfig: the software options

Kconfig is the other half. It holds the software choices: is the sensor subsystem built, how big is the heap, is stack painting on. You set them in a file named prj.conf or in a menu. Together, an overlay for the hardware and Kconfig for the software let you reconfigure a whole system without editing the source, as the Zephyr docs put it.

What it takes to get a driver

A node becomes a device only when it is enabled. The rule from the Zephyr docs is exact: a node is enabled if its status is “okay” or not given, and any other value counts as disabled. A node for a physical device must be enabled for its struct device to be allocated and initialised. The driver code must also be part of the build, which Kconfig decides.

Build a device from a node

Flip each switch and watch where the chain from the description to the running device breaks.

An illustrative overlay for an accelerometer at I2C address 0x19 on a bus labelled i2c1. The enabling rule for nodes is quoted from the Zephyr devicetree docs. What each broken case looks like in your build (a link error or a run-time check) depends on how the application asks for the device.

Here is the application side. It asks for the device by its node label, and checks that the device is ready before using it.

c#include <zephyr/kernel.h>
#include <zephyr/drivers/sensor.h>

static const struct device *accel = DEVICE_DT_GET(DT_NODELABEL(accel));  /* from the generated header */

int main(void) {
    if (!device_is_ready(accel)) { /* node off, bus off, or init failed */
        printk("accel not ready\n");
        return 0;
    }
    struct sensor_value v[3];
    for (;;) {
        sensor_sample_fetch(accel);
        sensor_channel_get(accel, SENSOR_CHAN_ACCEL_XYZ, v);
        k_sleep(K_MSEC(100));
    }
}

The failure mode

A node whose status is not okay never becomes a driver, and nothing in the running system complains about the missing device. This is the same class of bug as a compatible string that does not match in Linux: the description and the driver never meet, so the driver never starts.

Symptom: a link error that names the device, or device_is_ready() returning false. Measurement: read the files the build produced: the merged devicetree and the generated header show what the build believed. Fix: set status = "okay" in an overlay, enable the bus node too, and check the Kconfig symbol of the driver. The guiconfig build target shows the final Kconfig values.

On versions: the Zephyr release page lists Zephyr 4.4 on 2026-04-14 and Zephyr 4.5 on 2026-10-28, with 3.7 as the long-term-support release (LTS) from 2024-07-26. Check the release page before you start a project, because board names and option names change between releases.

On real hardware. Build the same application for an STM32 Nucleo-L476RG and an nRF52840 DK. Only the board changes. Then add the overlay above, rebuild, and read the generated header.

A sensor node is in the overlay with status = "disabled". The application calls DEVICE_DT_GET on it. What happens?

Chapter 7

Moving Bare-Metal Code to an RTOS, Under Test

Turn a superloop with forty shared globals into tasks, and find the races the move creates before the field does

A product has shipped for three years on a superloop. Its source has about six thousand lines, a dozen interrupt handlers, and forty global variables that any function may read or write. The team now needs a second radio, and the loop cannot meet its deadlines any more (the Chapter 1 problem). The plan is to move the code to an RTOS without breaking what works.

This is the hardest kind of change, because the old code has an unwritten rule: only an interrupt can break into the main loop, and only at known points. An RTOS removes that rule. After the move, any task can be paused at any instruction by any higher task. Every global is now a possible race. (The product is a made-up example. The risk is the standard one.)

A race, in slow motion

A race is a bug where the result depends on the order in which two things happen. The classic one is a shared counter. In C, errors++ looks like one step. On a Cortex-M it is three instructions: load the value into a register, add one, store it back.

arm asmldr  r1, [r0]      @ read errors
add  r1, r1, #1    @ add one in a register
str  r1, [r0]      @ write it back

Say a task is paused after its load, holding the value 5. An interrupt handler runs, loads 5, adds one, stores 6, and returns. The task resumes, adds one to its own copy of 5, and stores 6. Two errors happened. The counter says 6, not 7. One error vanished. A superloop has the same flaw, but only one place in the loop touched the counter, and its author knew to guard it. After a move, many tasks touch it, and nobody remembers which.

What is safe and what is not? On a Cortex-M, a single aligned 32-bit load or store is one instruction, and an interrupt cannot split it. So a 32-bit value that one side only writes and the other only reads is safe, if you also mark it volatile so the compiler does not cache it. A 64-bit value takes two instructions, so a reader can see half of the old value and half of the new one. A struct of 24 bytes is worse. And any read-modify-write has the lost-update problem above.

The five steps

One: take inventory. List every global, and for each one, who reads it and who writes it: interrupt, loop, or both. Your linker map and a search of the source give the first list. Do not change code yet.

Two: partition. Interrupt handlers shrink to the minimum: acknowledge the hardware, copy the data, signal a task (Chapter 4). The work moves into tasks, grouped by deadline (Chapter 1). Every delay loop becomes a blocking call, so waiting costs nothing.

Three: give every global one owner. A variable that one task owns, and that others reach only through a queue or a function the owner provides, cannot race. Put queues at the boundaries, as in Chapter 4.

Four: re-derive the timing and the stacks. Choose priorities from deadlines. Size each stack with the sum from Chapter 0, and measure the high-water marks under the heaviest load. Keep locks short, and use mutexes with priority inheritance, as in Chapter 5.

Five: gate every change with tests on real hardware. Build each commit in a continuous-integration (CI) system. Flash it to a board on a bench. Run scripted scenarios, and fail the build if a deadline is missed or a stack mark drops below its margin. This is hardware-in-the-loop testing. The later lesson on fail-safe design and functional safety covers it.

Choose a handoff for each global

Each row is a global from the old superloop and who touches it. Pick the way to share it after the move. A wrong pick tells you what would break.

Illustrative globals. The Cortex-M facts are real: an aligned 32-bit load or store is one instruction; a 64-bit access and a read-modify-write are not. More than one handoff can be valid for some rows; the board accepts the ones a reviewer would accept.

The failure mode

Symptom: the migrated build passes every bench test, then shows rare wrong values in the field: a counter that is low, a position that jumps by exactly half a word. Measurement: a trace of every access. Run the logic on a PC build under a race detector such as ThreadSanitizer, and on the target put a hardware watchpoint on the variable so the debugger stops at each write and shows who wrote it. Add a static-analysis pass in CI that flags any global written from two contexts. Fix: pick the handoff for each shared variable as in the board above.

On real hardware. On an STM32 Nucleo-L476RG, make one task and one interrupt both increment a counter ten million times without protection. Print the total. Then protect it with a critical section and repeat. The first total will be short by a visible amount.

A 64-bit odometer is updated by a timer interrupt and read by a task on a Cortex-M4. Why can the task read a wrong value, and what fixes it?

Chapter 8

Field Guide

Keep the numbers, the checklist and the sizing sum in one place, and find where to go next

You can now say what an RTOS does to a small chip, from memory. It gives each task a stack carved from shared RAM. It parks and restores a task’s registers in the PendSV handler. It keeps time with a tick, and it can stop the tick to sleep. It hands work from interrupts to tasks through queues and semaphores, under a priority line that protects its own data. And it can lend priority to a lock owner so a medium task cannot starve a high one.

The one-paragraph summary

A task’s stack must hold its deepest call chain, one exception frame for the first interrupt and one more for each nesting level that shares the stack, the kernel’s saved context, and a margin. A floating-point context turns a 32-byte frame into a 104-byte one. The high-water mark measures the real peak. A context switch changes only the stack pointer and moves a few dozen words. The tick keeps the chip from sleeping deeply; tickless idle fixes that. Interrupts that call FromISR functions must sit at or below the kernel limit. A mutex beats a binary semaphore for guarding data because it lends priority. And moving from a superloop to an RTOS turns every shared global into a possible race.

The numbers that matter

WhatNumberSource
Basic exception frame8 words = 32 B (r0 to r3, r12, lr, pc, xPSR)Arm DAI0298A
Frame with a floating-point context26 words = 104 B (8 + s0 to s15 + FPSCR + 1 reserved)Arm DAI0298A layout
Kernel-saved contextr4 to r11 and r14: 9 words = 36 B; s16 to s31: 16 words = 64 BFreeRTOS Cortex-M4F port, PendSV handler
One context switch, out of a task17 words (68 B); with a floating-point context 51 words (204 B)sums of the two rows above
Stack paint0xA5 fills the stack at task creationFreeRTOS tasks.c
High-water markminimum free stack ever, in wordsFreeRTOS Kernel Book, ch. 13
Overflow check, method 2tests the pattern at the far end, only at a context switchKernel Book ch. 13; stack_macros.h
Interrupt priority bits4 on STM32F4 and STM32L4: 16 levels; priority 5 is stored as 0x50 = 80ST CMSIS device headers; Kernel Book ch. 7
Tickless limit24-bit SysTick: 209 ticks at 80 MHz and a 1 kHz tickport.c: 16,777,215 divided by counts per tick
Least idle time to stop the tick2 ticks by defaultFreeRTOS.h, configEXPECTED_IDLE_TIME_BEFORE_SLEEP
One serial byte at 115,200 bit/s10 bits = 86.8 microsecondsarithmetic
Switch overhead (illustrative)300 cycles at 80 MHz: 0.375% at 1 kHz; 37.5% at 100 kHzr × c / f; measure your own c
Mars Pathfinder resetslanded 4 July 1997; priority inheritance had been left offRapita Systems account
FreeRTOS kernel releasesV11.0.0 on 2023-12-18; V11.3.0 on 2026-03-30GitHub releases
Zephyr releases4.4 on 2026-04-14; 4.5 on 2026-10-28; 3.7 LTS on 2024-07-26Zephyr release page

The checklist

  1. Size every stack from the sum, then confirm with the high-water mark under the worst load. Re-check after any compiler, library or interrupt change.
  2. Turn on a guard if the chip has an MPU, and turn on the run-time stack check while developing.
  3. Know where interrupts run: on the task stack or on their own. Count nesting levels for whichever stack they use.
  4. Measure the context switch on your target with a pin toggle or the cycle counter.
  5. Look at the current trace for spikes at the tick rate. Use tickless idle if they are there.
  6. Set the kernel limit deliberately, and put every interrupt that calls FromISR at or below it. Define configASSERT().
  7. Guard shared data with a mutex, signal with a semaphore or queue, and give each global one owner.
  8. Record a trace before you blame the scheduler, and look for the high task in the Blocked state.

The sizing sum as code

pythonimport math

def stack_bytes(chain, fp=False, nest=1, shared=True, margin=0.25):
    """chain: frame sizes (bytes) along the worst call path of one task."""
    frame = 104 if fp else 32             # exception frame (Arm DAI0298A)
    saved = 36 + (64 if fp else 0)     # r4-r11, r14 (+ s16-s31): FreeRTOS CM4F PendSV
    irq   = frame * (1 + (nest if shared else 0))   # first interrupt, plus each nested level
    need  = sum(chain) + irq + saved
    return need, math.ceil(need * (1 + margin) / 8) * 8   # keep the stack 8-byte aligned

print(stack_bytes([64] * 6))               # (484, 608)
print(stack_bytes([64] * 6, fp=True))      # (692, 872)
print(stack_bytes([64] * 6, nest=3, shared=False))  # (452, 568): nesting lands on the interrupt stack

The frame sizes in the example are made up. In a real project, read them from the compiler’s stack-usage output and from a measured high-water mark. The interrupt stack, when it is separate, needs its own sum: the largest handler chain plus one frame for each nesting level.

Where this sits

This lesson built on Reset to main() (the stack and the vector table) and on the survey in Embedded RTOS. Embedded real-time systems goes deeper into the Cortex-M4 and its timers. For the same ideas on a big processor, see Real-time Linux and pipelines and privilege.

Keep going

Later lessons in this track cover deadlines and schedulability (the response-time maths this lesson only pointed at), and micro-ROS on FreeRTOS and Zephyr.

Sources

This lesson is not based on a course. It was built from the primary sources above. The Cortex-M4 timing of a context switch and the supply currents in Chapter 3 are deliberately not quoted: measure them on your own board.

The takeaway. An RTOS moves your program’s problems, it does not remove them. The old shared state becomes stacks, locks and priorities, and each has a number you can measure. Measure it before it fails at 3 a.m.

Go back to the three stacks at the top and push Task C until it overflows too. Then open Teach mode from the dock and explain the sizing sum on a whiteboard.

RTOS Internals: Context Switch, Stacks and the FromISR Rule
Reset to main() · Embedded RTOS · Back to Gleams