Memory management maps logical addresses onto physical memory — base/limit registers, contiguous partitions, paging with TLBs, segmentation and demand-paged virtual memory. Address-translation, EAT and page-replacement numericals (FIFO, Optimal, LRU, Belady's anomaly) appear in almost every paper.
High-yield 75 minSyllabus: “Memory management”
Mark as
The idea in one minute
Picture a vast library (a program's address space) and a small reading room (RAM). You bring in only the chapters you are reading, each placed on a numbered desk (a frame). A catalogue (the page table) records which chapter sits on which desk, and a sticky note of recent lookups (the TLB) saves trips to the catalogue. When every desk is taken and you need another chapter, you must choose one to send back to the stacks — that choice is page replacement.
Key points — the night-before list
The CPU issues logical addresses; the MMU maps them to physical ones (physical = base + logical, legal only if logical < limit). Execution-time binding needs this hardware.
Fixed partitions → internal fragmentation; variable partitions → external fragmentation, cured by compaction or paging. First fit and best fit beat worst fit.
Paging: logical address = page number (m − n bits) + offset (n bits) for 2ⁿ-byte pages; physical = frame × page size + offset; no external fragmentation.
Page-table size = number of pages × entry size: 32-bit addresses, 4 KB pages, 4-byte entries → 2²⁰ entries = 4 MB per process.
EAT with a TLB = h(t + m) + (1 − h)(t + 2m); a k-level page table costs k + 1 memory accesses on a TLB miss.
Demand paging: EAT = (1 − p)·ma + p·(page-fault service time); even one fault per thousand accesses slows memory dozens of times.
FIFO suffers Belady's anomaly (more frames can mean more faults: 9 vs 10 on the classic string); LRU and Optimal are stack algorithms and never do.
Thrashing = more time paging than executing; control it with the working-set model (Σ WSS > frames ⇒ suspend a process) or page-fault frequency.
01Addresses, binding and the MMU
The CPU generates logical (virtual) addresses; the memory unit sees physical addresses. The set of logical addresses a program can use is its logical address space; the matching physical locations form the physical address space. The hardware that converts one into the other at run time is the memory-management unit (MMU).
Compile time — if the program's memory location is known in advance, the compiler emits absolute code (MS-DOS .COM programs). Moving it means recompiling.
Load time — the compiler emits relocatable code and the loader fixes the addresses when the program is loaded. Moving it means reloading.
Execution time — the process can move in memory while it runs, so binding is delayed until each access. This needs hardware (the MMU) and is what most operating systems use.
The simplest MMU has a relocation (base) register: every logical address is added to it on its way to memory. With relocation = 20000, the logical address 1250 becomes physical 21250. The program never sees physical addresses. A limit register provides protection: each logical address must be less than the limit, otherwise the hardware traps to the OS with an addressing error.
Logical and physical addresses are identical under compile-time and load-time binding and differ under execution-time binding. Only the OS, in kernel mode, may load the base and limit registers.
Dynamic loading loads a routine only when it is first called, so unused code (error handlers, say) never occupies memory. Dynamic linking postpones linking of library routines until run time: a small stub finds the shared library (.so on Linux, .dll on Windows) in memory and patches in its address, so one copy of the library serves every process.
Swapping moves a whole process temporarily out to a backing store (fast disk) and later back in — roll out, roll in. Swap time is dominated by transfer time: a 100 MB process on a 50 MB/s disk needs 2 s out plus 2 s in. Because that is slow, modern systems swap only under memory pressure and usually swap pages rather than whole processes; mobile systems such as iOS and Android avoid swapping to flash storage altogether — they ask apps to release memory or terminate background apps instead.
02Contiguous allocation and fragmentation
In contiguous allocation each process occupies one single section of memory. The OS usually sits in low memory (next to the interrupt vector) and user processes above it. There are two classic ways to divide the user area.
Fixed partitions (MFT)
Memory is divided in advance into partitions of fixed sizes
Each partition holds exactly one process; the degree of multiprogramming = number of partitions
A process smaller than its partition wastes the rest — internal fragmentation
Simple; used by early IBM OS/360
Variable partitions (MVT)
Each process gets exactly as much memory as it needs
As processes come and go, free holes of different sizes are scattered through memory
Total free memory may suffice while no single hole does — external fragmentation
Needs a placement strategy to choose a hole
First fit — allocate the first hole that is big enough; stop searching there.
Best fit — allocate the smallest hole that is big enough; leaves the smallest leftover, but must search the whole list unless it is sorted.
Worst fit — allocate the largest hole, hoping the leftover stays useful; also needs a full search.
Next fit — like first fit, but each search starts where the previous one ended (here: at the hole used last).
Request (KB)
First fit
Best fit
Worst fit
Next fit
210
H2 (450) → 240 left
H3 (250) → 40 left
H5 (550) → 340 left
H2 (450) → 240 left
400
H5 (550) → 150 left
H2 (450) → 50 left
H2 (450) → 50 left
H5 (550) → 150 left
120
H1 (150) → 30 left
H1 (150) → 30 left
H4 (350) → 230 left
H5 (150) → 30 left
440
must wait
H5 (550) → 110 left
must wait
must wait
Holes in order: H1 150, H2 450, H3 250, H4 350, H5 550 KB. Only best fit places all four requests here
Simulations show that first fit and best fit beat worst fit in both speed and storage utilisation, and first fit is generally the fastest. Neither escapes external fragmentation: Knuth's 50-percent rule says that with first fit, for every N allocated blocks about another 0.5N blocks are lost to fragmentation — up to one-third of memory may be unusable.
Internal fragmentation
Wasted space inside an allocated block (the block is bigger than requested)
Free memory split into many small non-contiguous holes
Variable partitions, segmentation
Cured by compaction, or avoided by paging
Compaction shuffles the processes together so all free memory forms one large hole. It is possible only when relocation is dynamic (execution-time binding) and it is expensive. The lasting solution is to let a process's memory be non-contiguous — paging and segmentation. Kernels allocate their own memory with the buddy system (power-of-two blocks that split and coalesce; a 33 KB request gets 64 KB, so internal fragmentation) and the slab allocator (caches of pre-built objects).
Interactive · Page-replacement simulator Full page
Loading interactive tool…
03Paging: pages, frames and address translation
Paging divides physical memory into fixed-size blocks called frames and logical memory into blocks of the same size called pages. Any page can go into any free frame, so a process's memory need not be contiguous and external fragmentation disappears. Page sizes are powers of two, from 512 bytes to 1 GB (huge pages); 4 KB is typical.
Logical address space = 2ᵐ bytes, page size = 2ⁿ bytes
page number p = high-order (m − n) bits number of pages = 2ᵐ⁻ⁿ
page offset d = low-order n bits
physical address = (frame number f) × 2ⁿ + d
number of frames = physical memory size ÷ page size
page-table size = number of pages × size of one entry
Small example: 1 KB pages (n = 10). Logical address 3085 = 3 × 1024 + 13, so p = 3 and d = 13. If the page table maps page 3 to frame 7, the physical address is 7 × 1024 + 13 = 7181. In hexadecimal it is even easier: with 4 KB pages (12 offset bits = 3 hex digits), logical address 0x3A7F splits into p = 0x3 and d = 0xA7F; if page 3 is in frame 0x12, the physical address is simply 0x12A7F.
Page-table entry field
Purpose
Frame number
Where the page lives in physical memory
Valid–invalid (present) bit
Is the page legal for this process and currently in memory?
Protection bits
Read / write / execute permissions; violating them traps
Dirty (modified) bit
Set when the page is written; a clean victim need not be written back
Referenced (accessed) bit
Set on every access; used by LRU approximations such as Clock
Caching-disabled bit
For pages mapped to device registers
User/supervisor bit
Whether user-mode code may access the page
Paging still has internal fragmentation: the last page of a process is usually partly empty — on average half a page per process. A 10,500-byte process with 4 KB pages needs 3 frames (12,288 bytes) and wastes 1,788 bytes. Smaller pages waste less but need larger page tables, and disk transfers are more efficient with larger pages, so page sizes have grown over time.
The page table lives in main memory, located by the page-table base register (PTBR), with a page-table length register (PTLR) giving its size; switching processes just reloads the PTBR. The OS also keeps a frame table recording which frames are free. Paging makes sharing easy: reentrant (pure) code such as an editor or a C library can be mapped into the frames of many processes at once, so 40 users need only one copy of the code.
PSC favourite
Paging eliminates external fragmentation but not internal fragmentation. Every memory reference now needs two memory accesses — one for the page-table entry and one for the data — which is why a TLB is essential.
04TLB, effective access time and page-table structures
A translation look-aside buffer (TLB) is a small, fast associative memory that caches recent page-table entries. Each entry is a key (page number) and a value (frame number); all entries are compared in parallel. TLBs hold roughly 32 to 1,024 entries. On a TLB hit the frame number is available almost at once; on a TLB miss the page table in memory is consulted and the entry is loaded into the TLB, replacing another (LRU or random). Some entries — for kernel code — can be wired down. Address-space identifiers (ASIDs) tag entries by process so the TLB need not be flushed on every context switch.
h = TLB hit ratio, t = TLB lookup time, m = one memory access time
EAT = h (t + m) + (1 − h)(t + 2m)
(miss: one access for the page-table entry, one for the data)
If the TLB lookup time is ignored: EAT = h·m + (1 − h)·2m
With a k-level page table: EAT = h (t + m) + (1 − h)(t + (k + 1)m)
Example: t = 10 ns, m = 100 ns
h = 0.90 → 0.90 × 110 + 0.10 × 210 = 120 ns (20% slower than 100 ns)
h = 0.99 → 0.99 × 110 + 0.01 × 210 = 111 ns
Hierarchical (multilevel) paging. A 32-bit address space with 4 KB pages has 2²⁰ pages; with 4-byte entries one process's page table is 4 MB, and it would have to be contiguous. The cure is to page the page table itself. In two-level paging the 20-bit page number is split into a 10-bit outer index p1 and a 10-bit inner index p2, followed by the 12-bit offset. Each inner table then has 2¹⁰ entries × 4 B = 4 KB — exactly one page — and inner tables for unused regions need not exist. 64-bit systems need more levels: x86-64 uses 48-bit virtual addresses with four levels of 9 bits each plus a 12-bit offset (five levels for 57-bit addresses).
Each extra level adds a memory access on a TLB miss
Hashed page table
Hash the virtual page number into a table of chains of (VPN, frame, next) elements
Good for sparse address spaces wider than 32 bits; clustered variant maps several pages per entry
Chains must be searched
Inverted page table
One entry per physical frame holding (process-id, page number); one table for the whole system
Memory for tables shrinks to a fixed fraction of RAM
Lookup must search (use a hash table); shared pages are awkward. Used on PowerPC, UltraSPARC, IA-64
Watch out
Books differ on the EAT formula: some add the TLB lookup time t to both cases, others ignore it (EAT = h·m + (1 − h)·2m). Use whichever matches the data given; if no TLB time is quoted, assume it is negligible.
05Segmentation
Programmers do not think of memory as one linear array of bytes but as a collection of variable-sized segments: the main program, functions, the stack, the heap, global variables, the symbol table. Segmentation supports this view: a logical address is a pair ⟨segment number s, offset d⟩. A segment table, located by the segment-table base register (STBR) and bounded by the segment-table length register (STLR), gives each segment's base (start in physical memory) and limit (length).
Logical address ⟨s, d⟩:
if s ≥ STLR → trap (invalid segment)
if d ≥ limit[s] → trap (addressing error)
physical = base[s] + d
Segment
Base
Limit
Logical ⟨s, d⟩
Physical
0
2000
600
⟨0, 599⟩
2000 + 599 = 2599
1
5200
300
⟨1, 310⟩
trap — 310 ≥ 300
2
900
1000
⟨2, 450⟩
900 + 450 = 1350
3
7000
1200
⟨3, 1199⟩
7000 + 1199 = 8199
A worked segment table
Paging
Fixed-size pages; invisible to the programmer
No external fragmentation; small internal fragmentation
Logical address = one number split by the hardware into page + offset
Protection and sharing at page granularity
Segmentation
Variable-size segments matching the program's logical units
External fragmentation; no internal fragmentation
Logical address = an explicit pair ⟨segment, offset⟩
Natural protection and sharing per segment (e.g. read-only code segment)
Segmentation with paging combines the two: each segment is itself paged, so segments keep their logical meaning while memory is allocated in frames. MULTICS pioneered it. On Intel IA-32 a logical address (selector, offset) goes through the segmentation unit to become a 32-bit linear address, which the paging unit (two-level, 10 | 10 | 12) turns into a physical address. A selector holds a 13-bit segment number, 1 bit choosing the GDT or LDT and 2 protection bits. On x86-64 segmentation is essentially flat, and paging does the real work.
06Virtual memory, demand paging and page faults
Virtual memory separates the logical memory a program sees from the physical memory it gets, so a program need not be entirely in memory to run. Programs can be larger than RAM, more programs fit in memory at once (raising CPU utilisation and throughput), and less I/O is needed to load or swap them. It also makes shared libraries and fork() with copy-on-write cheap.
Demand paging brings a page into memory only when it is referenced — a lazy swapper, or pager. The valid–invalid bit marks each page-table entry: valid means the page is legal and in memory; invalid means it is either outside the address space or legal but still on disk. Pure demand paging starts a process with no pages in memory at all. It works because programs show locality of reference: in any short period they use only a small set of pages.
Handling a page fault
Trap
A reference to a page marked invalid traps to the OS — a page fault.
Check legality
The OS looks at an internal table (in the PCB). An illegal address terminates the process; a legal page that is simply not resident must be paged in.
Find a free frame
Take one from the free-frame list — or, if none is free, run a page-replacement algorithm to free one.
Read the page
Schedule a disk read of the page into that frame. The CPU is given to another process meanwhile.
Update the tables
When the read completes, record the frame in the page table and set the bit to valid.
Restart
Restart the instruction that caused the fault; it now finds the page in memory.
p = page-fault rate (0 ≤ p ≤ 1), ma = memory access time
EAT = (1 − p) × ma + p × (page-fault service time)
Example: ma = 100 ns, fault service = 10 ms = 10,000,000 ns
EAT = 100 + 9,999,900·p ns
p = 0.0001 (one fault per 10,000 accesses) → EAT ≈ 1,100 ns (11 × slower)
for at most 10% slow-down: 100 + 9,999,900·p ≤ 110 → p ≤ 1.0 × 10⁻⁶
Page-fault service time has three big components: servicing the interrupt, reading the page (seek, rotational latency and transfer — milliseconds, the dominant term) and restarting the process. The lesson of the formula is brutal: memory stays usable only if page faults are extremely rare. Follow the whole fault path in the step-through diagram on this page.
Copy-on-write (COW): after fork(), parent and child share all pages, marked read-only; only when one of them writes is that page copied. Free frames for such copies come from a pool that is zero-filled on demand. (vfork() goes further: the parent is suspended and the child uses the parent's pages directly until it calls exec.)
07Page-replacement algorithms
When a page fault occurs and no frame is free, the OS must pick a victim frame: write the victim out if it has been modified (its dirty bit is set), read in the wanted page, update the tables and restart the process. The dirty bit halves the cost for clean victims, which need no write-back. Algorithms are compared by running them on a reference string of page numbers and counting the page faults; more frames normally mean fewer faults.
FIFO — replace the page that has been in memory the longest. Simple, but it may throw out a heavily used page, and it can suffer Belady's anomaly.
Optimal (OPT or MIN) — replace the page that will not be used for the longest time in the future. It gives the lowest possible fault rate but needs future knowledge, so it serves as a benchmark.
LRU (least recently used) — replace the page that has not been used for the longest time: it uses the recent past as a guess of the near future. Implemented with a time-of-use counter per entry or a stack of page numbers, both needing hardware help on every reference.
LRU approximations — use the hardware reference bit: the additional-reference-bits algorithm shifts the bit into an 8-bit history byte at regular intervals; second chance (Clock) is FIFO that skips a page whose reference bit is 1 (clearing it); enhanced second chance uses the (reference, modify) pair.
Counting-based — LFU replaces the page with the smallest reference count; MFU replaces the page with the largest, arguing that the smallest count belongs to a page just brought in. Neither is common: expensive, and poor at approximating OPT.
Page buffering — keep a pool of free frames so the wanted page can be read in before the victim is written out.
(Reference, Modify)
Meaning
As a victim
(0, 0)
Neither recently used nor modified
Best page to replace
(0, 1)
Not recently used, but dirty
Must be written out first
(1, 0)
Recently used, clean
Probably needed again soon
(1, 1)
Recently used and dirty
Worst choice
Enhanced second-chance classes, from best to worst victim
Belady's anomaly: for some algorithms, giving a process more frames can increase its page faults. With FIFO the reference string 1 2 3 4 1 2 5 1 2 3 4 5 causes 9 faults with 3 frames but 10 faults with 4 frames (worked in the examples). László Bélády reported this in 1969. Stack algorithms cannot show the anomaly: for them, the set of pages in memory with n frames is always a subset of the set with n + 1 frames. LRU and Optimal are stack algorithms; FIFO, and second chance, which degenerates to FIFO, are not.
Algorithm
Implementable?
Belady's anomaly?
Notes
FIFO
Yes, trivially
Yes
Ignores usage
Optimal
No (needs the future)
No
Benchmark: fewest faults possible
LRU
Yes, with hardware help
No
Good approximation of OPT; costly to do exactly
Second chance / Clock
Yes (reference bit)
Possible (degenerates to FIFO)
Practical LRU approximation
LFU / MFU
Yes (counters)
Possible
Rarely used
Tip
Count faults by writing the frame contents after every reference, exactly as in the worked examples — and check your traces in the Page-replacement simulator on this page, which shows FIFO, LRU and Optimal frame by frame and demonstrates Belady's anomaly.
08Frame allocation, thrashing and the working set
How many frames should each process get? The minimum is set by the architecture: an instruction and its operands may straddle several pages, and all of them must be present for it to complete (the IBM 370's MVC instruction can need 6 frames). The maximum is the amount of physical memory.
Equal allocation: each of n processes gets ⌊m / n⌋ frames
Proportional allocation: aᵢ = (sᵢ / S) × m, S = Σ sᵢ
sᵢ = size (in pages) of process i, m = frames available
Example: m = 64 frames, s₁ = 20 pages, s₂ = 140 pages, S = 160
a₁ = 20/160 × 64 = 8 frames, a₂ = 140/160 × 64 = 56 frames
Global replacement
A faulting process may take a frame from any process
A process's frame count changes over time
Better system throughput — the common choice
A process's fault rate depends on the others' behaviour
Local replacement
A process replaces only among its own frames
Its frame count stays fixed
Performance is more predictable
Unused frames elsewhere cannot be borrowed
Thrashing is high paging activity in which a process spends more time paging than executing. It begins when processes have fewer frames than the pages they are actively using: each fault throws out a page that is needed again almost at once. CPU utilisation drops, so the OS — seeing an idle CPU — admits more processes, which steals even more frames and makes things worse. Plotted against the degree of multiprogramming, CPU utilisation rises, peaks and then collapses. Local replacement confines the damage to one process but does not cure it.
The cure is to give each process the frames its current locality needs. Peter Denning's working-set model (1968) defines the working set WS(t, Δ) as the set of distinct pages referenced in the most recent Δ references (the working-set window). If D = Σ WSSᵢ, the total demand, exceeds the number of frames m, thrashing will occur, so the OS suspends a process and frees its frames. Δ too small misses the locality; Δ too large spans several localities; Δ = ∞ covers the whole program. Example, Δ = 4, references 1 2 1 3 2 4 4 5 4 5 5 6: at the 4th reference WS = {1, 2, 3}, at the 8th WS = {2, 4, 5}, at the 11th WS = {4, 5}.
Page-fault frequency (PFF) is a more direct control: set an upper and a lower bound on each process's fault rate. Above the upper bound the process gets another frame; below the lower bound it loses one. If the fault rate is too high and no frame is free, a process is suspended.
PSC favourite
Cause of thrashing → too high a degree of multiprogramming (too few frames per process). Remedies → working-set model, page-fault frequency, reducing multiprogramming, adding memory. Increasing multiprogramming makes it worse.
Step through · Servicing a page fault
step 1 / 10
Step 1: Reference page p
An instruction touches page p. The TLB misses, so the MMU reads p's page-table entry.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Paging: address bits, table size and translation
A system has 32-bit logical addresses, 4 KB pages, 4-byte page-table entries and 1 GB of physical memory. Find (a) the page-number and offset bits, (b) the number of pages and the size of a single-level page table, (c) the number of frames and frame-number bits, (d) the physical address of logical 0x00003A7F if page 3 is in frame 0x12, and (e) the two-level split.
EX 2Effective access time with a TLB
TLB lookup takes 10 ns and a memory access 100 ns. Find the EAT for hit ratios of 90% and 99%, compare with no TLB, and find the hit ratio needed for an EAT of at most 115 ns.
EX 3FIFO, Optimal and LRU on one reference string
With 3 frames, initially empty, count the page faults for the reference string 3 2 3 5 4 3 1 5 3 2 3 1 under FIFO, Optimal and LRU.
EX 4Belady's anomaly with FIFO
Apply FIFO to the reference string 1 2 3 4 1 2 5 1 2 3 4 5 with 3 frames and then with 4 frames.
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
For the reference string 7 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 1 7 0 1 with 3 frames (initially empty), count the page faults under FIFO, Optimal and LRU.
Q2
Memory access takes 100 ns and servicing a page fault takes 10 ms. (a) Find the EAT if one access in 10,000 causes a fault. (b) What fault rate keeps the slow-down below 10%?
Q3
Free holes, in order, are 200, 700, 500, 300, 100 and 400 KB. Place requests of 315, 427, 250 and 550 KB (in that order) using first fit, best fit, worst fit and next fit.
Q4
A logical address space has 64 pages of 1,024 bytes each, mapped onto a physical memory of 32 frames. How many bits are in a logical address and in a physical address? How many entries does the page table have?
Q5
(a) 64 frames are shared by two processes of 20 and 140 pages using proportional allocation. How many frames does each get? (b) With Δ = 4 and the reference string 1 2 1 3 2 4 4 5 4 5 5 6, find the working set after the 8th and after the 12th reference.
Exam traps
Paging removes external fragmentation but still has internal fragmentation; segmentation is the reverse.
Belady's anomaly belongs to FIFO (and FIFO-like Clock). LRU and Optimal are stack algorithms and never suffer it.
Some books ignore the TLB lookup time in EAT (EAT = h·m + (1 − h)·2m); others include it. With a k-level page table a TLB miss costs k + 1 memory accesses, not 2.
An inverted page table has one entry per physical frame, not per virtual page — and it is shared by all processes.
Optimal replaces the page used furthest in the future; LRU replaces the page used furthest in the past. FIFO looks only at load time, not at use.
Thrashing is cured by reducing the degree of multiprogramming (or adding memory), never by admitting more processes.
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.