Simvik

The context switch

Save one task's registers on its own stack and restore the next task's, as PendSV does. A hard embedded C problem (Inside an RTOS kernel), run and graded in…

hard · Inside an RTOS kernel · rtos · context-switch · cortex-m · pendsv

On Cortex-M the context switch runs in the PendSV exception. When it starts, the hardware has already pushed R0 to R3, R12, LR, PC and xPSR onto the running task's stack (cpu->psp). The rest is the kernel's job. Write pendsv(cpu, current, next):

  1. Push R11 down to R4 of the current task onto its stack, with *--sp, so R4 ends up lowest.
  2. Save that stack pointer in (*current)->sp.
  3. Make next the current task.
  4. Load its saved stack pointer and pop R4 up to R11 from it.
  5. Leave cpu->psp pointing just above the words you popped.

On return the hardware pops the other eight registers from the new psp, and the next task carries on. New tasks were set up with the frame from the previous problem, so the same code starts them.

Starter code

void pendsv(cpu_t *cpu, tcb_t **current, tcb_t *next) {
  // 1. push R11..R4 of the current task onto cpu->psp
  // 2. save the stack pointer in the current task
  // 3. switch to next
  // 4. load its stack pointer and pop R4..R11
  *current = next;
}

Example tests

Start a new task, then come back

cpu_t cpu = {0};
tcb_t *current = &task_a;
cpu.psp = &task_a.stack[STACK_WORDS - 4];   // A is running, with 4 words of locals
set_regs(&cpu, 0xA0, 0x08000200u);
task_stack_init(&task_b, 0x08000401u, 7);
switch_to(&cpu, &current, &task_b);
show("B", &cpu, &task_b);
set_regs(&cpu, 0xB0, 0x08000460u);
switch_to(&cpu, &current, &task_a);
show("A", &cpu, &task_a);
printf("B saved at sp+%d\n", (int)(&task_b.stack[STACK_WORDS] - task_b.sp));

Expected output:

B pc=08000400 sp+0 r: 7 0 0 0 0 0 0 0 0 0 0 0 0
A pc=08000200 sp+4 r: A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC
B saved at sp+16

Learn it first

More Inside an RTOS kernel problems