I have implemented a context switching code. For going back to privileged user mode after setting the return value in SP + 0x18 address, I am using BX LR instruction.
But code execution goes to HardFault handler and INVPC bit of USAFAULT register is set.
Following is the status of CPU registers just before executing the BX LR instruction. Address (0x100EFA34) saved at SP+0x18 is a valid address where I want PC to go
There are many possible causes:
1) Invalid value in EXC_RETURN number during exception return.For example,– Return to thread with EXC_RETURN = 0xFFFFFFF1– Return to handler with EXC_RETURN = 0xFFFFFFF9To investigate the problem, the current LR value provides the value of LR at the failing exception return.
2) Invalid exception active status. For example:– Exception return with exception active bit for the current exception already cleared. Possibly caused by use ofVECTCLRACTIVE, or clearing of exception active status in SCB->SHCSR.– Exception return to thread with one (or more) exception active bit still active.
3) Stack corruption causing the stacked IPSR to be incorrect.For INVPC fault, the Stacked PC shows the point where the faulting exception interrupted the main/pre-empted program.To investigate the cause of the problem, it is best to use exception trace feature in ITM.
4) ICI/IT bit invalid for current instruction. This can happen when a multiple-load/store instruction gets interrupted and, duringthe interrupt handler, the stacked PC is modified. When the interrupt return takes place, the non-zero ICI bit is applied toan instruction that do not use ICI bits. The same problem can also happen due to corruption of stacked PSR.
In my case, HardFault was triggered from the SV Call context (Case 2). After taking some necessary actions(Loading new context) I have to return from HardFault exception using BX LR. But SYSCALLACT bit in SCB->SHCSR register was still active.Now I am clearing the SYSCALLACT bit in SCB->SHCSR register when HardFault is triggered from an SV Call context. This has solved the issue.