I’m trying to implement a context switch for my RTOS. The context switch occurs in my PendSV_Handler.
When I do the very first context switch from task 1 to task 2, when I run the line for bx lr
, it causes a hard fault
__attribute((naked)) void PendSV_Handler(void)
{
__asm volatile
(
// Save the context of the current task
" mrs r0, psp n" // get current PSP
" isb n"
" ldr r1, =curr_task n" // load address of the pointer curr_task into r1
" ldr r2, [r1] n" // load TCB pointed to by curr_task, into r2
" stmdb r0!, {r4-r11} n" // store r4 - r11 on process stack
" str r0, [r2] n" // Save new stack top
// Update curr_task to next_task
" ldr r0, =next_task n" // load address of next_task into r0
" ldr r2, [r0] n" // load pointer to next_task's TCB
" str r2, [r1] n" // update curr_task to point to next_task
// Restore the context of the next task
" ldr r0, [r2] n" // get the (new) curr_task's stack_top
" ldmia r0!, {r4-r11} n" // restore r4-r11 from stack
" msr psp, r0 n" // update PSP with stack_top
" bx lr n" // return to the next task
);
}
When I hit the line bx lr
, PSP is at the next task’s stack, after having restored & popped its R4 – R11. Therefore, if i print PSP at that point, I get this:
Yellow = R0 – R3, and R12
Green = LR set for a return to Thread mode using Basic frame
Orange = PC. This is the address for the next task function, as seen in the next print
Pink = xPSR, having set bit 24, the Thumb bit.
This follows the stack-popping convention on exception return, as stated in Page 542 of the ARMv7-M Architecture Reference Manual:
However, after I execute the bx lr
instruction, I go to the HardFault_Handler
The 0x82 means PRECISERR with BFARVALID in the Bus Fault Register
Now, if I inspect BFAR at 0xE000ED38 to see the address that caused the fault:
I see this memory address that I didn’t try to access.
I would like some pointers on where else I should look for the cause of this error?
My stack for each task is set up like this. This issue happens on the first ever context switch, so it’s using the initial stack values shown here
Thank you. Let me know if any more information would help.