OS and Virtual Memory Atlas

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.

user programhardwarekerneldisk / device
About the sourceThe 6.191 lecture slides need an MIT login that was not available, so this page teaches the standard RISC-V treatment of each topic under the public lecture titles. Numbers such as page size and address width are labelled as examples unless they come from the RISC-V specification or from your Lab 7 code. Check them against the slides before an exam.

0The big picture: five ideas

Idea 1 · The OS is an illusionist with one trick: the trap

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 believesWhat is really trueHow the kernel gets controlWhat the kernel does
"I run continuously on my own CPU"Many processes take turns on one CPUTimer interruptSave registers, pick another process, restore its registers
"I have all of memory, starting at address 0"Each process has a private slice of physical memoryFault on a bad or unmapped addressSet up the translation, or kill the process
"I can print and read keys"Only the kernel may touch devicesSystem 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.

Idea 2 · Indirection through a table buys isolation and flexibility

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.

Process A: virtual page 0
VA 0x0000_0ABC
→
A's table
→
PA 0x0002_3ABC
Process B: the same virtual address
VA 0x0000_0ABC
→
B's table
→
PA 0x0007_1ABC

One table lookup gives four things at once:

BenefitBecause the table can…
IsolationSimply not contain an entry for another process's memory
RelocationMap the same virtual address to different physical places, so every program can be linked at address 0
ProtectionCarry permission bits per entry: readable, writable, executable, user-accessible
More memory than existsMark an entry "not here right now" and let the kernel fetch the data from disk on first use

Idea 3 · If something slow sits on the common path, cache it

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 byAddress tag and indexVirtual page number
ReturnsA word of dataA physical page number and permission bits
On a missFetch a line from main memoryRead the page table (a "page walk")
One entry covers64 bytesA whole page, 4 KB in the examples
Typical sizeThousands of linesTens 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.

Idea 4 · An exception is a branch nobody wrote

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 PCThe instruction itselfA CSR, mtvec
Younger instructions in the pipelineSquashedSquashed
Old PCForgotten (or saved in ra by jal)Saved in mepc by hardware
PrivilegeUnchangedRaised to machine mode
How to returnjalr / retmret

Idea 5 · Hardware provides mechanism, software decides policy

The hardware part is small, fixed and fast. Everything that could reasonably be decided differently lives in kernel software.

TopicHardware mechanismKernel policy
TrapsSave PC, record cause, switch mode, jump to mtvecWhat each cause means and what to do about it
SchedulingA timer that interruptsWhich process runs next, and for how long
MemoryTranslate through a table, fault when not allowedWhat is in the table, which page to evict, when to load from disk
I/ODevice registers at fixed addresses, an interrupt lineDrivers, 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).

1Lecture 16 · Operating systems

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.

Two modes, one gate

User modeMachine mode (kernel)
Ordinary instructionsallowedallowed
Read or write CSRs (mtvec, mepc, translation registers)illegal-instruction exceptionallowed
Access memory outside its own address spacefaultallowed
Touch device registersfaultallowed
mretillegalallowed

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.

The four registers of a trap

CSRWritten byHolds
mtvecKernel, once at bootAddress of the trap handler
mepcHardware on a trap, kernel before mretPC of the instruction that trapped, or was about to run when the interrupt arrived
mcauseHardware on a trapWhy. The top bit is 1 for interrupts and 0 for exceptions
mstatusHardware on trap and on mretInterrupt-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.

A system call is a function call across the privilege boundary

Function callSystem call
Instructionjal / jalrecall
Target chosen byThe callerThe kernel, through mtvec. The caller only passes a number in a7
Arguments and resulta0–a7, result in a0a0–a6, result in a0
Return address inramepc
Registers preservedCallee-saved onlyAll of them, except the result
PrivilegeUnchangedUser → 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.

Context switch: the process is whatever is in its saved state

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.

Lab 7's memory protection: base and bound

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.

Try it

Base-and-bound translation with your Lab 7 numbers

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

What does the hardware do on a trap, in order?

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.

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

Numeric: in 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).

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

A process executes 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.

Where does a system call's return value go, given that the handler restores every register?

The kernel writes it into the saved copy, curProc->regs[REG_a0]. The restore then loads it into a0.

Numeric: process 3 passes the pointer 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.

What exactly makes two processes isolated in Lab 7?

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.

2Lecture 17 · Virtual memory 1: pages and page tables

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.

Why base and bound is not enough

Base and bound: one contiguous block per process
AAfreeBBBfreeC

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.

Paging: any virtual page can live in any physical page
A0B1C0A1B0C1B2free

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.

Splitting the address

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

BitNameMeaning when set
VValidThe translation exists and the page is in memory. If clear, any access faults
R W XRead, write, executeWhich kinds of access are allowed
UUserUser-mode code may use this page
AAccessedThe page has been used recently. Helps the OS choose a victim
DDirtyThe 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.

Try it

Translate an address through an example page table

Example machine: 16-bit virtual addresses, 4 KB pages, 20-bit physical addresses. So 4 VPN bits, 12 offset bits, 8 PPN bits.

Page faults and demand paging

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 invalidKernel responseProgram 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 instructionNothing, apart from a delay
First touch of a fresh stack or heap pageAllocate a zeroed frame, set V, return to the same instructionNothing
Address was never part of the programTerminate the processSegmentation fault
Write to a read-only pageTerminate, or copy the page if it was shared on purposeFault, 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

Numeric: 32-bit virtual addresses, 4 KB pages. How many offset bits, VPN bits and page-table entries?

4 KB = 212, so 12 offset bits. VPN = 32 − 12 = 20 bits. A flat table has 220 = 1,048,576 entries.

Numeric: in the example table above, translate a load of 0x1ABC.

VPN = 0x1, offset = 0xABC. Entry 1 is valid with PPN 0x3A. Physical address = 0x3A followed by ABC = 0x3AABC.

Numeric: 16 KB pages and 32-bit virtual addresses. How do the fields change?

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.

Numeric: entries hold an 18-bit PPN and pages are 4 KB. How much physical memory can be addressed?

Physical address = 18 + 12 = 30 bits, so 230 bytes = 1 GB.

Why is the offset not translated?

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.

After the kernel handles a page fault by loading the page, which instruction runs next?

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.

What is the difference between internal and external fragmentation, and which does paging have?

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.

Why must a dirty page be written to disk before eviction, and a clean one not?

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.

3Lecture 18 · Virtual memory 2: making translation small and fast

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.

Problem 1: size. Solution: a tree of small tables

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.

Calculator

Page-table size: flat against multi-level

flat table, always this size
multi-level, for this process
smaller

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.

Problem 2: speed. Solution: the TLB

Calculator

Average cost of a memory access with a TLB

cycles per access on average
cycles added by one TLB miss

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.

What can and cannot happen together

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.

TLBPage tableCachePossible?Why
hitvalidhityesThe best case. No page-table access happens at all
hitvalidmissyesTranslation known, data fetched from main memory
missvalidhityesWalk the table, refill the TLB, then the data is in the cache
missvalidmissyesWalk, then fetch the data from main memory
missinvalid (page fault)missyesThe worst case. The page comes from disk
hitinvalidanynoA TLB entry exists only for a valid, in-memory page
missinvalid (page fault)hitnoThe page is not in memory, so none of its data can be in the cache

Doing the TLB and cache lookups at the same time

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.

Context switches and the TLB

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

Numeric: 32-bit addresses, 4 KB pages, 4-byte entries. Size of a flat page table per process?

220 entries × 4 bytes = 4 MB, for every process, even one that uses three pages.

Numeric: same machine with a two-level table (10 + 10 + 12). A process maps one code page at address 0 and one stack page at the top of the address space. How much page-table memory?

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.

Numeric: how much memory does one second-level table cover in that two-level scheme?

1024 entries × 4 KB per page = 4 MB. One root entry therefore stands for 4 MB of virtual address space.

Numeric: a TLB has 64 entries and pages are 4 KB. How much memory can be accessed without any TLB miss?

64 × 4 KB = 256 KB. This is called TLB reach. Larger pages increase it.

Numeric: TLB miss rate 2%, two-level table, each table read costs 20 cycles, hit path 1 cycle. Average cycles per access?

1 + 0.02 × (2 × 20) = 1 + 0.8 = 1.8 cycles.

Numeric: a load takes a TLB miss on a machine with a three-level table and no caches. How many memory reads in total?

Three for the walk plus one for the data: 4.

Numeric: 4 KB pages, 64-byte lines, cache indexed in parallel with the TLB. Largest direct-mapped cache? Largest 8-way cache?

Each way can hold at most one page: 4 KB, which is 64 sets. Direct-mapped: 4 KB. Eight ways: 32 KB.

Why can a multi-level table be smaller when it has more levels and more total entries available?

Lower-level tables are only allocated for regions in use. An invalid entry in an upper level stands for a whole missing subtree.

Who handles a TLB miss and who handles a page fault?

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.

The kernel changes a page-table entry, for example to evict a page. What else must it do?

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.

4Lecture 19 · Exceptions and I/O

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.

Kinds of trap

Caused byTimingmepc points atAfter handling, resume atmcause
System callThe ecall instructionSynchronousThe ecallmepc + 4, set by the kernel8 (from user mode)
Fault (page fault, illegal instruction, bad address)An instruction that cannot completeSynchronousThe faulting instructionThe same instruction, or never2 illegal, 13 load page fault, 15 store page fault
Interrupt (timer, keyboard, disk)Something outside the programAsynchronousThe first instruction that has not executedThat instructiontop 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 exceptions in a pipeline

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.

RuleReason
Carry the exception with the instruction, act on it at the last stageAn 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 nothingIt will run again after the handler, and must see the original state
Squash every younger instructionThey were fetched assuming no exception. Same as your annul
Take interrupts at an instruction boundaryAn 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.

I/O: devices look like memory

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 or interrupts

PollingInterrupts
Who starts the conversationThe CPU asks "anything yet?" repeatedlyThe device says "now"
Cost when nothing is happeningEvery poll is wasted workZero
Cost per eventSmall: one status readLarger: full trap, save, restore
Response timeUp to one polling intervalAlmost immediate
Best forVery frequent events, or very simple systemsRare or unpredictable events
Model

CPU time spent on a device: polling against interrupts

Recall

Numeric: an 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.

Which trap occurs: a user program stores to a page whose entry is valid and readable but not writable.

A store page fault, a synchronous exception with mcause 15. mepc points at the store.

Which trap occurs: a user program executes mret.

Illegal-instruction exception, mcause 2. mret is privileged.

How can you tell from 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.

A load in execute will page-fault. The instruction ahead of it, now in writeback, is fine. The two behind it are in decode and fetch. Which complete?

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.

Why not jump to the handler the moment a fault is detected in execute?

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.

Numeric: polling a device 1,000 times per second at 1 µs per poll. What fraction of CPU time is spent polling?

1,000 × 1 µs = 1 ms per second = 0.1%, whether or not any event arrives.

Why does the timer have to be an interrupt and not a polled device?

Its purpose is to take the CPU from a program that will not give it up. A program stuck in a loop never polls.

Why does the hardware disable interrupts on trap entry?

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.

In Lab 7, why is *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.

Know this cold