Lectures 16 to 22 in about 60 minutes, including the questions. Each lecture is one card: the idea, why it works, one picture, the exam move, the trap, and three questions that make you apply it to something new.
L16Operating systems
The OS shares one machine among many processes by keeping them in user mode and taking control only through exceptions.
Why it works
A process is a program plus its state: registers, PC and memory. Save that state and you can pause it. Restore it and it never notices.
User mode cannot touch devices, other memory, or the control registers. So the only way to do anything privileged is to ask the kernel.
An exception is a forced jump into the kernel. Hardware saves the PC in mepc, the reason in mcause, turns on supervisor mode, turns off interrupts, and jumps to the handler address in mtvec.
The same mechanism gives three services: system calls (the process asks), illegal operations (the process is stopped or emulated), and interrupts (a device or timer needs attention).
Event
Kind
Caused by the current instruction?
Resume at
ecall (system call)
Synchronous exception
Yes
mepc + 4, or the same call repeats
Fixable fault (page not in memory, instruction the OS emulates)
Synchronous exception
Yes
mepc to retry, or mepc + 4 if the OS did the work itself
Unfixable illegal operation
Synchronous exception
Yes
Nowhere. The process is terminated
Timer or device
Interrupt
No
mepc. That instruction has not run yet
The move: "what happens when…"
Classify the event: synchronous or interrupt.
Write what hardware does: save PC to mepc, cause to mcause, enter supervisor mode, disable interrupts, jump to mtvec.
Write what the handler does: save registers, handle the cause, maybe pick another process, restore registers, mret.
Decide the resume PC from the table.
TrapReturning to mepc after an ecall. The process would make the same system call forever. The handler must add 4.
A load touches a page the OS has not brought into memory yet. The OS loads the page and returns. Where does the process continue?
At the load itself, so it runs again
At the instruction after the load
At the address in mtvec
The load never completed, and now it can. Skipping it would leave the destination register with no value.
A user program executes an instruction that writes mtvec. What is the result?
The handler address changes for that process only
Nothing, the write is silently ignored
An illegal instruction exception, and the kernel decides what to do
Control registers are supervisor-only. A privileged instruction in user mode is itself an exception, which is what keeps the single entry point safe.
A timer interrupt arrives while process A is running and the kernel switches to process B. What must be saved for A to resume correctly later?
Only A's PC
A's PC and all its registers
A's PC, registers, and a copy of all its memory
A did not expect to stop, so every register may hold live data. Its memory stays where it is, protected from B.
Every process uses its own virtual addresses, and a per-process page table maps each virtual page to a physical page or to "not in memory".
Why it works
Memory is cut into fixed-size pages. An address is a page number plus an offset. Only the page number is translated. The offset passes through unchanged.
Because each process has its own table, it cannot even name another process's memory. That is protection.
The resident bit lets a page live on disk. Touching it causes a page fault, the OS brings it in, and the instruction retries. Programs can use more memory than the machine has.
A table lookup per memory access would be too slow, so the TLB caches recent translations.
TLB
Page table entry
What happens
Cost
Hit
Not consulted
Physical address is ready immediately
Almost nothing
Miss
Resident = 1
Read the entry from the page table, put it in the TLB, continue
A memory access or a few
Miss
Resident = 0
Page fault. OS picks a victim page, writes it to disk if dirty, loads the wanted page, updates the table, retries the instruction
Make translation cheap in space with multi-level page tables, and cheap in time by looking up the cache and the TLB at once.
Why it works
A flat table needs an entry for every virtual page, used or not. With 32-bit addresses and 4 KB pages that is 220 entries, 4 MB per process.
Most of a process's address space is empty. A two-level table splits the VPN in two. The first level points to second-level tables, and those exist only for regions actually in use.
The price is one more memory access per table walk. The TLB hides it most of the time.
The page offset is the same in the virtual and physical address. If the cache index fits inside the offset, the cache lookup can start before translation finishes. That is a virtually indexed, physically tagged cache.
Since mapping is per page, two processes can map the same physical page. That gives shared code, shared memory and file-backed memory.
L1 index · 10 bitsL2 index · 10 bitsoffset · 12 bits
Each table has 210 entries of 4 bytes, so each table is exactly one 4 KB page. A walk reads one L1 entry, then one L2 entry.
The move: how much page table does this process need?
Split the VPN into its level fields.
Always count one first-level table.
For each used page, note its L1 index. Count the distinct L1 indices: that is the number of second-level tables.
Total = (1 + distinct L1 indices) × table size. Compare with the flat size.
TrapCounting one second-level table per used page. Pages that share an L1 index share a table. Only distinct L1 indices cost a table.
With the 10 + 10 + 12 layout, a process uses one code page near address 0 and one stack page near the top of the address space. How much page table memory?
8 KB
12 KB
16 KB
4 MB
One L1 table plus two L2 tables, because the pages are far apart and have different L1 indices. Three tables of 4 KB each.
Pages are 4 KB and cache blocks are 64 bytes. You want a 16 KB cache whose index fits entirely in the page offset. How many ways does it need?
1
2
4
16
Offset has 12 bits and the block offset uses 6, leaving 6 index bits: 64 sets. One way holds 64 × 64 B = 4 KB, so 16 KB needs 4 ways. Capacity can only grow through associativity.
Two processes run the same program. How can the OS use less physical memory without letting one corrupt the other?
Map both processes' code pages to the same physical pages, read-only
Give both processes the same page table
Turn translation off for the code
Sharing is done page by page. Read-only code is safe to share. Sharing the whole table would also share their private data.
A pipelined processor must make exceptions look as if instructions ran one at a time, so it records them and acts only at the commit point.
Why it works
Different stages detect different problems, and a younger instruction can hit its problem in an earlier cycle than an older one.
So each instruction carries its exception down the pipeline. Nothing happens until it reaches the commit point, the last moment before it would change registers or memory.
There, the faulting instruction and everything younger are annulled, the PC is saved, and fetch is redirected to the handler. Everything older has already finished. This is the same machinery as a mispredicted branch.
Devices appear as memory addresses. The processor either checks a status register in a loop (polling) or lets the device raise an interrupt.
Stage
IF
DEC
EXE
MEM
WB
Can detect
bad instruction address
illegal instruction, system call
arithmetic problem
bad data address
Action
record
record
record
act here: annul this and all younger, redirect
older instruction completes
Polling
Interrupts
How
Loop reading the device's ready bit
Device signals, handler runs
Good when
The device is almost always ready, or nothing else needs the processor
Events are rare or unpredictable and there is other work to do
Cost
Wasted cycles checking
Saving and restoring state on each event
The move: exception in a pipeline diagram
Find the cycle the faulting instruction reaches the commit stage.
In that cycle, turn it and every younger instruction into NOPs.
The first handler instruction is fetched in the next cycle.
If two instructions have exceptions, the older one wins. The younger is annulled and will fault again later if it re-executes.
TrapHandling an exception in the stage and cycle where it is detected. That can take them out of program order.
In one cycle, a younger instruction is found illegal in DEC while an older one has a bad data address in MEM. Which exception is taken?
The illegal instruction, because it was earlier in the pipeline
The bad data address, because that instruction is older
Both, in the same cycle
Exceptions follow program order. The older instruction reaches the commit point first and the younger is annulled.
An instruction takes an exception at the commit point. What is true of the instruction just ahead of it, now in the last stage?
It is annulled too
It is re-executed after the handler
It completes normally
Older instructions are unaffected. The handler must see a state where everything before the fault happened and nothing after it did.
A sensor produces one reading every few seconds, at unpredictable times, while the processor runs a long computation. Which I/O method fits?
Interrupts
Polling in a tight loop
Either, the cost is the same
Polling would spend nearly all its checks finding nothing, or would stop the computation. Rare events favour interrupts.
Each core has its own cache, so the caches follow a protocol that allows either one writer or many readers of a line, never both.
Why it works
If two caches hold copies and one core writes, the other copy is stale. Reads would return old data.
Every cache watches a shared bus. Before a core reads or writes a line it does not have the right to, it announces the request, and the other caches react.
A write must first remove every other copy. A read of a line someone has modified makes that cache supply the new data and give up its write permission.
VI has only Valid and Invalid, so two readers keep stealing the line from each other. MSI adds Shared so many can read. MESI adds Exclusive so a core that is the only reader can start writing without a bus message.
MSI: state of this cache's line
This core reads
This core writes
Sees another core's BusRd
Sees another core's BusRdX
I Invalid
send BusRd → S
send BusRdX → M
stay I
stay I
S Shared, read-only
hit, stay S
send BusRdX → M
stay S
→ I
M Modified, only copy
hit, stay M
hit, stay M
write data back → S
write data back → I
The move: trace a sequence of accesses
Make one column per core for the line's state. Start all in I.
For each access, use the row for the acting core's state: which bus message, which new state.
Apply that bus message to every other core using the last two columns.
Check the invariant after each step: one M and everyone else I, or any number of S.
TrapUpdating only the core that acted. Every access that sends a bus message also changes the other cores' states.
MSI, all Invalid. Core 0 writes X, then core 1 reads X, then core 1 writes X. Final states (core 0, core 1)?
M, M
S, M
S, S
I, M
After the write: M, I. Core 1's read makes core 0 write back and drop to S: S, S. Core 1's write sends BusRdX, which invalidates core 0: I, M.
Which combination for one line across two caches can never occur in MSI?
S and S
M and S
M and I
I and I
M means the only up-to-date copy. If another cache could read its own copy at the same time, it would see stale data.
A core reads a line that no other cache holds, then writes it. How many bus requests does it send under MSI and under MESI?
MSI 2, MESI 1
MSI 1, MESI 1
MSI 2, MESI 2
MSI 1, MESI 0
MSI goes I → S with BusRd, then S → M with BusRdX. MESI goes I → E with BusRd, then E → M silently because no one else has a copy.
Parallelism speeds up only the part of the work that can be done in parallel, so the serial part sets the limit.
Why it works
Parallelism exists at three sizes. Between instructions (ILP), between elements of data (DLP), and between threads or tasks (TLP). Each is exploited by different hardware.
Work can be done in parallel only if the pieces do not depend on each other's results.
Amdahl's law: speed up a fraction f of the time by a factor S and the rest is untouched, so overall speedup = 1 / ((1 − f) + f / S).
Let S grow without bound and the speedup approaches 1 / (1 − f). A program that is 90% parallel can never run more than 10 times faster.
Memory behaviour matters as much as core count. Reordering or tiling loops so that data stays in the cache is often the larger win.
Granularity
Unit run in parallel
Exploited by
Needs
ILP instruction-level
Nearby instructions
Pipelining, superscalar processors
Instructions without dependencies between them
DLP data-level
The same operation on many elements
Vector / SIMD instructions, GPUs
Loop iterations that are independent
TLP thread-level
Separate threads or tasks
Multicore processors
Tasks that share little, and synchronization where they do share
The move: an Amdahl problem
Find f, the fraction of the original time that the improvement affects.
Find S, how much faster that part gets.
Speedup = 1 / ((1 − f) + f / S).
For "what is the best possible", use 1 / (1 − f).
TrapSwapping f and 1 − f, or answering f × S. The untouched part does not shrink, and it quickly dominates.
80% of a program's time is in a loop that becomes 4 times faster. What is the overall speedup?
3.2×
2.5×
4×
5×
1 / (0.2 + 0.8 / 4) = 1 / 0.4 = 2.5. 3.2 is f × S, which ignores the serial 20%.
A program is 95% parallelisable. With unlimited cores, what is the largest possible speedup?
95×
Unlimited
20×
19×
1 / (1 − 0.95) = 1 / 0.05 = 20. The serial 5% still takes its full time.
Which loop body can be executed with vector instructions as written?
a[i] = b[i] + c[i]
a[i] = a[i-1] + b[i]
sum = sum * a[i] + 1
In the first, every iteration is independent. The other two need the previous iteration's result, so they must run in order.