Simvik

A new task's first stack frame

Build the stack a task needs so that the first switch to it starts it at its entry point. A medium embedded C problem (Inside an RTOS kernel), run and graded…

medium · Inside an RTOS kernel · rtos · context-switch · cortex-m · stack

A Cortex-M kernel starts a task by "returning" into it, so a new task's stack must look as if it had been interrupted. Write task_stack_init(t, entry, arg), which fills the top of t->stack with that frame and sets t->sp to its lowest word.

The stack is full-descending: push with *--sp = value, starting from &t->stack[STACK_WORDS]. From the top down the frame is:

  1. The 8 words the hardware pops on exception return: xPSR, PC, LR, R12, R3, R2, R1, R0 (so R0 ends up lowest of the eight).
  2. xPSR = 0x01000000, the Thumb bit; without it the core faults.
  3. PC = entry with bit 0 cleared.
  4. LR = TASK_EXIT, where the task goes if its function returns.
  5. R0 = arg, the task function's parameter. The others are 0.
  6. Below them, the 8 words the kernel restores itself: R11 down to R4 (so R4 ends up at sp). All 0.

Starter code

void task_stack_init(tcb_t *t, uint32_t entry, uint32_t arg) {
  uint32_t *sp = &t->stack[STACK_WORDS];
  *--sp = entry;
  *--sp = arg;
  t->sp = sp;
}

Example tests

A task with an argument

tcb_t t = {0};
task_stack_init(&t, 0x08000401u, 0x2A);
dump(&t);

Expected output:

16 words: 0 0 0 0 0 0 0 0 2A 0 0 0 0 80001F1 8000400 1000000

A stack that held old data

tcb_t t;
for (int i = 0; i < STACK_WORDS; i++) t.stack[i] = 0xFFFFFFFFu;
task_stack_init(&t, 0x08000800u, 0);
dump(&t);

Expected output:

16 words: 0 0 0 0 0 0 0 0 0 0 0 0 0 80001F1 8000800 1000000

Learn it first

More Inside an RTOS kernel problems

  • The context switch · Save one task's registers on its own stack and restore the next task's, as PendSV does.
  • Stack high-water mark · Paint a task stack and find how much of it was never touched.