# 2. Context Switch 和 Interrupt Handler ## Context Switch ### 我們先寫一個 sys.s ```riscv= # ============ MACRO ================== .macro ctx_save base sd ra, 0(\base) sd sp, 8(\base) sd s0, 16(\base) sd s1, 24(\base) sd s2, 32(\base) sd s3, 40(\base) sd s4, 48(\base) sd s5, 56(\base) sd s6, 64(\base) sd s7, 72(\base) sd s8, 80(\base) sd s9, 88(\base) sd s10, 96(\base) sd s11, 104(\base) .endm .macro ctx_load base ld ra, 0(\base) ld sp, 8(\base) # sp ld s0, 16(\base) ld s1, 24(\base) ld s2, 32(\base) ld s3, 40(\base) ld s4, 48(\base) ld s5, 56(\base) ld s6, 64(\base) ld s7, 72(\base) ld s8, 80(\base) ld s9, 88(\base) ld s10, 96(\base) ld s11, 104(\base) .endm # ============ Macro END ================== # Context switch # # void sys_switch(struct context *old, struct context *new); # # Save current registers in old. Load from new. .globl sys_switch .align 4 sys_switch: ctx_save a0 # a0 => struct context *old ctx_load a1 # a1 => struct context *new ret ``` 邏輯很簡單,兩個 macro,一個將資料從 register 寫入記憶體,另一個讀出來。 由於我們在 64 bit 處理器下,因此是使用 sd 和 ld(load double words),我一開始照辦了陳鍾誠教授的 32 bit OS,寫成了 sw 和 lw,就錯了。 ### 然後寫一個 sys.h ```c= #define reg_t uint64_t extern void sys_switch(); struct context { reg_t ra; reg_t sp; // callee-saved reg_t s0; reg_t s1; reg_t s2; reg_t s3; reg_t s4; reg_t s5; reg_t s6; reg_t s7; reg_t s8; reg_t s9; reg_t s10; reg_t s11; }; ``` ### os.c ```c= #include "printf.h" #include "mem.h" #include "sys.h" #define STACK_SIZE 1024 __attribute__((aligned(16))) reg_t task0_stack[STACK_SIZE]; struct context ctx_os; struct context ctx_task; void user_task0(void) { printf("Task0: Context Switch Success !\n"); sys_switch(&ctx_task, &ctx_os); } int os_main(void) { page_init(); printf("OS start\n"); ctx_task.ra = (reg_t) user_task0; ctx_task.sp = (reg_t) &task0_stack[STACK_SIZE - 1]; printf("ctx_task = 0x%x\n", &ctx_task); sys_switch(&ctx_os, &ctx_task); printf("OS Loop\n"); while(1); return 0; } ``` #### 執行結果 ![](https://hackmd.io/_uploads/S1ISM6U-a.png) ## Time Interrupt ### sys.s 修改 sys.s 為下: ```riscv= # ============ MACRO ================== .macro ctx_save base sd ra, 0(\base) sd sp, 8(\base) sd s0, 16(\base) sd s1, 24(\base) sd s2, 32(\base) sd s3, 40(\base) sd s4, 48(\base) sd s5, 56(\base) sd s6, 64(\base) sd s7, 72(\base) sd s8, 80(\base) sd s9, 88(\base) sd s10, 96(\base) sd s11, 104(\base) .endm .macro ctx_load base ld ra, 0(\base) ld sp, 8(\base) # sp ld s0, 16(\base) ld s1, 24(\base) ld s2, 32(\base) ld s3, 40(\base) ld s4, 48(\base) ld s5, 56(\base) ld s6, 64(\base) ld s7, 72(\base) ld s8, 80(\base) ld s9, 88(\base) ld s10, 96(\base) ld s11, 104(\base) .endm .macro reg_save base # save the registers. sd ra, 0(\base) sd sp, 8(\base) sd gp, 16(\base) sd tp, 24(\base) sd t0, 32(\base) sd t1, 40(\base) sd t2, 48(\base) sd s0, 56(\base) sd s1, 64(\base) sd a0, 72(\base) sd a1, 80(\base) sd a2, 88(\base) sd a3, 96(\base) sd a4, 104(\base) sd a5, 112(\base) sd a6, 120(\base) sd a7, 128(\base) sd s2, 136(\base) sd s3, 144(\base) sd s4, 152(\base) sd s5, 160(\base) sd s6, 168(\base) sd s7, 176(\base) sd s8, 184(\base) sd s9, 192(\base) sd s10, 200(\base) sd s11, 208(\base) sd t3, 216(\base) sd t4, 224(\base) sd t5, 232(\base) sd t6, 240(\base) .endm .macro reg_load base # restore registers. ld ra, 0(\base) ld sp, 8(\base) ld gp, 16(\base) # not this, in case we moved CPUs: ld tp, 24(\base) ld t0, 32(\base) ld t1, 40(\base) ld t2, 48(\base) ld s0, 56(\base) ld s1, 64(\base) ld a0, 72(\base) ld a1, 80(\base) ld a2, 88(\base) ld a3, 96(\base) ld a4, 104(\base) ld a5, 112(\base) ld a6, 120(\base) ld a7, 128(\base) ld s2, 136(\base) ld s3, 144(\base) ld s4, 152(\base) ld s5, 160(\base) ld s6, 168(\base) ld s7, 176(\base) ld s8, 184(\base) ld s9, 192(\base) ld s10, 200(\base) ld s11, 208(\base) ld t3, 216(\base) ld t4, 224(\base) ld t5, 232(\base) ld t6, 240(\base) .endm # ============ Macro END ================== # Context switch # # void sys_switch(struct context *old, struct context *new); # # Save current registers in old. Load from new. .globl sys_switch .align 4 sys_switch: ctx_save a0 # a0 => struct context *old ctx_load a1 # a1 => struct context *new ret .align 4 .global sys_timer sys_timer: # Save the context addi sp, sp, -256 reg_save sp # call the C timer_handler(reg_t epc, reg_t cause) csrr a0, mepc csrr a1, mcause call timer_handler # timer_handler will return the return address via a0. csrw mepc, a0 # Restore the context reg_load sp addi sp, sp, 256 mret # back to interrupt location (pc=mepc) ``` 注意 timer interrupt 發生時需要儲存 context 資訊。 ### 新增一個 time.h ```c= #include "sys.h" #include "printf.h" #define CLINT 0x2000000 #define CLINT_MTIMECMP(hartid) (CLINT + 0x4000 + 4*(hartid)) #define CLINT_MTIME (CLINT + 0xBFF8) // cycles since boot. // which hart (core) is this? static inline reg_t r_mhartid() { reg_t x; asm volatile("csrr %0, mhartid" : "=r" (x) ); return x; } // Machine Status Register, mstatus #define MSTATUS_MPP_MASK (3 << 11) // previous mode. #define MSTATUS_MPP_M (3 << 11) #define MSTATUS_MPP_S (1 << 11) #define MSTATUS_MPP_U (0 << 11) #define MSTATUS_MIE (1 << 3) // machine-mode interrupt enable. static inline reg_t r_mstatus() { reg_t x; asm volatile("csrr %0, mstatus" : "=r" (x) ); return x; } static inline void w_mstatus(reg_t x) { asm volatile("csrw mstatus, %0" : : "r" (x)); } // machine exception program counter, holds the // instruction address to which a return from // exception will go. static inline void w_mepc(reg_t x) { asm volatile("csrw mepc, %0" : : "r" (x)); } static inline reg_t r_mepc() { reg_t x; asm volatile("csrr %0, mepc" : "=r" (x)); return x; } // Machine Scratch register, for early trap handler static inline void w_mscratch(reg_t x) { asm volatile("csrw mscratch, %0" : : "r" (x)); } // Machine-mode interrupt vector static inline void w_mtvec(reg_t x) { asm volatile("csrw mtvec, %0" : : "r" (x)); } // Machine-mode Interrupt Enable #define MIE_MEIE (1 << 11) // external #define MIE_MTIE (1 << 7) // timer #define MIE_MSIE (1 << 3) // software static inline reg_t r_mie() { reg_t x; asm volatile("csrr %0, mie" : "=r" (x) ); return x; } static inline void w_mie(reg_t x) { asm volatile("csrw mie, %0" : : "r" (x)); } reg_t timer_handler(reg_t epc, reg_t cause); void timer_init(); ``` ### 增加一個 timer.c ```c= #include "timer.h" #include <stdint.h> #define interval 10000000 // cycles; about 1 second in qemu. void timer_init() { // each CPU has a separate source of timer interrupts. int id = r_mhartid(); // ask the CLINT for a timer interrupt. *(reg_t*)CLINT_MTIMECMP(id) = *(reg_t*)CLINT_MTIME + interval; // set the machine-mode trap handler. w_mtvec((reg_t)sys_timer); // enable machine-mode interrupts. w_mstatus(r_mstatus() | MSTATUS_MIE); // enable machine-mode timer interrupts. w_mie(r_mie() | MIE_MTIE); } static int timer_count = 0; reg_t timer_handler(reg_t epc, reg_t cause) { reg_t return_pc = epc; // disable machine-mode timer interrupts. w_mie(~((~r_mie()) | (1 << 7))); printf("timer_handler: %d\n", ++timer_count); int id = r_mhartid(); *(reg_t *)CLINT_MTIMECMP(id) = *(reg_t *)CLINT_MTIME + interval; // enable machine-mode timer interrupts. w_mie(r_mie() | MIE_MTIE); return return_pc; } ``` ### 最後修改我們的 os.c ```c= #include "printf.h" #include "mem.h" #include "sys.h" #define STACK_SIZE 1024 __attribute__((aligned(16))) reg_t task0_stack[STACK_SIZE]; struct context ctx_os; struct context ctx_task; void delay(volatile int count) { count *= 50000; while (count--) { asm volatile ("nop"); } } void user_task0(void) { printf("Task0: Context Switch Success !\n"); sys_switch(&ctx_task, &ctx_os); } int os_main(void) { page_init(); timer_init(); printf("OS start\n"); ctx_task.ra = (reg_t) user_task0; ctx_task.sp = (reg_t) &task0_stack[STACK_SIZE - 1]; printf("ctx_task = 0x%x\n", &ctx_task); sys_switch(&ctx_os, &ctx_task); while(1) { printf("OS Loop\n"); delay(1000); /* int count = 50000 * 1000; */ /* while (count--); */ }; return 0; } ``` ### 運行結果 ![](https://hackmd.io/_uploads/B1eQ6RIbT.png) ## Trap Handler ### 修改 sys.s ```riscv= .global trap_vector trap_vector: # Save the context addi sp, sp, -256 reg_save sp # call the C timer_handler(reg_t epc, reg_t cause) csrr a0, mepc csrr a1, mcause call trap_handler # timer_handler will return the return address via a0. csrw mepc, a0 # Restore the context reg_load sp addi sp, sp, 256 mret # back to interrupt location (pc=mepc) ``` ### 修改 trap.h ``` #include "printf.h" #include "riscv.h" #include "timer.h" // Machine Status Register, mstatus #define MSTATUS_MPP_MASK (3 << 11) // previous mode. #define MSTATUS_MPP_M (3 << 11) #define MSTATUS_MPP_S (1 << 11) #define MSTATUS_MPP_U (0 << 11) #define MSTATUS_MIE (1 << 3) // machine-mode interrupt enable. // Machine-mode Interrupt Enable #define MIE_MEIE (1 << 11) // external #define MIE_MTIE (1 << 7) // timer #define MIE_MSIE (1 << 3) // software extern void trap_vector(); // Machine-mode interrupt vector static inline void w_mtvec(reg_t x) { asm volatile("csrw mtvec, %0" : : "r" (x)); } static inline reg_t r_mstatus() { reg_t x; asm volatile("csrr %0, mstatus" : "=r" (x) ); return x; } static inline void w_mstatus(reg_t x) { asm volatile("csrw mstatus, %0" : : "r" (x)); } void trap_init(); ``` ### 修改 trap.c ```c= #include "trap.h" void trap_init() { // set the machine-mode trap handler. w_mtvec((reg_t)trap_vector); // enable machine-mode interrupts. w_mstatus(r_mstatus() | MSTATUS_MIE); } reg_t trap_handler(reg_t epc, reg_t cause) { reg_t return_pc = epc; reg_t cause_code = cause & 0xfff; /* printf("0x%x", cause); */ if (cause & 0x8000000000000000LL) { /* Asynchronous trap - interrupt */ switch (cause_code) { case 3: printf("software interruption!\n"); break; case 7: /* printf("timer interruption!\n"); */ // disable machine-mode timer interrupts. w_mie(~((~r_mie()) | (1 << 7))); timer_handler(); // enable machine-mode timer interrupts. w_mie(r_mie() | MIE_MTIE); break; case 11: printf("external interruption!\n"); break; default: printf("unknown async exception!\n"); break; } } else { /* Synchronous trap - exception */ printf("Sync exceptions: "); switch (cause_code) { case 2: printf("Illegal instruction!\n"); break; case 5: printf("Fault load!\n"); break; case 7: printf("Fault store!\n"); break; default: /* Synchronous trap - exception */ printf("Sync exceptions! cause code: %d\n", cause_code); break; } /* return_pc += 2; */ while(1) {} } return return_pc; } ``` ### 修改 time.h ```c= #include "sys.h" #include "printf.h" #define CLINT 0x2000000 #define CLINT_MTIMECMP(hartid) (CLINT + 0x4000 + 4*(hartid)) #define CLINT_MTIME (CLINT + 0xBFF8) // cycles since boot. // which hart (core) is this? static inline reg_t r_mhartid() { reg_t x; asm volatile("csrr %0, mhartid" : "=r" (x) ); return x; } // Machine Scratch register, for early trap handler static inline void w_mscratch(reg_t x) { asm volatile("csrw mscratch, %0" : : "r" (x)); } // Machine-mode Interrupt Enable #define MIE_MEIE (1 << 11) // external #define MIE_MTIE (1 << 7) // timer #define MIE_MSIE (1 << 3) // software static inline reg_t r_mie() { reg_t x; asm volatile("csrr %0, mie" : "=r" (x) ); return x; } static inline void w_mie(reg_t x) { asm volatile("csrw mie, %0" : : "r" (x)); } void timer_init(); void timer_handler(); ``` ### 修改 time.c ```c= #include "timer.h" #include <stdint.h> reg_t timer_scratch[1024][5]; #define interval 10000000 // cycles; about 1 second in qemu. void timer_init() { // each CPU has a separate source of timer interrupts. int id = r_mhartid(); // ask the CLINT for a timer interrupt. // int interval = 1000000; // cycles; about 1/10th second in qemu. *(reg_t *)(uintptr_t)CLINT_MTIMECMP(id) = *(reg_t *)(uintptr_t)CLINT_MTIME + interval; // prepare information in scratch[] for timervec. // scratch[0..2] : space for timervec to save registers. // scratch[3] : address of CLINT MTIMECMP register. // scratch[4] : desired interval (in cycles) between timer interrupts. reg_t *scratch = &timer_scratch[id][0]; scratch[3] = CLINT_MTIMECMP(id); scratch[4] = interval; w_mscratch((reg_t)scratch); // enable machine-mode timer interrupts. w_mie(r_mie() | MIE_MTIE); } static int timer_count = 0; void timer_handler() { printf("timer_handler: %d\n", ++timer_count); int id = r_mhartid(); *(reg_t *)(uintptr_t)CLINT_MTIMECMP(id) = *(reg_t *)(uintptr_t)CLINT_MTIME + interval; } ``` ### 修改 os.c ```c= #include "printf.h" #include "mem.h" #include "time.h" #include "trap.h void delay(volatile int count) { count *= 50000; while (count--) { asm volatile ("nop"); } } int os_main(void) { page_init(); trap_init(); timer_init(); printf("OS start\n"); while(1) { printf("OS Loop\n"); delay(1000); }; return 0; } ``` ### 運行結果 ![](https://hackmd.io/_uploads/rkozrfPb6.png) ## 參考資料 1. ChatGPT 2. [Tsung-Han Liu 助教](https://github.com/zonghan0904) 3. [cccriscv/mini-riscv-os](https://github.com/cccriscv/mini-riscv-os/) 4. [xv6-riscv](https://github.com/mit-pdos/xv6-riscv/)