Highlights

Contents

Part VII
07

Paging and virtual memory

A virtual address is a name whose physical location can change. Paging gives the kernel fixed-size units for protection, sharing and replacement, while the TLB keeps common translations close to the CPU. We will compute Finch’s translation, table size, page faults, replacement traces, thrashing and segmentation.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1OS fundamentals2Processes3Fork, exec and threads4Synchronization5Deadlocks6CPU scheduling7Paging and memory8Copy-on-write9Filesystems10I/O and IPC11Protection and Linux12Complete server trace

#Section 26Memory management goals

If programs used physical addresses directly, one process could overwrite another and relocation would be difficult. A virtual address belongs to a process’s address-space view. A physical address names a location in RAM. The memory manager maps one to the other and checks permissions before the hardware performs the access.

The goals are isolation, relocation, protection, allocation and sharing. A private page can be mapped to different frames in different processes. A read-only code page can be shared. A missing page can be brought in only when used. These choices let the 32-bit model expose 1,048,576 virtual pages without requiring every page to occupy RAM at once.

PRIVATE ADDRESS SPACES CAN SHARE A FRAME OR LEAVE A PAGE ABSENTPRIVATE ADDRESS SPACES CAN SHARE A FRAME OR LEAVE A PAGE ABSENTprocess Aphysical RAMprocess BVA 0VA 0privateVA 1VA 1sharedVA 2VA 2privateVA 3VA 3not every virtual page is residentabsent page → fault
Figure 3.33Illustrative address-space cutaway. Private maps may name the same shared physical frame, while a valid page can be absent from RAM. Residency and the virtual view are separate questions.

Contiguous allocation makes placement simple but produces holes. Paging removes external fragmentation from physical placement, though the final page can still contain unused bytes.

Contiguous allocation and fragmentation

Fixed partitions reserve predefined regions; variable partitions find a free hole large enough for each request. First fit takes an adequate hole encountered early, best fit selects a small adequate hole, and worst fit selects a large one. Searching and splitting have costs, and none eliminates the need to coalesce adjacent free regions when allocations end.

Internal fragmentation wastes space within an allocation; external fragmentation separates usable holes. Paging allows discontiguous physical frames but does not remove unused bytes inside the final page.

UNUSED SPACE INSIDE A BLOCK DIFFERS FROM HOLES BETWEEN BLOCKSUNUSED SPACE INSIDE A BLOCK DIFFERS FROM HOLES BETWEEN BLOCKSinternal fragmentationused bytesallocated, unusedexternal fragmentationusedfreeusedfreeusedfreefree bytes can exist without one large enough hole
Figure 3.34Illustrative fixed and variable allocations separate unused bytes inside an allocation from free holes between allocations. Orange marks external fragmentation.

#Section 27Paging and address translation

With 4,096-byte pages, a 32-bit virtual address has 12 offset bits and 20 virtual-page-number bits. Finch’s address 13,396 gives VPN 3 and offset 1,108. The page table maps VPN 3 to frame 9. The physical address is frame times page size plus offset, or 9×4096+1108=379729\times4096+1108=37972.

The offset does not change during translation. The page table entry adds the frame and permission state. A present bit says whether the frame is resident; protection bits say which access is allowed. Dirty and referenced bits help writeback and replacement decisions.

THE PAGE NUMBER IS LOOKED UP, THE OFFSET RIDES ALONG13,396 = 3 × 4,096 + 1,108VPN = 3offset = 1,10820 bits12 bitsVPNframe051absent214394absent52page tableframe 728,672frame 832,768frame 936,864frame 1040,960frame 1145,056frame 1249,152physical memoryVPN is looked upoffset copied unchangedVPN 3frame 9+1,1089 × 4,096 + 1,108 = 37,972
Figure 3.35Illustrative translation splits 13,396 into VPN 3 and offset 1,108, then combines frame 9 with the unchanged offset to produce 37,972. Orange marks the final physical address.
CONSECUTIVE VIRTUAL PAGES CAN LIVE IN SCATTERED PHYSICAL FRAMESCONSECUTIVE VIRTUAL PAGES CAN LIVE IN SCATTERED PHYSICAL FRAMESvirtual pagesphysical framespage 0page 1page 2page 3frame 0frame 1frame 2frame 3frame 4frame 5page table0 → 41 → 12 → 53 → 0the page table joins the two views
Figure 3.36Illustrative placement. Consecutive virtual pages map to scattered physical frames; the page table supplies the correspondence. Orange follows virtual page 2 to its assigned frame.

A page is the fixed-size unit in virtual memory, while a frame is the corresponding fixed-size physical unit. Compute the split explicitly: 13396=3×4096+110813396=3\times4096+1108. The quotient selects the virtual page and the remainder selects a byte within it. Translating to frame 9 changes only that quotient, giving 9×4096=368649\times4096=36864 before adding the unchanged remainder. Read both equations as base-plus-offset calculations.

Check permission and residency separately. A present read-only frame can reject a write, while a valid permitted mapping can fault because its backing page is absent.

#Section 28Page tables and TLBs

A linear table needs one 4-byte entry for each of 1,048,576 virtual pages, which is 4,194,304 bytes per address space. Multi-level tables allocate lower branches only for populated regions. Inverted designs index by physical frame and store which virtual page occupies it, changing lookup trade-offs.

A translation lookaside buffer, or TLB, caches recent virtual-to-physical translations. With a 90 percent hit rate, a hit costs 10 ns of TLB lookup plus 100 ns of memory access. A miss costs 10 ns plus two 100 ns memory accesses. The weighted effective time is 120 ns.

E=h(t+m)+(1−h)(t+2m)=0.9(110)+0.1(210)=120 ns.E=h(t+m)+(1-h)(t+2m)=0.9(110)+0.1(210)=120\text{ ns}.

Read this as hit probability h times hit cost plus miss probability times miss cost. E is the expected access time, t the 10 ns TLB lookup and m the 100 ns memory access. The example assumes one page-table memory lookup on a miss and excludes page faults.

A FLAT TABLE PAYS FOR EVERY PAGE, A TREE PAYS FOR USED ONESflat table1,048,576 entries× 4 bytes each= 4,194,304 Ballocated even wherenothing is mappedtwo-level treedirectory1,024 entries4,096 B4,096 B4,096 Bempty entriespoint nowhereillustrative: 3 populated branchesflat 4,194,304 B16,384 B = 4 × 4,096
Figure 3.37Illustrative comparison of a flat table, which costs 4,194,304 bytes whatever is mapped, with a two-level tree that allocates a directory and only three populated branches, 16,384 bytes. Orange marks the populated branches.
THE TLB CACHES A TRANSLATION; A MISS READS THE PAGE TABLE FIRSTTHE TLB CACHES A TRANSLATION; A MISS READS THE PAGE TABLE FIRSTCPUVPN 3TLBVPNframe3910 ns lookupphysical RAMframe 7frame 8frame 9frame 10frame 11hitpage table in RAMVPN 3 → frame 9miss100 ns per memory accesshit: 110 nsmiss: 210 ns0.9 × 110 + 0.1 × 210 = 120 ns
Figure 3.38Illustrative translation paths. A hit costs 10 + 100 = 110 ns; a miss costs 10 + 100 + 100 = 210 ns in the stated model. A 0.9 hit fraction gives 120 ns, and frame 9 is the translated destination.

Context switches can flush or partition TLB state. ASIDs or PCIDs let supported hardware retain entries while tagging ownership.

Multi-level tables save space for sparse mappings by omitting lower branches. A translation miss then needs more navigation. Inverted tables instead organize around physical frames and require another lookup strategy.

Virtual memory and translation tags

Private views, protection and shared mappings are the purpose of virtual memory; backing pages with storage is only one mechanism. Translation tags distinguish entries from different address spaces so a switch can retain correctly identified cached translations. A retained TLB entry must still follow mapping changes and invalidation rules. A larger hit rate cannot repair an outdated entry that grants the wrong permission.

#Section 29Demand paging and faults

Demand paging leaves a valid virtual mapping without a resident frame until the CPU touches it. A page fault transfers control to the kernel. The kernel checks whether the address is legal, locates file-backed bytes or creates a zero page, obtains a frame, updates the PTE and retries the faulting instruction.

A minor fault can be satisfied without storage I/O, while a major fault needs slower backing storage. A dirty evicted page must be written before its frame can be reused. The process is blocked during the wait, so page faults affect both memory latency and scheduler state.

A VALID MISSING PAGE IS LOADED BEFORE THE INSTRUCTION RETRIESA VALID MISSING PAGE IS LOADED BEFORE THE INSTRUCTION RETRIESCPUfaulting instructionnot presentpage-table entrybacking fileresident framepage faultvalidate + allocateload bytesmap frame, retry same instruction
Figure 3.39Illustrative fault path locates or creates a page, maps a frame and retries the same instruction. Orange marks the kernel decision that distinguishes an invalid access from a valid missing page.

Classify the permitted backing first. Demand-zero and already-cached file pages can avoid storage I/O; a major backing read may block the faulting task.

After establishing the mapping, retry the faulting instruction. An address outside the allowed region cannot be repaired merely by catching its failure signal.

#Section 30Page replacement

With three frames and reference string 1,2,3,4,1,2,5,1,2,3,4,5, FIFO produces 9 faults. With four frames it produces 10, the exact Belady anomaly in the supplied trace. LRU with three frames produces 10, while OPT produces 7 because it knows future references and is a benchmark rather than a deployable predictor.

FIFO evicts the oldest resident page, LRU the least recently used, and Clock approximates recency with a referenced bit. Replacement must also consider dirty state, sharing and working-set locality.

FIFO REPLACEMENT, ONE COLUMN PER PAGE REFERENCEFIFO REPLACEMENT, ONE COLUMN PER PAGE REFERENCEpagefault?1121231234234134124125125112521253253453455349 faults in 12 referencesa hit leaves the arrival order unchanged
Figure 3.40Computed FIFO trace for the supplied references and three frames. Each column shows the resident pages after its reference; orange fault columns and dots identify the nine misses.
BELADY'S ANOMALY: FIFO FAULTS 9 TIMES WITH 3 FRAMES, 10 WITH 4BELADY'S ANOMALY: FIFO FAULTS 9 TIMES WITH 3 FRAMES, 10 WITH 4123412512345referenceFIFO, 3 frames9FIFO, 4 frames10LRU, 3 frames10OPT, 3 frames7faults10circle = page fault; dot = hit
Figure 3.41Illustrative comparison shows FIFO’s 9 versus 10 faults, LRU’s 10 and OPT’s 7. Orange marks the anomaly.

The first references 1, 2 and 3 fill the three frames. Reference 4 evicts the oldest loaded page, 1. References 1 and 2 then fault because FIFO’s earlier decisions removed them. After loading 5, the next references to 1 and 2 hit. The remaining references distinguish the policies because FIFO remembers admission order, LRU remembers recent use and OPT compares the next future use.

FIFO, optimal, LRU and Clock

Clock grants referenced frames a second chance by clearing their bit. Reclaiming a candidate still respects dirty and ownership rules. It approximates recency without a fully ordered access history.

#Section 31Thrashing and segmentation

When a task’s working set does not fit, it faults, loads a page, evicts a useful page and faults again. Thrashing means the system spends most of its time paging instead of executing. Locality, working-set size and page-fault frequency provide signals for reducing active work or adding frames.

Segmentation names logical regions such as code, heap and stack. Paging beneath segmentation supplies fixed physical placement and avoids external holes. A segment plus offset still needs bounds and permissions, while a page mapping handles frame placement.

WHEN THE WORKING SET DOES NOT FIT, USEFUL PAGES KEEP TRADING PLACESWHEN THE WORKING SET DOES NOT FIT, USEFUL PAGES KEEP TRADING PLACESworking setABCDavailable framesABCbacking storageevictloadfaultmore page traffic,less useful execution
Figure 3.42Illustrative loop shows a working set that exceeds available frames and repeatedly evicts useful pages. Orange marks the useless fault cycle.
SEGMENTS ARE THE NAMES PROGRAMMERS SEE; PAGES BENEATH THEM DECIDE WHERE BYTES LANDSEGMENTS ARE THE NAMES PROGRAMMERS SEE; PAGES BENEATH THEM DECIDE WHERE BYTES LANDlogical segmentscoder-xheaprw-stackrw-physical frames01234567891011paging beneath: any free frame fits,so no external holessegments carry the permissions
Figure 3.43Illustrative logical regions are named separately from physical paging. Orange marks the page layer that removes external placement holes.

Working sets and page-fault frequency

A working set depends on an observation interval. Admitting more tasks can worsen repeated eviction when their combined active pages exceed available frames. Distinguish that pressure from compulsory first access.

Segmentation and paging

Segmentation adds logical region identity and bounds; paging can allocate its pieces independently. Logical organization and physical placement differ, and neither permits out-of-bounds pointers.