Fast Track 3: Systems

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

EventKindCaused by the current instruction?Resume at
ecall (system call)Synchronous exceptionYesmepc + 4, or the same call repeats
Fixable fault (page not in memory, instruction the OS emulates)Synchronous exceptionYesmepc to retry, or mepc + 4 if the OS did the work itself
Unfixable illegal operationSynchronous exceptionYesNowhere. The process is terminated
Timer or deviceInterruptNomepc. That instruction has not run yet

The move: "what happens when…"

  1. Classify the event: synchronous or interrupt.
  2. Write what hardware does: save PC to mepc, cause to mcause, enter supervisor mode, disable interrupts, jump to mtvec.
  3. Write what the handler does: save registers, handle the cause, maybe pick another process, restore registers, mret.
  4. 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?

  1. At the load itself, so it runs again
  2. At the instruction after the load
  3. 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?

  1. The handler address changes for that process only
  2. Nothing, the write is silently ignored
  3. 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?

  1. Only A's PC
  2. A's PC and all its registers
  3. 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.

More depth: operating systems · your handler in Lab 7

L17Virtual memory 1

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

TLBPage table entryWhat happensCost
HitNot consultedPhysical address is ready immediatelyAlmost nothing
MissResident = 1Read the entry from the page table, put it in the TLB, continueA memory access or a few
MissResident = 0Page fault. OS picks a victim page, writes it to disk if dirty, loads the wanted page, updates the table, retries the instructionMillions of cycles

The move: size everything, then translate

  1. Offset bits = log2(page size).
  2. VPN bits = virtual address bits − offset bits. PPN bits = physical address bits − offset bits.
  3. Page table entries = 2VPN bits. Entry width = PPN bits + status bits (resident, dirty, …).
  4. To translate: split the address, look up the VPN, check resident, then PA = PPN followed by the same offset.
TrapAdding the PPN to the address, or translating the offset. The PPN replaces the VPN bits and the offset is copied.

Virtual addresses are 20 bits, physical addresses 16 bits, pages 1 KB. How many entries does a flat page table have?

  1. 64
  2. 220
  3. 216
  4. 1,024

Offset is 10 bits, so the VPN is 20 − 10 = 10 bits and there are 210 entries. 64 is the number of physical pages.

Pages are 256 bytes. The table maps VPN 0x3 to PPN 0x5, resident. What is the physical address for virtual address 0x3A7?

  1. 0x5A7
  2. 0x8A7
  3. 0x3A5
  4. Page fault

Offset is 8 bits: 0xA7. The VPN 0x3 is replaced by PPN 0x5. Adding 0x3 and 0x5 gives the wrong answer 0x8A7.

A store misses in the TLB. The page table entry is resident and writable. What happens?

  1. A page fault, and the OS reads the page from disk
  2. The entry is copied into the TLB and the store proceeds
  3. The process is terminated

A TLB miss only means the translation was not cached. The page is in memory, so no disk and no fault.

More depth: virtual memory 1

L18Virtual memory 2

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

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?

  1. Split the VPN into its level fields.
  2. Always count one first-level table.
  3. For each used page, note its L1 index. Count the distinct L1 indices: that is the number of second-level tables.
  4. 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?

  1. 8 KB
  2. 12 KB
  3. 16 KB
  4. 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. 1
  2. 2
  3. 4
  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?

  1. Map both processes' code pages to the same physical pages, read-only
  2. Give both processes the same page table
  3. 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.

More depth: virtual memory 2

L19Exceptions and I/O

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

StageIFDECEXEMEMWB
Can detectbad instruction addressillegal instruction, system callarithmetic problembad data address
Actionrecordrecordrecordact here: annul this and all younger, redirectolder instruction completes
PollingInterrupts
HowLoop reading the device's ready bitDevice signals, handler runs
Good whenThe device is almost always ready, or nothing else needs the processorEvents are rare or unpredictable and there is other work to do
CostWasted cycles checkingSaving and restoring state on each event

The move: exception in a pipeline diagram

  1. Find the cycle the faulting instruction reaches the commit stage.
  2. In that cycle, turn it and every younger instruction into NOPs.
  3. The first handler instruction is fetched in the next cycle.
  4. 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?

  1. The illegal instruction, because it was earlier in the pipeline
  2. The bad data address, because that instruction is older
  3. 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?

  1. It is annulled too
  2. It is re-executed after the handler
  3. 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?

  1. Interrupts
  2. Polling in a tight loop
  3. Either, the cost is the same

Polling would spend nearly all its checks finding nothing, or would stop the computation. Rare events favour interrupts.

More depth: exceptions and I/O · polling in Lab 7

L20Synchronization

Threads interleave in any order, so you rule out the bad orders with semaphores, which enforce "this must happen before that".

Why it works

GoalInitial valueWhere the calls go
A must finish before B starts (precedence)0signal after A, wait before B
At most K users of a resource poolKwait to take one, signal to give it back
One thread at a time in a critical section (mutex)1wait on entry, signal on exit
Bounded buffer of N slotsspaces = N, items = 0, lock = 1Producer: wait(spaces) … signal(items). Consumer: wait(items) … signal(spaces). Lock around the buffer update

The move: add semaphores to code

  1. Write each requirement as "X ≺ Y" or "at most K at once".
  2. One semaphore per requirement, with the initial value from the table.
  3. Put signal where the arrow starts and wait where it ends.
  4. Check for deadlock: is there an order where every thread is blocked in a wait?
TrapUsing initial value 1 for precedence. Then B's first wait succeeds before A has run. Precedence needs 0.

Thread 1 must print "ready" before thread 2 prints "go". Which setup guarantees it?

  1. s = 1. Thread 1: wait(s), print. Thread 2: wait(s), print
  2. s = 0. Thread 1: wait(s), print. Thread 2: print, signal(s)
  3. s = 0. Thread 1: print, signal(s). Thread 2: wait(s), print

Thread 2 blocks until thread 1 has printed and signalled. Option A is a mutex, which allows either order.

Five threads share three identical scanners. Which initial value lets as many as possible work without two using the same scanner?

  1. 1
  2. 3
  3. 5
  4. 0

The semaphore counts free resources. 3 lets three threads in and blocks the fourth. 1 is safe but wastes two scanners.

Thread 1 does wait(a) then wait(b). Thread 2 does wait(b) then wait(a). Both semaphores start at 1. What can happen?

  1. Deadlock: each holds one and waits for the other
  2. A race on a, but no deadlock
  3. Nothing wrong, the semaphores protect both

If each completes its first wait, neither second wait can ever succeed. Making both take a before b fixes it.

More depth: synchronization · semaphores in Lab 7

L21Cache coherence

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

MSI: state of this cache's lineThis core readsThis core writesSees another core's BusRdSees another core's BusRdX
I Invalidsend BusRd → Ssend BusRdX → Mstay Istay I
S Shared, read-onlyhit, stay Ssend BusRdX → Mstay S→ I
M Modified, only copyhit, stay Mhit, stay Mwrite data back → Swrite data back → I

The move: trace a sequence of accesses

  1. Make one column per core for the line's state. Start all in I.
  2. For each access, use the row for the acting core's state: which bus message, which new state.
  3. Apply that bus message to every other core using the last two columns.
  4. 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)?

  1. M, M
  2. S, M
  3. S, S
  4. 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?

  1. S and S
  2. M and S
  3. M and I
  4. 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?

  1. MSI 2, MESI 1
  2. MSI 1, MESI 1
  3. MSI 2, MESI 2
  4. 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.

More depth: cache coherence

L22Parallel processing

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

GranularityUnit run in parallelExploited byNeeds
ILP instruction-levelNearby instructionsPipelining, superscalar processorsInstructions without dependencies between them
DLP data-levelThe same operation on many elementsVector / SIMD instructions, GPUsLoop iterations that are independent
TLP thread-levelSeparate threads or tasksMulticore processorsTasks that share little, and synchronization where they do share

The move: an Amdahl problem

  1. Find f, the fraction of the original time that the improvement affects.
  2. Find S, how much faster that part gets.
  3. Speedup = 1 / ((1 − f) + f / S).
  4. 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?

  1. 3.2×
  2. 2.5×
  3. 4×
  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?

  1. 95×
  2. Unlimited
  3. 20×
  4. 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?

  1. a[i] = b[i] + c[i]
  2. a[i] = a[i-1] + b[i]
  3. 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.

More depth: parallel processing

Have these memorised