LeeLin2602
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 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/)

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully