A walkthrough of lab7-yumelody: a small operating system kernel for a RISC-V simulator. It has one trap handler in assembly, a dispatcher and system calls in C, a five-entry process table, polled console I/O, and semaphores. The page starts with the ideas that carry beyond this kernel, then shows each one in your committed code, with flow diagrams of the control path and recall questions.
sim/Riscv.py, and general knowledge. Exercise numbers come from the comments in the source files.Read this section first. Sections 1 to 10 are the same ideas applied to your code.
User code cannot call the kernel. It can only cause a trap. The hardware then switches to kernel mode and jumps to one fixed address the kernel chose in advance.
That single entry point is the whole security model. A process cannot jump into the middle of kernel code with kernel privileges, because the only way to gain privilege is to go through the address in mtvec, and only the kernel can write mtvec.
| Kind of trap | Caused by | Timing | mcause in this lab | mepc points at | Resume at |
|---|---|---|---|---|---|
| System call | The program runs ecall on purpose | Synchronous | 8 | The ecall itself | mepc + 4, or it would trap forever |
| Interrupt | A device or the timer, unrelated to the current instruction | Asynchronous | 0x80000007 (timer) | The instruction that did not get to run | mepc, so nothing is skipped |
| Fault | An illegal instruction or a bad address | Synchronous | Not handled: panic | The faulting instruction | A real OS fixes the cause and retries, or kills the process |
All three use one mechanism. The hardware saves the PC in mepc, records the reason in mcause, raises the privilege level, and jumps to mtvec. mret undoes it. In Lab 6 terms, a trap is an annulment plus a redirect whose target is the handler, with the old PC kept so execution can come back.
If you copy every register and the PC into a struct, the program is frozen. Copy them back and it continues as if nothing happened. A context switch is saving one struct and loading another.
ProcState, 148 bytes| Offset | Field | Holds |
|---|---|---|
| 0 | pc | Where to resume |
| 4 … 124 | regs[0..30] | x1 to x31. regs[i] is register x(i+1) |
| 128 | vmbase | Start of its physical memory |
| 132 | vmbound | Size of its memory |
| 136 | pid | Index in the table |
| 140 | blocked | 1 while waiting on a semaphore |
| 144 | program_break | Where its heap starts |
build-tools/link.sh places each program's image at these addresses in mem.vmh. Every program is linked as if it started at address 0.
x0 is not saved because it is always zero. Nothing else about a process lives in the CPU, so 31 registers and a PC are a complete snapshot.
In user mode every address is compared with a bound and then added to a base. A process cannot name memory outside its region, so it cannot read or damage anything else.
This is base-and-bound translation, the simplest form of virtual memory. Two CSRs, mbase and mbound, hold the current process's region, and only kernel mode can write them. The same program image runs at any physical location because it only ever sees addresses starting at 0. Paging, in Lectures 17 and 18, replaces the single base with a table of them.
| Operation | User mode | Kernel mode |
|---|---|---|
| Read or write its own memory | Yes, through base and bound | Yes, physical addresses directly |
| Read or write another process's memory | No. The address cannot be expressed | Yes |
Write a device register at 0x4000_0000 | No. Above the bound | Yes |
Write mtvec, mepc, mbase, mbound | No | Yes |
Run mret | No. The simulator reports a bug | Yes |
| Be interrupted by the timer | Yes | No. Interrupts are delivered only in user mode |
A process that never makes a system call would keep the CPU forever. A timer interrupt forces a trap at regular intervals, so the kernel always gets control back and can pick someone else.
The length of the time slice is a trade-off. A short slice makes every process feel responsive but spends more of the CPU on saving and restoring registers. A long slice wastes less and makes interactive programs wait.
The simulator raises the timer every 10,000 instructions. handler.S runs about 70 instructions to save and restore, plus the C dispatcher. At that slice the overhead is small, and it grows quickly once the slice gets close to the switch cost.
A device exposes registers at fixed addresses. Reading or writing those addresses talks to the device. The design question is what the CPU does while the device is not ready.
Simple and correct. Burns CPU while waiting. Your kputc does this for the display, and user programs do it around read.
No CPU wasted while waiting. Costs a trap per event and needs a handler. The timer in this lab works this way.
The scheduler skips the waiter completely. Your semaphores do this. A real OS blocks on keyboard reads the same way.
The rule that generalises: polling is fine when the wait is short and known, interrupts or blocking win when the wait is long or unpredictable. The device addresses are the same idea as the MMIO addresses in Lab 6's CacheWrapper, now with a kernel standing between programs and the device.
The count says how many more processes may proceed. wait takes one or goes to sleep. signal gives one back or wakes a sleeper. Both must be atomic.
| Initial value | Pattern | What it guarantees |
|---|---|---|
| 1 | wait … critical section … signal | Mutual exclusion: at most one process inside |
| N | wait before using one of N resources | At most N users at once |
| 0 | A does signal after step X, B does wait before step Y | Ordering: Y happens after X |
In this kernel the two operations are atomic for free. They run inside the trap handler, and the simulator delivers no interrupts in kernel mode, so nothing can run between the test of the counter and the update. On a multiprocessor that is no longer true and the kernel itself needs locks, which is where Lectures 20 to 22 go.
flowchart TB
subgraph U[User mode, base and bound active]
P1[proc1.S] ~~~ P2[proc2.S] ~~~ P3[proc3.c] ~~~ P4[proc4.c]
API[kernel_api.c and libc_stubs.c
syscall wrappers, _write, getchar]
end
subgraph K[Kernel mode]
H[handler.S
common_handler] --> D[dispatcher.c
eh_dispatcher]
D --> S[syscalls.c
kputc kputs read sem*]
D --> T[(proc_tbl)]
B[kernel.S
_start boot]
end
subgraph HW[Simulator sim/Riscv.py]
CSR[mtvec mepc mcause mbase mbound]
DEV[display 0x40000000
keyboard 0x40000100/104]
TMR[timer every 10,000 instructions]
end
API -->|ecall| H
TMR -->|interrupt| H
S --> DEV
H -->|mret| U
common_handler. Every arrow out is mret.| File | Role | What you wrote | Lecture |
|---|---|---|---|
| src/kernel.S | Boot: stack, mtvec, process table, first mret | Provided | L16 |
| src/dispatcher.c | Process table, scheduler, trap and syscall dispatch | init_proc_tbl | L16 |
| src/handler.S | Save registers, call the dispatcher, restore, return | All of it | L19 |
| src/syscalls.c | Device access and semaphores | kputs, kernel _write, syscall_read, three semaphore calls | L19, L20 |
| src/libc_stubs.c | What printf, malloc, getchar stand on | User _write | L16 |
| src/kernel_api.c | User-side wrappers that load a7 and run ecall | Provided | L16 |
| user/ | Four programs and their start file | Uncommented the Exercise 5 block in proc3.c |
The kernel starts the first process with the same instruction it uses to return from every trap. It sets mepc to 0 and runs mret, as if process 1 had trapped at its first instruction. The offsets 128 and 132 are the positions of vmbase and vmbound in the struct, so assembly and C must agree on the layout.
Recall
mtvec be set before the first mret?The first user instruction could already trap, and the timer will fire soon. The hardware jumps to whatever mtvec holds, so it has to hold the handler before any user code runs.
curProc and kernelSP are placed at fixed addresses 0x70 and 0x74. What does lw t0, curProc in the handler read?The pointer stored at that address, which is the address of the current ProcState. The handler runs in kernel mode, so the address is physical and not translated.
li sp, 0x20000 in start.S. Why can all four use the same stack address?It is a virtual address. Each process has a different base, so the four stacks are at physical 0x40000, 0x60000, 0x80000 and 0xa0000, all going downward.
The process table is the kernel's whole knowledge of what is running. Initialising it defines every process's memory and makes each one look like it trapped at address 0 with empty registers.
| pid | vmbase | vmbound | program_break | pc | blocked |
|---|---|---|---|---|---|
| 0 (kernel) | 0x00000 | 0x20000 | 0x10000 | 0 | 0 |
| 1 | 0x20000 | 0x20000 | 0x30000 | 0 | 0 |
| 2 | 0x40000 | 0x20000 | 0x50000 | 0 | 0 |
| 3 | 0x60000 | 0x20000 | 0x70000 | 0 | 0 |
| 4 | 0x80000 | 0x20000 | 0x90000 | 0 | 0 |
program_break is the midpoint of the region, stored as a physical address. The formula is base plus half the bound.syscall_getbrk converts it to a virtual address with pa_to_va, so every process sees 0x10000. _sbrk in libc_stubs.c asks once and then grows the heap upward, while the stack grows downward from 0x20000.&proc_tbl[1]. Entry 0 describes the kernel and is never scheduled.NUM_PROCS, not the number 5. The test compiles the file with NUM_PROCS set to 10.dispatcher.c lists pid 1 as the rotating cursor and pid 2 as the message printer. The files are the other way round: user/proc1.S prints "Hello from Proc1!" and user/proc2.S draws the cursor.Recall
malloc's first block start near in every user process, and why is it the same for all?0x10000. The break is base + 0x10000 physically, and syscall_getbrk subtracts the base before returning it.
pc = 0 the right initial value for every process?Each program is linked at address 0 with _start in .text.init first. The PC is virtual, so 0 means the first instruction of that process's own image.
lw a0, 0x1234(zero). Which physical address is read?0x60000 + 0x1234 = 0x61234. The address is below the bound 0x20000, so the access is allowed.
ProcState, and which test depends on that number?4 + 31×4 + 5×4 = 148 bytes. tests/sems/run.py computes the same size to find the blocked field of each entry in simulator memory.
The handler must save the interrupted program's registers without using any register first. It has exactly one scratch location that is not a general register, and that is enough.
When a trap arrives, all 31 registers belong to the user program. The handler needs one register to hold the address of the save area, but loading that address would destroy a user value. The CSR mscratch breaks the circle: park t0 there, use t0 as the pointer, and store the parked value last.
| Rule | What breaks otherwise |
|---|---|
| The slot for register xN is at offset 4·N | The dispatcher reads arguments as regs[REG_a0], which is regs[9] at offset 40. A different layout hands the kernel the wrong values |
| Save everything before calling C | The compiler assumes it may overwrite every caller-saved register. The user program made no call, so it expects none of them to change |
| Save even callee-saved registers | The handler may return to a different process, whose s-registers are different |
Switch to kernelSP before the call | The user stack pointer is a virtual address and may be garbage. Kernel code must not trust it or write through it |
Reload curProc after the call | t0 is caller-saved, and the dispatcher may have changed curProc to the next process |
Restore t0 last | It is the base pointer for every other load |
The handler never mentions the kernel stack again on the way out. The kernel keeps nothing on its stack between traps, so every trap starts from the same kernelSP. The saved state lives in the process table, not on a stack.
Recall
lw t0, curProc?That overwrites the user's t0 before it has been saved. The value would be lost and the program would resume with a wrong register.
call eh_dispatcher, which registers still hold what the handler put there?Only callee-saved ones and sp, and the handler uses none of them for its own data. That is why it reloads t0 from curProc and takes the next PC from the return value in a0.
a0 = 5. The handler returns to pid 3. Where is the 5?In proc_tbl[2].regs[9], at physical offset 40 inside pid 2's entry. It is loaded back into a0 the next time the handler returns to pid 2.
mepc were not copied into curProc->pc?The dispatcher returns curProc->pc as the resume address. A stale value would restart the process somewhere it had already been. For a syscall, pc += 4 would also be applied to the wrong number.
a0 into mepc instead of leaving mepc alone?The next process to run may be different, with its own PC, and a syscall must resume one instruction later. The dispatcher decides and reports the address.
A system call is a function call across a privilege boundary. Arguments go in registers, a number selects the function, and the result comes back by editing the saved registers.
Every handler function has the same shape: take the current process, return the process to run next. Returning the same pointer means "resume the caller". Returning a different one is a context switch. The three lines at the bottom then make that process current, install its memory region, and hand its PC to the assembly.
a7 | Name | Arguments | Result in a0 | Can switch process? |
|---|---|---|---|---|
| 0x13 | sys_puts | a0 = virtual address of a string | unchanged | no |
| 0x14 | sys_putc | a0 = character | unchanged | no |
| 0x15 | sys_read | a0 = virtual address of a 1-byte buffer | 0 if a character was stored, −1 if none | no |
| 0x16 | sys_yield | none | unchanged | always |
| 0x17 | sys_semwait | a0 = semaphore id | unchanged | if it blocks |
| 0x18 | sys_seminit | a0 = id, a1 = value | unchanged | no |
| 0x19 | sys_semsignal | a0 = semaphore id | unchanged | no |
| 0x21 | sys_getbrk | none | virtual address of the heap start | no |
| other | −128 | no |
curProc->regs[REG_a0]. The restore path then loads that into the real a0. From the user's side, ecall behaved like an instruction that changed a0.kputs((char*) va_to_pa(curProc, curProc->regs[REG_a0])).dispatcher.h defines is_valid_va, and the syscalls in this lab do not call it. A user program could pass an address that translates into another process's memory. A real kernel validates every user pointer before using it.Recall
eh_dispatcher add 4 to the PC for a syscall and not for a timer interrupt?mepc for an ecall is the address of the ecall, which has done its job. Returning there would trap again forever. For an interrupt, mepc is an instruction that has not run yet and must not be skipped.
-1 back from read?syscall_read stores −1 in curProc->regs[REG_a0]. The handler's restore path loads it into a0, and the wrapper does mv out, a0 after the ecall.
REG_a0 is 9 although a0 is x10. Why?regs has no slot for x0, so regs[i] holds x(i+1). REG_idx(i) is i - 1.
sys_puts with a0 = 0x1040. What address does kputs receive?0x40000 + 0x1040 = 0x41040.
panic prints "ABORT: " and the message, writes 1 to 0x40001000, which the simulator treats as a failed exit, and loops.
The scheduler is one small function that answers "who runs next?". Everything else about a context switch is already done by the trap handler saving into one struct and restoring from another.
This is round-robin: the next pid in order, wrapping from 4 back to 1, skipping any process whose blocked flag is set. It is called from three places: the timer interrupt, sys_yield, and a semwait that has to block.
| What triggers it | Kind | Who decided to give up the CPU |
|---|---|---|
| Timer interrupt | Preemptive | The kernel. The process did not agree |
yield() | Cooperative | The process, voluntarily |
semwait() on a zero semaphore | Blocking | The process cannot continue until someone signals |
switch_to_next_proc calls itself until it finds a runnable process. If pids 1 to 4 are all blocked it never finds one, and the recursion runs until the kernel stack overflows. That situation is a deadlock: every process is waiting for a signal that only another waiting process could send.Recall
pid 2. Next pid would be 5, which wraps to 1. pid 1 is blocked, so the function recurses from pid 1 and returns pid 2.
yield(). What happens?The search goes 4, 1, 2 (all blocked) and comes back to 3, which is not blocked. pid 3 continues after its ecall.
Entirely in its ProcState and in its own memory region. Nothing about it remains in the CPU or on the kernel stack.
mbase and mbound, through set_vmbase_and_bound. Without that the new process would run with the old process's memory.
printf (Exercises 3–4)A library function like printf ends in one small routine that knows how to emit bytes. Swap that routine and the same library works in the kernel and in user programs.
-DKERNEL)0x40000000 returns the display's status. The top bit set means ready. The simulator holds one pending character and prints it after 20 to 50 more instructions, so the loop in kputc really does spin.kputs stops at the terminating zero. _write is given a length and must not look for a zero, because printf passes buffers that are not terminated. The print test checks that exactly len characters come out._write makes one trap per character. That is roughly 70 handler instructions plus the dispatcher for every byte. A sys_puts style call passes a whole buffer in one trap. Batching work per crossing is a general rule for any expensive boundary.unsigned char stops a byte above 127 from being sign-extended into a negative argument.Recall
0x40000000 directly?In user mode the address is compared with the bound, 0x20000. The simulator reports the access as out of range. Only kernel mode can write the device addresses.
The kernel is compiled with -DKERNEL, which removes the user _write in libc_stubs.c and leaves the one in syscalls.c. User programs link libc_stubs.c without the flag.
printf("hi\n") with buffering disabled. How many traps occur?Three, one sys_putc per character, assuming libc hands _write the three bytes. Each trap saves and restores all 31 registers.
kputc, and who pays it?The CPU spins inside the kernel until the display is ready. No other process can run during that time, because interrupts are not delivered in kernel mode.
A non-blocking call answers immediately with either the data or "nothing yet". The caller decides whether to retry, do something else, or give up the CPU.
a0 is used twice: on the way in it is the buffer's virtual address, on the way out it is the status. The address must be read before it is overwritten.va_to_pa. Writing through the raw virtual address would hit kernel memory at that low address.proc3.c loops on while (read(buf+i) == -1); and getchar in libc_stubs.c does the same. This is polling from user space: each failed attempt is a full trap, and the process uses its whole time slice asking. The timer still preempts it, so the other processes keep running, which is why the cursor keeps spinning while the name prompt waits.
Recall
read call and what does each leave in the buffer?0 with the new character stored in the buffer, or −1 with the buffer untouched. The read test checks both, including that the buffer still holds its old value on −1.
Block the reader: mark it blocked, switch away, and unblock it from a keyboard interrupt handler when a key arrives. The simulator defines a keyboard interrupt code, and this kernel's dispatcher does not handle it.
read with a0 = 0x10008 and a key 'q' is waiting. What memory changes?The byte at physical 0x70008 becomes 'q', and proc_tbl[3].regs[9] becomes 0.
Blocking turns "keep checking until it is free" into "do not schedule me until it is free". The waiter costs nothing while it waits.
semsignal wakes it and does not increment the counter. The woken process does not decrement either: its PC was already advanced past the ecall, so it simply continues. The permit passes straight from signaller to waiter. Incrementing and also waking would create a permit out of nothing.mru. The search for a waiter starts one past the most recently unblocked pid. With two waiters on the same semaphore they are woken in turn. Always scanning from pid 0 would let a low pid starve a high one.semsignal returns curProc. The woken process becomes runnable and waits for the scheduler to reach it.| Process | Calls | Effect |
|---|---|---|
| proc1.S | semsignal(7) once at start, then semwait(7), print, semsignal(7) in a loop | Creates the first permit. Holds a permit while printing its line |
| proc2.S | none | The cursor is never restricted |
| proc3.c | semsignal(7) after each greeting, then five yield()s | Adds a permit every time a name is entered |
| proc4.c | semwait(7), run one calculation, semsignal(7) | Holds a permit for a whole prompt-and-answer exchange |
Because proc3 signals without ever waiting, the count is not kept at 0 or 1. Semaphore 7 here is a counter of permits, not a strict lock. The flow shows the value reaching 2.
sems[]The check sems[sem_id] > 0 and the decrement must not be separated by another process's semwait, or two processes could both take the last permit. Here nothing can interleave: the code runs in kernel mode on one CPU with interrupts not delivered. This is the simplest way to make an operation atomic, and it stops working with more than one processor.Recall
sems[3] = 0, nobody waiting. pid 2 calls semsignal(3), then pid 4 calls semwait(3). Does pid 4 block?No. The signal finds no waiter and raises the count to 1. The wait finds 1, lowers it to 0, and returns. A semaphore remembers signals that arrive early.
mru = 1. Who does the next semsignal(0) wake?pid 4. The scan order is 2, 3, 4, 0, 1 and pid 4 is the first waiter found. Afterwards mru = 4, so the following signal reaches pid 1 first.
semwait. Where does it resume, and is the counter decremented?At the instruction after its ecall, because the dispatcher added 4 to its PC before calling syscall_semwait. The counter is not touched. The signal that woke it was consumed by the wake-up.
wait; x = x + 1; signal once. Can the final x be wrong?No. The first to wait takes the count to 0, the second blocks until the first signals, so the two updates cannot interleave. This is the mutual-exclusion pattern.
wait(s); wait(t). B does wait(t); wait(s). What can go wrong?Deadlock. A holds s and waits for t while B holds t and waits for s. In this kernel both become blocked, and if no other process can run, switch_to_next_proc recurses without end. Taking locks in one global order prevents it.
semwait return switch_to_next_proc(curProc) when it blocks?The caller cannot continue, so the kernel must run someone else. Returning curProc would resume a process that is marked blocked.
Each test isolates one piece by replacing everything around it with a stub, then checks the piece against state the test controls. Two tests run your C code natively on the host, three run it in the RISC-V simulator.
| Test | Runs on | Your code under test | Replaced by stubs | How it checks |
|---|---|---|---|---|
| test_proc_tbl | Host C | init_proc_tbl | All syscalls, set_vmbase_and_bound | Includes dispatcher.c with NUM_PROCS = 10 and compares every field of all ten entries, then the return value |
| test_handler | Simulator | handler.S | The dispatcher and the boot code | Two fake processes with known register patterns. A fake dispatcher checks sp and the cause, wrecks every register, and switches process |
| test_print | Simulator | kputs, both _writes, the full syscall path | User program | Captures display output and compares it at marker instructions |
| test_read | Host C | syscall_read | The devices, with mmap at the real addresses | Sets the control and data registers, calls the function, checks the return value and the buffer |
| test_sems | Simulator | The three semaphore calls | Five scripted user programs, interrupts off | Reads sems, pid_waiting_for, mru and blocked straight out of simulator memory at each checkpoint |
The simulator tests need the program to tell the test script "check now". They do it by executing a word that is not a valid instruction, such as .word 0xabcdef02, with a code in x31. The simulator reports a bug, the Python script recognises the word, runs the check for that code, advances the PC by 4, and continues.
| Mistake | Caught by | How |
|---|---|---|
| Hard-coding five processes | test_proc_tbl | Entries 5 to 9 are checked |
| Not switching to the kernel stack | test_handler | The fake dispatcher compares sp with kernelSP (code 99) |
Not passing mcause in a0 | test_handler | The test sets the cause to 33 and the fake dispatcher expects 33 (code 98) |
| Missing or misplaced register save | test_handler | Process 1 has xi = 2i + 2, process 2 has odd values. After the switch the script compares all 31 |
Not saving mepc | test_handler | proc1.pc must equal the address the test put in mepc (code 105) |
| Not using the dispatcher's return value | test_handler | Execution must arrive at proc2_ok, then at proc1_ok |
_write ignoring len or returning the wrong count | test_print | Writes 9 of 14 characters and expects exactly "OctopusOc" and a return of 9 |
Forgetting va_to_pa in read | test_read | The buffer is mapped only at the translated address, so the raw one faults and the signal handler prints a hint |
| Writing the buffer when no key is ready | test_read | The buffer is preset to 'X' and must still be 'X' |
| Incrementing the counter while also waking a waiter | test_sems | The sems array is compared with expected values after each step |
Not updating mru, or scanning from pid 0 | test_sems | Two processes wait on one semaphore and the test checks which one wakes |
| Not calling the scheduler when blocking | test_sems | The script watches for the PC reaching switch_to_next_proc |
make test runs test_all.py, which reads the five names from test_info.yml. make run builds everything, links the images with link.sh, and starts sim/run.py keyboard so you can type at the running system.
Recall
To prove the handler restores from the saved struct and not from whatever happens to be left in the registers. A handler that skipped a register would pass by luck otherwise.
To make the order of events exact. With the timer off, processes switch only at yield and at a blocking semwait, so the script knows which checkpoint must come next.
test_read run kernel code on the host when the code dereferences 0x40000100?The test maps a page of ordinary memory at 0x40000000 with mmap and MAP_FIXED, then writes the control and data values there itself.
| In this lab | The general idea | Where it continues |
|---|---|---|
Trap: save PC, jump to mtvec, mret back | Redirect control and remember where you were | Lab 6: an exception in a pipeline annuls the younger instructions and redirects fetch, like a taken branch |
mbase and mbound | Translate and check every address | L17–18: page tables and the TLB do the same per page |
| Polled display and keyboard, timer interrupt | Devices as addresses, polling against interrupts | L19: exceptions and I/O |
| Semaphores, atomic because interrupts are off | Counter plus waiting room, atomicity | L20–22: locks, deadlock, and what changes with several processors |
| Calling convention used by the handler and the wrappers | Which registers a call may destroy | L10–15 review: RISC-V assembly and procedures |
mepc, mcause, privilege, jump to mtvec. What mret does.ProcState layout and why offset 4·N holds register xN.mscratch, why it switches stacks, why it reloads curProc and restores t0 last.va_to_pa.