Skip to content

Commit eb33d96

Browse files
committed
Improve mstatus reconstruction
The instruction count in 'hal_context_save' has been reduced from 7 to 6.
1 parent 4654f81 commit eb33d96

File tree

2 files changed

+6
-20
lines changed

2 files changed

+6
-20
lines changed

Documentation/hal-riscv-context-switch.md

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -48,20 +48,7 @@ typedef uint32_t jmp_buf[17];
4848
The `hal_context_save` function captures complete task state including both execution context and processor state.
4949
The function saves all callee-saved registers as required by the RISC-V ABI,
5050
plus essential pointers (gp, tp, sp, ra).
51-
For processor state, it performs sophisticated interrupt state reconstruction:
52-
53-
```c
54-
/* mstatus reconstruction during timer interrupts */
55-
csrr t0, mstatus // Read current mstatus (MIE=0 in trap)
56-
srli t1, t0, 4 // Shift MPIE (bit 7) to bit 3 position
57-
andi t1, t1, 8 // Isolate the reconstructed MIE bit
58-
li t2, ~8 // Create mask to clear old MIE bit
59-
and t0, t0, t2 // Clear the current MIE bit
60-
or t0, t0, t1 // Set MIE to pre-trap value (from MPIE)
61-
sw t0, 16*4(%0) // Store in jmp_buf[16]
62-
```
63-
64-
This ensures that tasks resume with correct interrupt state,
51+
For processor state, it performs sophisticated interrupt state reconstruction and ensures that tasks resume with correct interrupt state,
6552
maintaining system responsiveness and preventing interrupt state corruption.
6653

6754
### 2. Select Next Task

arch/riscv/hal.c

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -444,12 +444,11 @@ int32_t hal_context_save(jmp_buf env)
444444
* state from MPIE for consistent interrupt context preservation.
445445
*/
446446
"csrr t0, mstatus\n" /* Read current mstatus (MIE=0 in trap) */
447-
"srli t1, t0, 4\n" /* Shift MPIE (bit 7) to bit 3 pos */
448-
"andi t1, t1, 8\n" /* Isolate the bit (MSTATUS_MIE) */
449-
"li t2, ~8\n" /* Create mask to clear old MIE bit */
450-
"and t0, t0, t2\n" /* Clear the current MIE bit */
451-
"or t0, t0, t1\n" /* Set MIE to its pre-trap value (from MPIE) */
452-
"sw t0, 16*4(%0)\n"
447+
"andi t1, t0, ~8\n" /* Clear MIE bit first */
448+
"srli t2, t0, 4\n" /* Get MPIE bit to position 3 */
449+
"andi t2, t2, 8\n" /* Isolate bit 3 */
450+
"or t1, t1, t2\n" /* Combine cleared MIE with reconstructed bit */
451+
"sw t1, 16*4(%0)\n"
453452
/* By convention, the initial call returns 0. */
454453
"li a0, 0\n"
455454
:

0 commit comments

Comments
 (0)