Lectures 16 to 19 of 6.191: operating systems, virtual memory, exceptions and I/O. The page starts with five ideas that explain most of the material, then goes lecture by lecture with flow diagrams, calculators and recall questions. Code is quoted from your Lab 7 kernel where it shows an idea in practice. For the lab itself see Lab 7. For the pipeline these mechanisms attach to, see Lab 6.
Each program believes it owns the processor, the memory and the devices. The kernel maintains those three illusions, and every one of them is built on the same hardware mechanism: stop the program, jump into the kernel, come back later.
| The program believes | What is really true | How the kernel gets control | What the kernel does |
|---|---|---|---|
| "I run continuously on my own CPU" | Many processes take turns on one CPU | Timer interrupt | Save registers, pick another process, restore its registers |
| "I have all of memory, starting at address 0" | Each process has a private slice of physical memory | Fault on a bad or unmapped address | Set up the translation, or kill the process |
| "I can print and read keys" | Only the kernel may touch devices | System call (ecall) | Do the I/O on the program's behalf |
All three rows enter the kernel the same way. That entry is the trap, and Lecture 16 and Lecture 19 are both about it.
A program never names physical memory. It names a virtual address, and a table that only the kernel can edit turns it into a physical one. Whoever controls the table controls what the program can reach.
One table lookup gives four things at once:
| Benefit | Because the table can… |
|---|---|
| Isolation | Simply not contain an entry for another process's memory |
| Relocation | Map the same virtual address to different physical places, so every program can be linked at address 0 |
| Protection | Carry permission bits per entry: readable, writable, executable, user-accessible |
| More memory than exists | Mark an entry "not here right now" and let the kernel fetch the data from disk on first use |
Translating every address through a table in memory would make every memory access several accesses. A TLB is a cache of recent translations, and it works for the same reason your Lab 6 cache works: locality.
| Data cache (Lab 6) | TLB | |
|---|---|---|
| Looked up by | Address tag and index | Virtual page number |
| Returns | A word of data | A physical page number and permission bits |
| On a miss | Fetch a line from main memory | Read the page table (a "page walk") |
| One entry covers | 64 bytes | A whole page, 4 KB in the examples |
| Typical size | Thousands of lines | Tens to a few thousand entries |
Because one TLB entry covers a whole page, a tiny TLB covers a lot of memory. Section 3 has a calculator for what a miss costs.
The pipeline already knows how to throw away wrong-path instructions and fetch from a new address. An exception uses exactly that machinery, with the handler address as the target and one extra step: remember where to come back to.
| Taken branch (Lab 6) | Exception or interrupt | |
|---|---|---|
| Who decides the new PC | The instruction itself | A CSR, mtvec |
| Younger instructions in the pipeline | Squashed | Squashed |
| Old PC | Forgotten (or saved in ra by jal) | Saved in mepc by hardware |
| Privilege | Unchanged | Raised to machine mode |
| How to return | jalr / ret | mret |
The hardware part is small, fixed and fast. Everything that could reasonably be decided differently lives in kernel software.
| Topic | Hardware mechanism | Kernel policy |
|---|---|---|
| Traps | Save PC, record cause, switch mode, jump to mtvec | What each cause means and what to do about it |
| Scheduling | A timer that interrupts | Which process runs next, and for how long |
| Memory | Translate through a table, fault when not allowed | What is in the table, which page to evict, when to load from disk |
| I/O | Device registers at fixed addresses, an interrupt line | Drivers, buffering, who is allowed to use which device |
When a question asks "who does this, hardware or OS?", ask whether it must happen on every instruction (hardware) or only on rare events (software).
A process is a running program plus everything needed to pause and resume it. The kernel is the only code allowed to run with full privilege, and programs can enter it only through a trap.
| User mode | Machine mode (kernel) | |
|---|---|---|
| Ordinary instructions | allowed | allowed |
Read or write CSRs (mtvec, mepc, translation registers) | illegal-instruction exception | allowed |
| Access memory outside its own address space | fault | allowed |
| Touch device registers | fault | allowed |
mret | illegal | allowed |
Full RISC-V also has a supervisor mode between these two. Your Lab 7 kernel uses machine mode only, so this page does the same.
| CSR | Written by | Holds |
|---|---|---|
| mtvec | Kernel, once at boot | Address of the trap handler |
| mepc | Hardware on a trap, kernel before mret | PC of the instruction that trapped, or was about to run when the interrupt arrived |
| mcause | Hardware on a trap | Why. The top bit is 1 for interrupts and 0 for exceptions |
| mstatus | Hardware on trap and on mret | Interrupt-enable bit, its saved copy, and the previous privilege mode |
The hardware part is one atomic step and it saves almost nothing: one PC and one cause. Saving the 31 general registers is the handler's job, and it must do it before it uses any of them.
| Function call | System call | |
|---|---|---|
| Instruction | jal / jalr | ecall |
| Target chosen by | The caller | The kernel, through mtvec. The caller only passes a number in a7 |
| Arguments and result | a0–a7, result in a0 | a0–a6, result in a0 |
| Return address in | ra | mepc |
| Registers preserved | Callee-saved only | All of them, except the result |
| Privilege | Unchanged | User → machine → user |
The caller cannot choose the target address. That is the security property: a program can ask for a service by number, and it cannot jump into the middle of kernel code.
Notice that the handler never contains "switch" logic. It saves into curProc and restores from curProc. The dispatcher changes which struct curProc points to in between, and that pointer change is the entire context switch.
Your kernel gives each process a contiguous 128 KB region. The hardware adds mbase to every user address and faults if the address is not below mbound. This is the simplest form of address translation, and Lecture 17 starts from its weaknesses.
The kernel itself runs on physical addresses. When a process passes a pointer in a system call, the kernel must translate it by hand before using it, as in kputs((char*) va_to_pa(curProc, curProc->regs[REG_a0])).
Recall
Save the PC in mepc, write the reason to mcause, disable interrupts and record the previous mode in mstatus, switch to machine mode, set PC to mtvec. Nothing else. General registers are untouched.
csrw mscratch, t0?It needs a register to hold the pointer to the save area, but every register still holds user data. mscratch is a kernel-only spare, so t0 is parked there, used as the pointer, and its original value is saved last.
ProcState, at what byte offset is a0 saved, and why?Offset 40. pc is at 0, then regs[i-1] holds register xi. a0 is x10, so it is regs[9] at 4 + 9×4 = 40. The handler has sw a0, 40(t0).
kernelSP before calling C code?The user stack pointer cannot be trusted. It may be invalid or point at memory the kernel should not overwrite. It is also a virtual address, and the kernel runs on physical addresses.
csrw mtvec, t0 in user mode. What happens?Illegal-instruction exception. If user code could change mtvec it could make the next trap run its own code in machine mode.
The kernel writes it into the saved copy, curProc->regs[REG_a0]. The restore then loads it into a0.
0x1234 to sys_puts. What physical address does the kernel read?vmbase for pid 3 is 3 × 0x20000 = 0x60000. The physical address is 0x60000 + 0x1234 = 0x61234.
Every user address is checked against mbound and offset by mbase, and only machine mode can write those CSRs. The dispatcher reloads them on every switch.
Cut both virtual and physical memory into fixed-size pages. Translate the page number through a table and keep the offset within the page unchanged.
A new process needs 2 blocks. Two are free, but they are not adjacent, so it cannot start. This is external fragmentation. A process also cannot grow past its neighbour, and unused space inside its block is wasted.
Pages are all the same size, so any free page fits any request. The price is a table with one entry per page instead of two registers per process.
With a page size of 2p bytes, the low p bits are the offset inside the page and are not translated. The remaining high bits are the virtual page number (VPN), which indexes the page table. The table entry supplies the physical page number (PPN).
| Bit | Name | Meaning when set |
|---|---|---|
| V | Valid | The translation exists and the page is in memory. If clear, any access faults |
| R W X | Read, write, execute | Which kinds of access are allowed |
| U | User | User-mode code may use this page |
| A | Accessed | The page has been used recently. Helps the OS choose a victim |
| D | Dirty | The page has been written. It must be saved to disk before its frame is reused |
These are the RISC-V entry bits. Compare them with your Lab 6 cache line status: NotValid, Clean, Dirty. The valid and dirty ideas are the same, applied to pages instead of lines.
Example machine: 16-bit virtual addresses, 4 KB pages, 20-bit physical addresses. So 4 VPN bits, 12 offset bits, 8 PPN bits.
A page fault is an exception raised when the entry is not valid or the access is not permitted. It is not necessarily an error. The kernel uses invalid entries on purpose:
| Why the entry is invalid | Kernel response | Program sees |
|---|---|---|
| Page is on disk (swapped out, or never loaded yet) | Find a free frame, read the page in, set V, return to the same instruction | Nothing, apart from a delay |
| First touch of a fresh stack or heap page | Allocate a zeroed frame, set V, return to the same instruction | Nothing |
| Address was never part of the program | Terminate the process | Segmentation fault |
| Write to a read-only page | Terminate, or copy the page if it was shared on purpose | Fault, or nothing |
Loading pages only when they are first touched is demand paging. It is the same lazy idea as your cache's fill on miss, with the disk in the role of main memory and a penalty of milliseconds instead of 33 cycles. Because the penalty is so large, the miss handling is done in software and the replacement policy can afford to be clever.
Recall
4 KB = 212, so 12 offset bits. VPN = 32 − 12 = 20 bits. A flat table has 220 = 1,048,576 entries.
0x1ABC.VPN = 0x1, offset = 0xABC. Entry 1 is valid with PPN 0x3A. Physical address = 0x3A followed by ABC = 0x3AABC.
16 KB = 214. Offset is 14 bits, VPN is 18 bits, and a flat table has 218 entries. Bigger pages mean a smaller table and more wasted space inside each page.
Physical address = 18 + 12 = 30 bits, so 230 bytes = 1 GB.
A page is mapped as a whole unit. The byte at offset k of the virtual page is the byte at offset k of the physical page.
The same one that faulted. mepc is left pointing at it, so it re-executes and this time the translation succeeds. Contrast with a system call, where the kernel adds 4.
External: free memory exists but in pieces too small to use. Internal: allocated memory that the owner does not use. Paging removes external fragmentation and has internal fragmentation, on average half a page per region.
The disk copy of a clean page is identical, so it can be dropped. A dirty page holds the only copy of its latest contents. This is the same rule as your cache's Writeback state.
A flat page table is too big and a table lookup on every access is too slow. Multi-level tables fix the size. The TLB fixes the speed.
A flat table needs an entry for every virtual page, used or not. Most programs use a few megabytes at the bottom of the address space and a little at the top, with nothing in between. A multi-level table splits the VPN into pieces. The top piece indexes a root table whose entries point to second-level tables, and a second-level table is allocated only if something in its range is mapped.
The calculator assumes the mapped memory is one contiguous run, which is the best case. Scattered pages need more second-level tables. Entries are 4 bytes for addresses up to 32 bits and 8 bytes above, as in RISC-V Sv32 (two levels of 10 bits) and Sv39 (three levels of 9 bits).
The trade: a walk through an L-level table costs L memory accesses instead of 1. That makes the speed problem worse, which is why the TLB is not optional.
Model: a TLB hit costs 1 cycle in total. A miss adds one page-table read per level. Same shape as the cache formula in Lab 6: average = hit time + miss rate × miss penalty.
A classic exam question lists a TLB result, a page-table result and a cache result and asks whether the combination is possible. Two rules decide every case. The TLB only holds translations for pages that are in memory. The cache only holds data that is in memory.
| TLB | Page table | Cache | Possible? | Why |
|---|---|---|---|---|
| hit | valid | hit | yes | The best case. No page-table access happens at all |
| hit | valid | miss | yes | Translation known, data fetched from main memory |
| miss | valid | hit | yes | Walk the table, refill the TLB, then the data is in the cache |
| miss | valid | miss | yes | Walk, then fetch the data from main memory |
| miss | invalid (page fault) | miss | yes | The worst case. The page comes from disk |
| hit | invalid | any | no | A TLB entry exists only for a valid, in-memory page |
| miss | invalid (page fault) | hit | no | The page is not in memory, so none of its data can be in the cache |
Translating first and then indexing the cache puts two lookups in series. The offset bits do not change under translation, so if the cache index and line offset fit inside the page offset, the cache can be indexed with untranslated bits while the TLB works. The tag comparison then uses the physical page number from the TLB.
Virtual address, 4 KB pages
Your Lab 6 cache: 20-bit tag, 6-bit index, 6-bit line offset
Your Lab 6 cache has 64 sets of 64-byte lines, so index plus offset is exactly 12 bits, the size of a 4 KB page offset. The constraint in general: bytes per way ≤ page size. To make such a cache larger, add ways, not sets.
TLB entries belong to one address space. After a switch, process B must not use process A's translations. Either flush the TLB on every switch, which is simple and causes a burst of misses, or tag each entry with an address-space ID so entries from several processes can coexist. In Lab 7 the equivalent step is one line: reload mbase and mbound.
Recall
220 entries × 4 bytes = 4 MB, for every process, even one that uses three pages.
One root table plus two second-level tables (one for the lowest 4 MB region, one for the highest). Each is 1024 × 4 bytes = 4 KB. Total 12 KB instead of 4 MB.
1024 entries × 4 KB per page = 4 MB. One root entry therefore stands for 4 MB of virtual address space.
64 × 4 KB = 256 KB. This is called TLB reach. Larger pages increase it.
1 + 0.02 × (2 × 20) = 1 + 0.8 = 1.8 cycles.
Three for the walk plus one for the data: 4.
Each way can hold at most one page: 4 KB, which is 64 sets. Direct-mapped: 4 KB. Eight ways: 32 KB.
Lower-level tables are only allocated for regions in use. An invalid entry in an upper level stands for a whole missing subtree.
A TLB miss with a valid page-table entry is usually handled by hardware, which walks the table and refills the TLB. A page fault always goes to the kernel, because it needs policy decisions and disk I/O.
Remove the matching TLB entry. Otherwise the TLB keeps serving the stale translation. It is a cache, and caches must be kept consistent with what they copy.
Events that the running program did not ask for must be handled so that the program cannot tell, afterwards, that anything happened. That requirement is called precision, and the pipeline meets it by acting on exceptions only at the commit point.
| Caused by | Timing | mepc points at | After handling, resume at | mcause | |
|---|---|---|---|---|---|
| System call | The ecall instruction | Synchronous | The ecall | mepc + 4, set by the kernel | 8 (from user mode) |
| Fault (page fault, illegal instruction, bad address) | An instruction that cannot complete | Synchronous | The faulting instruction | The same instruction, or never | 2 illegal, 13 load page fault, 15 store page fault |
| Interrupt (timer, keyboard, disk) | Something outside the program | Asynchronous | The first instruction that has not executed | That instruction | top bit set, e.g. 0x80000007 machine timer |
Your Lab 7 dispatcher handles two of these: SYSCALL = 8 and TIMER_INTERRUPT = 0x80000007. The line curProc->pc += 4 appears only in the system-call case, which matches the fifth column.
Precise means the saved state looks as if execution stopped cleanly between two instructions: everything before the faulting instruction has finished, and neither it nor anything after it has changed a register or memory. In a pipeline several instructions are in flight, so this needs care.
| Rule | Reason |
|---|---|
| Carry the exception with the instruction, act on it at the last stage | An older instruction might fault too, and the older one must win. A branch ahead might also turn out to be mispredicted, in which case the faulting instruction never really ran |
| The faulting instruction writes nothing | It will run again after the handler, and must see the original state |
| Squash every younger instruction | They were fetched assuming no exception. Same as your annul |
| Take interrupts at an instruction boundary | An interrupt is attached to whichever instruction is at the commit point, then treated identically |
In the Lab 6 processor the two things that change permanent state are the register-file write in writeback and the data-cache store request in execute. A full implementation must make sure a store does not go out if an older instruction is about to trap.
With memory-mapped I/O, certain addresses are wired to device registers instead of RAM. A store sends data or a command, and a load reads status or data. No new instructions are needed.
kputc spins until the display's ready bit (bit 31) is set, then writes. syscall_read does not spin. It returns −1 at once if no key is waiting, so the process can yield and try again later.
| Polling | Interrupts | |
|---|---|---|
| Who starts the conversation | The CPU asks "anything yet?" repeatedly | The device says "now" |
| Cost when nothing is happening | Every poll is wasted work | Zero |
| Cost per event | Small: one status read | Larger: full trap, save, restore |
| Response time | Up to one polling interval | Almost immediate |
| Best for | Very frequent events, or very simple systems | Rare or unpredictable events |
Recall
ecall sits at 0x48. What is in mepc on entry to the handler, and where does the process resume?mepc = 0x48. The dispatcher adds 4 to the saved PC, so the process resumes at 0x4C. Without the +4 it would execute the ecall forever.
A store page fault, a synchronous exception with mcause 15. mepc points at the store.
mret.Illegal-instruction exception, mcause 2. mret is privileged.
mcause alone whether a trap was an interrupt?The top bit. 0x80000007 has it set, so it is an interrupt. As a signed integer an interrupt cause is negative.
Only the one ahead. The load itself writes nothing and its PC goes to mepc. The two younger ones are squashed and will be fetched again after the handler returns.
An older instruction still in the pipeline might also fault, and its exception must be reported first. Waiting until the commit point orders exceptions the same way the instructions are ordered.
1,000 × 1 µs = 1 ms per second = 0.1%, whether or not any event arrives.
Its purpose is to take the CPU from a program that will not give it up. A program stuck in a loop never polls.
A second trap arriving before the handler has saved mepc and the registers would overwrite them, and the first program's state would be lost.
*buffer = … written through va_to_pa?The pointer in a0 is a user virtual address. The kernel runs without translation, so it must add the process's base to reach the right physical byte.
mepc, mcause, mode, interrupts off, PC ← mtvec. And mret as its inverse.ProcState, change curProc, restore from another.mepc + 4. Fault resumes at mepc. Interrupt resumes at mepc.