Kernel Startup and Timers
The focus is on entry.S and start.c, which transitions to supervisor
mode, has timer initialization, and handles timer interrupts in
kernelvec.S
Kernel Startup Process
entry.S
entry.Sis executed in machine mode, which is the highest privilege level.- It sets the stack pointer
spfor each core. - Each core gets its own 4KB stack.
- With
mhartidto determine the core number of 0-7. - jumps to
start()
start.c
- In machine mode,
start()sets themstatusregister to supervisor mode - sets
mepcto point tomain() - ensures
mretwill runmain() - disables paging by setting
satp = 0 - Delegates exceptions and interrupts to supervisor mode.
- Enables interrupts from devices
- Configures memory protection
- initializes timer interrupts with
timerinit() - saves
mhartidintotp - executes
mretto jump to main and get into supervisor mode
Timer Initialization
timerinit() configures the core’s timer with mtimecmp and schedules
the first timer interrupt 1 million cycles later.
- Uses
timer_scratchto storemtimecmpand the timer interval. - writes
timer_scratchtomscratch - sets
mtvectotimervecto point the machine-mode trap handler totimervec - enables machine-mode interrupts
mstatusandmie
Handling Timer Interrupts
After an interrupt happens:
timervecexecutes, savinga1-a3intotimer_scratch- schedules the next timer interrupt at 1 million cycles in the future
- triggers a software interrupt to supervisor mode
- restores saved registers and executes
mret
Supervisor mode
After switching to supervisor mode, the kernel receives a software interrupt, which it recognizes as a timer interrupt, and switches the currently run process.