Try Embedded

Write your own preemptive RTOS kernel (no library)

A real preemptive kernel in about 150 lines for the Uno: task stacks, a 1 ms tick, an assembly context switch, priorities and taskDelay.

RTOS · Advanced

In a real product: RTOS vendor (Industrial): The core of every commercial RTOS is a kernel like this one.

FreeRTOS, Zephyr and every other RTOS kernel come down to the same few ideas: each task has its own stack, a timer interrupt ticks regularly, and on each tick the kernel saves the running task's registers and loads another's. This sketch does all of that with no library, in code short enough to read in one sitting. It runs on the Uno and Nano (ATmega328P).

Three tasks run on it: blink toggles an LED every 250 ms, report prints once a second, and crunch counts as fast as it can and never stops. Even so, the LED keeps perfect time: the kernel takes the CPU away from crunch whenever a more important task wakes.

What you'll learn

  • What a task really is: a stack and a saved set of registers
  • How a timer tick and a context switch give preemption
  • How priorities and round-robin choose the next task
  • How taskDelay() lets a task sleep without wasting CPU time
  • Why shared data needs a critical section, even on an 8-bit chip

How it works

Tasks and stacks. Each task gets a 160-byte array as its stack and a Task record: its saved stack pointer, name, priority, and whether it is asleep. createTask() prepares a new stack so it looks as if the task had already been interrupted just before its first instruction: the address of the task's function (where ret will jump), then 33 bytes for the registers, with the status register's I bit set so interrupts are on when it starts.

The tick. Timer1 runs in CTC mode at 16 MHz / 64 = 250 kHz and interrupts every 250 counts: once a millisecond. The interrupt handler is naked, so the compiler adds no code of its own, and it only calls switchFromTick().

The context switch. switchFromTick() pushes every register of the interrupted task onto that task's own stack (SAVE_CONTEXT), stores the stack pointer in its Task, calls the scheduler, then loads the stack pointer of whichever task the scheduler chose and pops its registers (RESTORE_CONTEXT). The final ret and reti then return into the new task, exactly where it was interrupted last time. The interrupted task never notices.

The scheduler. schedule() counts the tick, wakes tasks whose delay is over, and picks the ready task with the highest priority. Among tasks of equal priority it takes the next one after the current task, so they share the CPU in turns: round-robin. An IDLE task at priority 0 is always ready, so there is always something to run.

Sleeping. taskDelay(ms) marks the task asleep until ticks + ms and calls taskYield(), a context switch the task asks for itself instead of waiting for the tick. A sleeping task costs no CPU time at all.

A critical section. crunchLoops is 4 bytes, and the AVR reads it one byte at a time. If the tick switched to crunch halfway through report's read, report could print a value that never existed. cli() and sei() around the read stop interrupts, and with them task switches, for those few instructions.

Open the Tasks panel while it runs. The kernel reports each switch through the same three spare registers the FreeRTOS builds use, so you can watch blink and report interrupt crunch within a millisecond of waking.

The context switch, line by line

SAVE_CONTEXT:

  • push r0, in r0, __SREG__, cli, push r0: save r0, then the status register. Interrupts go off after reading it, so the saved copy keeps the task's own interrupt flag.
  • push r1, clr r1: the compiler expects r1 to be zero in any C code, including the scheduler about to run.
  • push r2 to push r31: every other register. Together with r0, r1 and the status register: 33 bytes.
  • lds r26, current ... st x+, r0: store the stack pointer (__SP_L__, __SP_H__) in the first field of the current Task. This is why sp has to stay the first member.

RESTORE_CONTEXT is the mirror image: read the new task's saved stack pointer into SP, then pop r31 to r0 in reverse order and the status register with them. The return address on top of that stack takes the CPU back into the task.

The AVR has a 2-byte return address on the Uno and a 3-byte one on the Mega, which is why this sketch is for the ATmega328P only. ARM Cortex-M chips do half of this work in hardware: on an interrupt they save eight registers themselves, and kernels switch tasks in a low-priority exception called PendSV.

How FreeRTOS compares

This kernel is the same design as FreeRTOS's AVR port, much simplified. FreeRTOS adds queues, semaphores, mutexes with priority inheritance, task notifications, software timers, stack overflow checks, a sorted list of sleeping tasks instead of a scan, and years of testing. Writing your own kernel is the best way to understand those features, and the best reason to use a proven one in a product.

Try this

  • Give crunch priority 3, above the others. The LED stops and the reports stop: starvation. Watch it in the Tasks panel.
  • Set crunch back to 1 and remove taskDelay from blink, so blink never sleeps. Since blink has the higher priority, crunch now starves instead.
  • Make blink priority 1, the same as crunch, and remove its taskDelay. Now they take turns every tick: round-robin.
  • Add a binary semaphore: a flag that taskWait() sleeps on until another task (or an ISR) calls taskSignal().
  • Shrink STACK_BYTES until the sketch breaks. Why does report need more stack than blink?

sketch.ino

// A preemptive RTOS kernel in one sketch, with no library: tasks with their own stacks, a 1 ms tick from Timer1,
// priorities with round-robin between equals, and taskDelay(). Uno and Nano (ATmega328P) only: the Mega's 3-byte
// return addresses need a different stack layout.
#include <avr/io.h>
#include <avr/interrupt.h>

// ---- the kernel ---------------------------------------------------------------------------------------------------

const uint8_t MAX_TASKS = 4;        // including the idle task
const uint16_t STACK_BYTES = 160;   // per task: its own calls and locals, its saved registers, and room for ISRs

struct Task {
  uint8_t *sp;            // the saved stack pointer. Must stay first: the assembly reads it at offset 0
  const char *name;
  uint8_t priority;       // the higher, the sooner it runs
  bool sleeping;
  uint16_t wakeAt;        // the tick to wake at, while sleeping
};

Task tasks[MAX_TASKS];
uint8_t stacks[MAX_TASKS][STACK_BYTES];
uint8_t taskCount = 0;

// Read by name from the assembly below, so they keep plain C names and are never optimised away.
extern "C" {
  __attribute__((used)) Task *volatile current;
  __attribute__((used)) volatile uint16_t ticks = 0;
}

// Tells the simulator's Tasks panel which task now runs (the registers FreeRTOS builds use for the same thing).
static inline void trace(const Task *t) {
  GPIOR1 = (uint16_t)t->name & 0xff;
  GPIOR2 = (uint16_t)t->name >> 8;
  GPIOR0 = 1;
}

// Push every register and the status register onto the running task's stack, then store the stack pointer in its
// Task. Interrupts are off from here until the next task's registers are back.
#define SAVE_CONTEXT()                                                    \
  asm volatile(                                                           \
    "push r0             \n\t"                                            \
    "in   r0, __SREG__   \n\t"                                            \
    "cli                 \n\t"                                            \
    "push r0             \n\t"                                            \
    "push r1             \n\t"                                            \
    "clr  r1             \n\t"                                            \
    "push r2  \n\t push r3  \n\t push r4  \n\t push r5  \n\t push r6  \n\t" \
    "push r7  \n\t push r8  \n\t push r9  \n\t push r10 \n\t push r11 \n\t" \
    "push r12 \n\t push r13 \n\t push r14 \n\t push r15 \n\t push r16 \n\t" \
    "push r17 \n\t push r18 \n\t push r19 \n\t push r20 \n\t push r21 \n\t" \
    "push r22 \n\t push r23 \n\t push r24 \n\t push r25 \n\t push r26 \n\t" \
    "push r27 \n\t push r28 \n\t push r29 \n\t push r30 \n\t push r31 \n\t" \
    "lds  r26, current   \n\t"                                            \
    "lds  r27, current+1 \n\t"                                            \
    "in   r0, __SP_L__   \n\t"                                            \
    "st   x+, r0         \n\t"                                            \
    "in   r0, __SP_H__   \n\t"                                            \
    "st   x+, r0         \n\t")

// The reverse for the task `current` now names: load its stack pointer, then pop its registers back.
#define RESTORE_CONTEXT()                                                 \
  asm volatile(                                                           \
    "lds  r26, current   \n\t"                                            \
    "lds  r27, current+1 \n\t"                                            \
    "ld   r28, x+        \n\t"                                            \
    "out  __SP_L__, r28  \n\t"                                            \
    "ld   r29, x+        \n\t"                                            \
    "out  __SP_H__, r29  \n\t"                                            \
    "pop  r31 \n\t pop  r30 \n\t pop  r29 \n\t pop  r28 \n\t pop  r27 \n\t" \
    "pop  r26 \n\t pop  r25 \n\t pop  r24 \n\t pop  r23 \n\t pop  r22 \n\t" \
    "pop  r21 \n\t pop  r20 \n\t pop  r19 \n\t pop  r18 \n\t pop  r17 \n\t" \
    "pop  r16 \n\t pop  r15 \n\t pop  r14 \n\t pop  r13 \n\t pop  r12 \n\t" \
    "pop  r11 \n\t pop  r10 \n\t pop  r9  \n\t pop  r8  \n\t pop  r7  \n\t" \
    "pop  r6  \n\t pop  r5  \n\t pop  r4  \n\t pop  r3  \n\t pop  r2  \n\t" \
    "pop  r1             \n\t"                                            \
    "pop  r0             \n\t"                                            \
    "out  __SREG__, r0   \n\t"                                            \
    "pop  r0             \n\t")

// The scheduler: on a tick, count it and wake the tasks whose delay is over; then pick the highest-priority task
// that is ready. Among tasks of equal priority it takes the next one after the current task: round-robin.
extern "C" __attribute__((used)) void schedule(uint8_t fromTick) {
  if (fromTick) {
    ticks++;
    for (uint8_t i = 0; i < taskCount; i++)
      if (tasks[i].sleeping && (int16_t)(ticks - tasks[i].wakeAt) >= 0) tasks[i].sleeping = false;
  }
  uint8_t at = current - tasks;
  Task *best = nullptr;
  for (uint8_t k = 1; k <= taskCount; k++) {
    Task *t = &tasks[(at + k) % taskCount];
    if (!t->sleeping && (best == nullptr || t->priority > best->priority)) best = t;
  }
  if (best != current) {
    current = best;
    trace(best);
  }
}

// A context switch from the tick: save the task that was interrupted, schedule, resume whichever task won.
extern "C" __attribute__((naked, used)) void switchFromTick() {
  SAVE_CONTEXT();
  asm volatile("ldi r24, 1 \n\t call schedule \n\t");
  RESTORE_CONTEXT();
  asm volatile("ret");
}

// The same, asked for by a task that is giving up the CPU (taskDelay).
extern "C" __attribute__((naked, used)) void taskYield() {
  SAVE_CONTEXT();
  asm volatile("clr r24 \n\t call schedule \n\t");
  RESTORE_CONTEXT();
  asm volatile("ret");
}

// Timer1's compare match, every 1 ms: the tick. Naked, so the compiler adds no register saving of its own.
ISR(TIMER1_COMPA_vect, ISR_NAKED) {
  asm volatile("call switchFromTick \n\t reti \n\t");
}

// Sleep for ms ticks; other tasks run meanwhile.
void taskDelay(uint16_t ms) {
  cli();
  current->wakeAt = ticks + ms;
  current->sleeping = true;
  taskYield();
  sei();
}

// Give a task its stack, laid out as if it had been interrupted at the very start of fn: a return address to fn,
// then the 33 registers SAVE_CONTEXT pushes (SREG with interrupts enabled, the rest zero).
void createTask(void (*fn)(), const char *name, uint8_t priority) {
  Task &t = tasks[taskCount];
  uint8_t *sp = &stacks[taskCount][STACK_BYTES - 1];
  uint16_t pc = (uint16_t)fn;
  *sp-- = pc & 0xff;        // 'ret' pops the high byte first, so the low byte goes in first
  *sp-- = pc >> 8;
  *sp-- = 0;                // r0
  *sp-- = 0x80;             // SREG: the I bit, interrupts enabled
  for (uint8_t r = 1; r <= 31; r++) *sp-- = 0;  // r1 to r31
  t.sp = sp;                // the AVR stack pointer points at the next free byte
  t.name = name;
  t.priority = priority;
  t.sleeping = false;
  taskCount++;
}

void idleTask() {
  for (;;) {}               // runs only when every other task is asleep
}

extern "C" __attribute__((naked)) void startFirstTask() {
  RESTORE_CONTEXT();
  asm volatile("ret");
}

// Start the tick and switch to the first task. Never returns: setup() is left behind on the main stack.
void kernelStart() {
  createTask(idleTask, "IDLE", 0);
  cli();
  TCCR1A = 0;
  TCCR1B = _BV(WGM12) | _BV(CS11) | _BV(CS10);  // CTC mode, clock / 64 = 250 kHz
  OCR1A = 249;                                  // 250 counts: one tick a millisecond
  TCNT1 = 0;
  TIMSK1 = _BV(OCIE1A);
  current = &tasks[taskCount - 1];
  schedule(0);              // the highest-priority task goes first
  trace(current);
  startFirstTask();
}

// ---- the application -------------------------------------------------------------------------------------------

const int LED = 12;
volatile uint32_t crunchLoops = 0;

// Blinks the LED every 250 ms.
void blinkTask() {
  pinMode(LED, OUTPUT);
  for (;;) {
    digitalWrite(LED, !digitalRead(LED));
    taskDelay(250);
  }
}

// Reports once a second how much work crunch got done.
void reportTask() {
  for (;;) {
    cli();                  // a critical section: crunch could change the 4-byte count halfway through the read
    uint32_t loops = crunchLoops;
    sei();
    Serial.print(F("tick "));
    Serial.print(ticks);
    Serial.print(F(", crunch loops "));
    Serial.println(loops);
    taskDelay(1000);
  }
}

// Never sleeps: it gets whatever CPU time the other tasks leave.
void crunchTask() {
  for (;;) crunchLoops++;
}

void setup() {
  Serial.begin(9600);
  createTask(blinkTask, "blink", 2);
  createTask(reportTask, "report", 2);
  createTask(crunchTask, "crunch", 1);
  kernelStart();
}

void loop() {}              // never reached

Lessons behind it