topic: kernel ~= three handlers

  * kernel ~= 3 handlers
    -- interrupt handlers
       respond to asynchronous events from hardware (e.g., timer, I/O).
    -- exception handlers
       handle synchronous faults triggered by the current instruction (e.g., pag
e fault).
    -- syscall handlers
       handle controlled entry from user space to request kernel services.

  a) interrupts

    Q: How does a CPU know what to execute when an interrupt is triggered?
    A: RISC-V register: mtvec

    Q: How does the kernel know which interrupt has been triggered?
    A: RISC-V register: mcause

    Q: how it works?
       [draw a cpu + memory]
       - cpu running a proc
       - timer interrupt (when? mtime > mtimecmp)
       - CPU jump to the handler (where? mtvec)
       - switch to the kernel space
       - execute interrupt handler
       - return (where? mepc)

  b) exceptions

    CPU: "I don't know how to process".

    Show trap reason table:
    https://naizhengtan.github.io/26spring/docs/intr_excp_table.pdf

    Q: ask students which exception the examples will trigger

    Examples:
      * read/write invalid memory
      * run invalid instructions
      * run privileged instructions in unprivileged mode

    These are synchronized traps.

    Q: how does the exception works on RISC-V CPUs?
       Similar to interrupts.
       Again, mtvec, mcause, mepc,

    Q: if the same, how to tell exceptions from interrupts?
       Check the first bit of mcause.

  c) syscalls

    Interfaces for user applications to "talk" to kernel.
    Multiple design questions for kernel developers (you):

    Q1: How does an application trap into the kernel?

      // Kernel has a function proc_yield().
      // A user app which is another program want to call proc_yield().
      // How to do this?
      Answer: an instruction, "ecall"

    Q2: How does the kernel determine the operation requested by the application
?
    That is, what information is required to handle a system call?

      // Syscall type
      // Syscall arguments
      // Syscall return value

    Q3: Where is this information stored?

      // registers?
      // stacks?
      // well-known memory places?

  d) OTHER CHANELS TO KERNEL (not covered here):
      proc filesystem (and sys filesystem)
      ioctl (for device drivers)
Machine exception registers: mtvec, mcause, mepc