Mode Transfer
Types of Mode Transfer
- interrupts: hardware events
- also called external interrupt (external to the CPU)
- may preempt exception & syscall handlers
- exceptions: problem caused by current instruction
- may terminate or resume execution depending on the exception
- list of exceptions can be found here
- system calls: requested by user, serviced by kernel
- implemented as software interrupt (can be invoked with
int
instruction)
Mode Transfer Mechanisms
- who executes the interrupt/exception/syscall handler?
- the current running process
- how does this work?
- hardware changes the process's
%rip
to the corresponding kernel handler upon a mode switch
- but how do we know where the process should resume execution if hardware just overwrites the
%rip
?
- what about values in other registers? kernel code may overwrite these values...
- how to ensure that the process can resume correctly?
- kernel must save any register value it may overwrite somewhere (the stack) and restore them as the process returns
- stack is also need for the kernel handler to execute
- can we just use the process's stack?
- who has read/write access to the stack?
- what data might be pushed onto the stack by the kernel?
- any security concerns?
- kernel allocates a separate stack for the process to use upon entering into the kernel
- where might this stack be allocated? kernel accessible memory or user accessible memory?
- hardware switches
%rsp
to point to the kernel stack upon user->kernel mode switch
- hardware & kernel pushes register values onto the kernel stack
- the pushed states together form the trap frame
- what if there are nested traps? how many trap frames will we have?
- why does the hw & kernel both save the registers?
- how may kernel stacks are there? global or per-process?
- how does the hardware know where the kernel handler is and which one to load?
- interrupt vector table/interrupt descriptor table (x86)
- array of handlers set up by the OS, hw understands it
- holds handlers for exceptions, syscall (software interrupt), and (hardware) interrupts
Putting It All Together
- mode switch control flow
- enters the kernel mode, hw saves process's PC & SP, switch to kernel stack, set PC to a kernel handler (from IDT)
- kernel handler pushes the rest of process's states (registers) onto the kernel stack
- handles the specific syscall, exception, or interrupt
- restores most of the process's state (pops off the stack)
- returns back to user mode, hw restores saved PC and stack pointer, process resumes execution
- resumes at PC+1 for syscalls
- resumes at PC for interrupts
- how does the first process start executing in user mode?