Lab 7 Kernel Atlas

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.

user modekernel modehardware / simulatorblocked
About the lecture materialThe 6.191 lecture slides and the Lab 7 handout need an MIT login that I could not use. Lecture references go by the public schedule titles (L16 Operating Systems, L19 Exceptions and I/O, L20 Synchronization), and the concepts are explained from your code, the simulator in sim/Riscv.py, and general knowledge. Exercise numbers come from the comments in the source files.

0The big picture: six ideas that outlive this lab

Read this section first. Sections 1 to 10 are the same ideas applied to your code.

Idea 1 · The kernel is a program that runs only when something traps into it

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 trapCaused byTimingmcause in this labmepc points atResume at
System callThe program runs ecall on purposeSynchronous8The ecall itselfmepc + 4, or it would trap forever
InterruptA device or the timer, unrelated to the current instructionAsynchronous0x80000007 (timer)The instruction that did not get to runmepc, so nothing is skipped
FaultAn illegal instruction or a bad addressSynchronousNot handled: panicThe faulting instructionA 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.

Idea 2 · A process is a saved CPU plus a region of memory

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.

One ProcState, 148 bytes
OffsetFieldHolds
0pcWhere to resume
4 … 124regs[0..30]x1 to x31. regs[i] is register x(i+1)
128vmbaseStart of its physical memory
132vmboundSize of its memory
136pidIndex in the table
140blocked1 while waiting on a semaphore
144program_breakWhere its heap starts
Physical memory, 128 KB per process
0x00000 kernel pid 0 · code, proc_tbl, stack top 0x10000
0x20000 proc1.S pid 1 · prints a message
0x40000 proc2.S pid 2 · spinning cursor
0x60000 proc3.c pid 3 · asks your name
0x80000 proc4.c pid 4 · calculator

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.

Idea 3 · Protection is a check the hardware makes on every memory access

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.

Try it

Translate a user address with base and bound

The check and the add
Where it lands

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.

OperationUser modeKernel mode
Read or write its own memoryYes, through base and boundYes, physical addresses directly
Read or write another process's memoryNo. The address cannot be expressedYes
Write a device register at 0x4000_0000No. Above the boundYes
Write mtvec, mepc, mbase, mboundNoYes
Run mretNo. The simulator reports a bugYes
Be interrupted by the timerYesNo. Interrupts are delivered only in user mode

Idea 4 · A timer makes sharing the CPU involuntary

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.

Model

Context-switch overhead against time-slice length

of the CPU spent switching at a 10,000-instruction slice
instructions a process waits for its next turn

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.

Idea 5 · Devices look like memory, and waiting for them has three styles

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.

Poll (busy-wait)
ready?
→
no: ask again
→
yes: do I/O

Simple and correct. Burns CPU while waiting. Your kputc does this for the display, and user programs do it around read.

Interrupt
do other work
→
device traps
→
handler does I/O

No CPU wasted while waiting. Costs a trap per event and needs a handler. The timer in this lab works this way.

Block the process
mark blocked
→
run others
→
unblock on event

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.

Idea 6 · A semaphore is a counter with a waiting room

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 valuePatternWhat it guarantees
1wait … critical section … signalMutual exclusion: at most one process inside
Nwait before using one of N resourcesAt most N users at once
0A does signal after step X, B does wait before step YOrdering: 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.

1What the lab builds

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
Every arrow into the kernel goes through common_handler. Every arrow out is mret.
FileRoleWhat you wroteLecture
src/kernel.SBoot: stack, mtvec, process table, first mretProvidedL16
src/dispatcher.cProcess table, scheduler, trap and syscall dispatchinit_proc_tblL16
src/handler.SSave registers, call the dispatcher, restore, returnAll of itL19
src/syscalls.cDevice access and semaphoreskputs, kernel _write, syscall_read, three semaphore callsL19, L20
src/libc_stubs.cWhat printf, malloc, getchar stand onUser _writeL16
src/kernel_api.cUser-side wrappers that load a7 and run ecallProvidedL16
user/Four programs and their start fileUncommented the Exercise 5 block in proc3.c

Boot in six steps

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

Why must 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.

Each user program has 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.

2The process table (Exercise 1)

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.

pidvmbasevmboundprogram_breakpcblocked
0 (kernel)0x000000x200000x1000000
10x200000x200000x3000000
20x400000x200000x5000000
30x600000x200000x7000000
40x800000x200000x9000000
A comment that does not match the codeThe header comment in 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

What virtual address does 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.

Why is 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.

Exam style: pid 3 executes lw a0, 0x1234(zero). Which physical address is read?

0x60000 + 0x1234 = 0x61234. The address is below the bound 0x20000, so the access is allowed.

How large is one 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.

3The trap handler (Exercise 2)

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.

Why each line is where it is

RuleWhat breaks otherwise
The slot for register xN is at offset 4·NThe 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 CThe 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 registersThe handler may return to a different process, whose s-registers are different
Switch to kernelSP before the callThe 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 callt0 is caller-saved, and the dispatcher may have changed curProc to the next process
Restore t0 lastIt 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

Why can the handler not simply start with 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.

After 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.

Exam style: a timer interrupt arrives while pid 2 has 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.

What would go wrong if 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.

Why does the handler write 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.

4The dispatcher and the system-call path

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.

The system calls

a7NameArgumentsResult in a0Can switch process?
0x13sys_putsa0 = virtual address of a stringunchangedno
0x14sys_putca0 = characterunchangedno
0x15sys_reada0 = virtual address of a 1-byte buffer0 if a character was stored, −1 if noneno
0x16sys_yieldnoneunchangedalways
0x17sys_semwaita0 = semaphore idunchangedif it blocks
0x18sys_seminita0 = id, a1 = valueunchangedno
0x19sys_semsignala0 = semaphore idunchangedno
0x21sys_getbrknonevirtual address of the heap startno
other−128no

Recall

Why does 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.

How does the user program get -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.

Exam style: pid 2 calls sys_puts with a0 = 0x1040. What address does kputs receive?

0x40000 + 0x1040 = 0x41040.

What does the kernel do with an unknown cause?

panic prints "ABORT: " and the message, writes 1 to 0x40001000, which the simulator treats as a failed exit, and loops.

5Scheduling and the context switch

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 itKindWho decided to give up the CPU
Timer interruptPreemptiveThe kernel. The process did not agree
yield()CooperativeThe process, voluntarily
semwait() on a zero semaphoreBlockingThe process cannot continue until someone signals
What happens if every process is blockedswitch_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 4 is running, pid 1 is blocked, the timer fires. Who runs next?

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.

Only pid 3 is runnable and it calls 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.

Where is the saved state of a process that is not running?

Entirely in its ProcState and in its own memory region. Nothing about it remains in the CPU or on the kernel stack.

What is the one piece of hardware state the dispatcher changes on a switch, apart from registers?

mbase and mbound, through set_vmbase_and_bound. Without that the new process would run with the old process's memory.

6Console output and 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.

In the kernel (built with -DKERNEL)
kprintf / printf
→
libc formatting
→
_write in syscalls.c
→
kputc
→
display register
In a user program
printf
→
libc formatting
→
_write in libc_stubs.c
→
ecall sys_putc
→
kputc
→
display register

Recall

Why can a user program not write to 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.

Why do the same libc sources produce different output paths in kernel and user builds?

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.

Exam style: a user program calls 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.

What is the cost of polling in 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.

7Keyboard input (Exercise 5)

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.

Who waits, and how

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

What are the two possible results of one 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.

How could the kernel avoid the wasted polling traps?

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.

Exam style: pid 3 calls 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.

8Semaphores (Exercise 6)

Blocking turns "keep checking until it is free" into "do not schedule me until it is free". The waiter costs nothing while it waits.

Three design points in your implementation

How the four user programs use semaphore 7

ProcessCallsEffect
proc1.Ssemsignal(7) once at start, then semwait(7), print, semsignal(7) in a loopCreates the first permit. Holds a permit while printing its line
proc2.SnoneThe cursor is never restricted
proc3.csemsignal(7) after each greeting, then five yield()sAdds a permit every time a name is entered
proc4.csemwait(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.

Why no lock protects 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.

pids 1 and 4 both wait on semaphore 0, 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.

A process is woken from 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.

Exam style: semaphore initialised to 1. A and B each run 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.

Exam style: two semaphores s and t, both 1. A does 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.

Why does 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.

9How the lab is tested

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.

TestRuns onYour code under testReplaced by stubsHow it checks
test_proc_tblHost Cinit_proc_tblAll syscalls, set_vmbase_and_boundIncludes dispatcher.c with NUM_PROCS = 10 and compares every field of all ten entries, then the return value
test_handlerSimulatorhandler.SThe dispatcher and the boot codeTwo fake processes with known register patterns. A fake dispatcher checks sp and the cause, wrecks every register, and switches process
test_printSimulatorkputs, both _writes, the full syscall pathUser programCaptures display output and compares it at marker instructions
test_readHost Csyscall_readThe devices, with mmap at the real addressesSets the control and data registers, calls the function, checks the return value and the buffer
test_semsSimulatorThe three semaphore callsFive scripted user programs, interrupts offReads sems, pid_waiting_for, mru and blocked straight out of simulator memory at each checkpoint

The marker-instruction trick

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.

What each test catches

MistakeCaught byHow
Hard-coding five processestest_proc_tblEntries 5 to 9 are checked
Not switching to the kernel stacktest_handlerThe fake dispatcher compares sp with kernelSP (code 99)
Not passing mcause in a0test_handlerThe test sets the cause to 33 and the fake dispatcher expects 33 (code 98)
Missing or misplaced register savetest_handlerProcess 1 has xi = 2i + 2, process 2 has odd values. After the switch the script compares all 31
Not saving mepctest_handlerproc1.pc must equal the address the test put in mepc (code 105)
Not using the dispatcher's return valuetest_handlerExecution must arrive at proc2_ok, then at proc1_ok
_write ignoring len or returning the wrong counttest_printWrites 9 of 14 characters and expects exactly "OctopusOc" and a return of 9
Forgetting va_to_pa in readtest_readThe 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 readytest_readThe buffer is preset to 'X' and must still be 'X'
Incrementing the counter while also waking a waitertest_semsThe sems array is compared with expected values after each step
Not updating mru, or scanning from pid 0test_semsTwo processes wait on one semaphore and the test checks which one wakes
Not calling the scheduler when blockingtest_semsThe 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

Why does the handler test's fake dispatcher overwrite every register before returning?

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.

Why does the semaphore test turn interrupts off?

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.

How can 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 labThe general ideaWhere it continues
Trap: save PC, jump to mtvec, mret backRedirect control and remember where you wereLab 6: an exception in a pipeline annuls the younger instructions and redirects fetch, like a taken branch
mbase and mboundTranslate and check every addressL17–18: page tables and the TLB do the same per page
Polled display and keyboard, timer interruptDevices as addresses, polling against interruptsL19: exceptions and I/O
Semaphores, atomic because interrupts are offCounter plus waiting room, atomicityL20–22: locks, deadlock, and what changes with several processors
Calling convention used by the handler and the wrappersWhich registers a call may destroyL10–15 review: RISC-V assembly and procedures
Know this cold