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:
- The 8 words the hardware pops on exception return:
xPSR,PC,LR,R12,R3,R2,R1,R0(soR0ends up lowest of the eight). xPSR=0x01000000, the Thumb bit; without it the core faults.PC=entrywith bit 0 cleared.LR=TASK_EXIT, where the task goes if its function returns.R0=arg, the task function's parameter. The others are 0.- Below them, the 8 words the kernel restores itself:
R11down toR4(soR4ends up atsp). 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 1000000A 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 1000000Learn it first
- Inside an RTOS kernel · Task control blocks, ready lists, the tick and the context switch.
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.