Modern Operating Systems - Memory Management
Memory Management Fundamentals and Hierarchy
- Resource Scarcity and Program Growth:
- Memory (RAM) represents a critical and constrained system resource.
- Programs expand continuously to consume the maximum quantity of memory available to them.
- Programmer Idealization versus Physical Reality:
- Programmer's Perspective: Memory is conceptualized as an idealized medium: private, infinitely large, infinitely fast, and nonvolatile.
- Hardware Reality: Technology delivers a memory hierarchy composed of distinct layers balancing cost, capacity, and latency:
- CPU Registers: Smallest capacity, highest speed (sub-nanosecond access).
- Cache: Static RAM (SRAM), low latency, intermediate capacity.
- Main Memory (RAM): Dynamic RAM (DRAM), primary operational storage for active instructions and data.
- Magnetic Disk / Solid-State Storage: High-capacity secondary nonvolatile storage.
- Magnetic Tape: Tertiary offline archival storage.
- Core Functions of the Memory Manager:
- Allocation: Determining the memory resources granted to processes, the granularity of allocation units, the mechanisms for locating free blocks, and the reclamation protocols when memory is released.
- Translation: Structuring the address format utilized by processes and mediating the conversion from logical/virtual addresses to physical hardware addresses.
- Protection: Enforcing isolation boundaries to safeguard the operating system kernel from unauthorized user-process access and isolating concurrent user processes from each other.
Memory Architecture Without Abstraction
- Direct Physical Addressing:
- Early mainframes, minicomputers, and early personal computers provided no memory abstraction.
- Programs referenced absolute physical addresses directly in hardware instructions (e.g.,
MOV REGISTER1, 1000loads the contents of absolute physical byte address directly into register 1). - Direct physical mapping renders the concurrent execution of multiple arbitrary programs in memory impossible without address collision.

- Monoprogramming Memory Organizations:
- Operating System in RAM at Bottom: The operating system resides in low memory (address upwards) in RAM, and the single user program occupies the remaining contiguous memory up to the physical maximum ().
- Operating System in ROM at Top: The operating system firmware is located in Read-Only Memory (ROM) at the top of the address space, with the user program occupying RAM from address upwards.
- Hybrid ROM/RAM Model: System device drivers reside in ROM at the top of the memory map, the operating system kernel core resides in RAM at the base (), and the user program executes in the contiguous middle RAM region.

- The Relocation Problem:
- When multiple programs share physical memory without abstraction, their instructions contain hardcoded target addresses.
- If a first program is loaded at physical address , an instruction such as
JMP 24branches correctly to address . - If a second program designed to start at address is loaded immediately above the first program at address , an instruction like
JMP 28fails catastrophically because it jumps into the address space of the first program at absolute address rather than target address ().
- Static Relocation:
- Introduced on systems such as the IBM System/360.
- The loader modifies the binary image on the fly during the loading phase by adding a constant offset ( in this instance) to every referenced address throughout the executable.
- Drawbacks: Substantially degrades program loading performance, mandates explicit relocation dictionaries in binary headers, and fails to prevent runaway pointers from corrupting adjacent program spaces or the operating system.
- Modern Application: Systems lacking memory abstraction remain common in deeply embedded architectures and specialized microcontrollers.
Address Space Abstraction and Dynamic Relocation
- Address Space Definition:
- An address space is an abstract set of memory locations allocated to a process for addressing storage independently of physical memory.
- Each process possesses a completely private, isolated address space disjoint from all other processes.
- Exposing raw physical memory to applications risks system integrity, permits operating system crashes, and complicates parallel computing.

- Dynamic Relocation via Base and Limit Registers:
- Hardware equips the central processing unit with two specialized registers:
- Base Register: Stores the starting physical memory address where the process image is currently placed in RAM (e.g., ).
- Limit Register: Stores the total allocation length or bounds of the process address space (e.g., ).
- Programs are loaded into contiguous memory spaces without software-level address modification.
- Runtime Address Translation and Verification:
- For every memory reference generated by the CPU, hardware compares the logical address against the limit register.
- If , a hardware trap occurs to protect neighboring memory.
- If the address is within bounds, hardware adds the base register value to obtain the physical address:
- Disadvantage: Every single memory read or write cycle incurs the computational overhead of an addition and a bound-checking comparison in hardware.
Swapping and Dynamic Partitioning
- Memory Management Approaches for Overloaded RAM:
- Modern multitasking involves multiple active background servers and user processes whose aggregate memory demand exceeds physical RAM capacity.
- Swapping: Moving complete processes between main memory and secondary storage (disk) dynamically.
- Virtual Memory: Permitting execution of programs that reside only partially in physical RAM.

- Dynamic Partitioning and Hole Formation:
- Processes are loaded into memory sequentially, creating variable partitions:
- Initial state: Operating system loaded at base; Process A loaded above OS.
- Process B is allocated space immediately adjacent to Process A.
- Process C arrives and is loaded directly above Process B.
- Process A terminates or is swapped out, leaving an unallocated gap (hole) between the OS and Process B.
- Process D arrives and, being smaller than Process A, is placed in the hole, leaving a smaller residual hole.
- Process B terminates, creating a second isolated hole between Process D and Process C.
- Process A returns; if it cannot fit in the lower hole, it must be allocated memory elsewhere, fragmenting the system into alternating blocks of processes and unused spaces.


- Managing Dynamic Process Growth:
- Processes expand dynamically during execution through heap allocation (dynamic data structures) and nested subroutine calls (execution stack).
- Single Segment Growth: The memory manager provisions extra unallocated buffer space ("room for growth") directly adjacent to the active data segment.
- Dual Segment Growth:
- The program text (code) occupies the base of the allocated segment.
- The data segment (heap) grows upward from low addresses toward high addresses.
- The stack segment grows downward from high addresses toward low addresses.
- The unallocated growth room resides in the center between the stack and the heap. If this space is exhausted, the process must be moved to a larger partition or swapped out.
- Complications of Swapping:
- Relocation Dynamics: When swapped out to disk and returned later, a process rarely lands at the identical physical base address, mandating dynamic hardware relocation via base/limit registers.
- External Fragmentation and Memory Compaction:
- Multiple holes form across physical memory, stranding free space in fragments too small for incoming processes.
- Compaction Cost: Recombining free holes into one continuous block requires moving all active processes toward memory base via the CPU.
- Numerical Performance Cost: If moving takes , transferring a full () requires:
- Spending over purely compacting RAM imposes an unacceptable performance freeze on interactive systems.
Free Memory Management Strategies

- Bitmaps:
- Memory is partitioned into uniform allocation units ranging from a few words up to several kilobytes.
- A dedicated hardware or software bitmap assigns per allocation unit:
0indicates that the corresponding allocation unit is unallocated (free hole).1indicates that the unit is currently occupied by a process.- Tradeoffs: The memory footprint of the bitmap depends entirely on unit size. Small units yield precise tracking with low internal fragmentation but produce large bitmaps. Large units reduce bitmap overhead but waste substantial memory to internal fragmentation. Searching a bitmap sequentially for a run of contiguous zeroes is an expensive scanning operation.
- Linked Lists:
- Memory segments are managed as a doubly linked list of descriptor nodes.
- Each node contains four fields:
- Tag character:
Pfor Process,Hfor Hole. - Start address: The index of the first allocation unit.
- Length: The span of units in the segment.
- Next pointer: Pointer to the succeeding list node.

- Coalescing Holes on Process Termination:
- When process terminates, the memory manager merges adjacent free blocks based on the configuration of its immediate neighbors:
- Case A (Process - X - Process): Neighboring nodes and are processes. Node transitions from
PtoH. List node count is invariant. - Case B (Process - X - Hole): Preceding node is a process; succeeding node is a hole. Node and the trailing hole merge into a single extended hole descriptor. List length decreases by .
- Case C (Hole - X - Process): Preceding node is a hole; succeeding node is a process. Node merges into the preceding hole node. List length decreases by .
- Case D (Hole - X - Hole): Both adjacent neighbors are holes. Preceding hole, node , and trailing hole coalesce into a single unified hole descriptor. List length decreases by .
- Memory Allocation Placement Algorithms:
- First Fit: Scans the list from the beginning and allocates the first hole large enough to satisfy the request. Fast, but tends to break large holes near the front into small unusable fragments.
- Next Fit: Identical to First Fit, but starts scanning from the location where the previous allocation occurred. Slightly worse memory utilization than First Fit.
- Best Fit: Traverses the entire list to locate the hole whose size is closest to the request size. Leaves tiny residual slivers that can cause severe fragmentation.
- Worst Fit: Traverses the list to find the largest available hole, splitting it so the remaining hole remains large enough to be useful. Empirical testing reveals poor overall performance.
- Quick Fit: Maintains separate linked lists for common allocation sizes (e.g., , , ). Searching for common sizes is , but coalescing free memory into adjacent holes requires expensive multi-list scanning.
Dynamic Partitioning Allocation Exercise
- Problem Configuration:
- Initial list of hole sizes arranged strictly in memory order:
- Three successive segment allocation requests arrive in sequence: , then , then .
- Step-by-Step Algorithm Traces:
- First Fit:
- Request 1 (): Scans from start. (too small), (too small). Selects the hole. Residual hole created: .
- State:
- Request 2 (): Scans from start. Selects the first hole encountered, which is (exact fit, leaves ).
- State:
- Request 3 (): Scans from start: (no), (no). Selects the hole. Residual: .
- Holes selected: , , .
- Best Fit:
- Request 1 (): Scans all holes. Finds exact match: selects the hole ( remainder).
- State:
- Request 2 (): Scans all holes. Finds exact match: selects the hole ( remainder).
- State:
- Request 3 (): Scans all holes. Finds exact match: selects the hole ( remainder).
- Holes selected: , , .
- Worst Fit:
- Request 1 (): Finds largest hole in list: selects . Remainder: .
- State:
- Request 2 (): Finds current largest hole: selects . Remainder: .
- State:
- Request 3 (): Finds current largest hole: selects . Remainder: .
- Holes selected: , , .
- Next Fit:
- Request 1 (): Scans from start. Takes the hole (leaving ). Pointer stops immediately after this newly carved hole.
- State:
- Request 2 (): Starts searching from pointer position. Next hole is . Selects (leaving ). Pointer stops after this position.
- State:
- Request 3 (): Starts searching from pointer position. Next is (too small). Next is . Selects (exact fit).
- Holes selected: , , .
Virtual Memory and Paging Architecture
- Overcoming Software Bloatware:
- Modern programs frequently exceed the capacity of physical RAM.
- Splitting software manually via programmer-managed overlays is labor-intensive and error-prone.
- Virtual memory automates dynamic program partitioning across physical storage.
- Fundamental Virtual Memory Principles:
- Each program is provisioned with its own logical address space.
- The logical address space is divided into fixed-size units designated as pages.
- Physical memory is partitioned into matching fixed-size blocks called page frames.
- Typical page and page frame sizes are powers of two, commonly ().
- Pages are mapped onto arbitrary physical page frames across RAM. A program does not require all its pages to reside in physical RAM concurrently to execute.

- Memory Management Unit (MMU):
- A hardware component located inside the CPU package (historically implemented as a discrete external chip).
- Intercepts virtual memory addresses generated by the CPU core and translates them dynamically into physical addresses routed across the system bus to memory and controllers.

- Virtual-to-Physical Address Mapping Mechanics:
- In a model system with a virtual address space and a physical memory using page sizes:
- There are virtual pages ( through ).
- There are physical page frames ( through ).
- Sample mapping table:
- Virtual Page () maps to Frame ().
- Virtual Page () maps to Frame ().
- Virtual Page () maps to Frame ().
- Virtual Page () maps to Frame ().
- Virtual Page () maps to Frame ().
- Virtual Page () maps to Frame ().
- Virtual Page () is unmapped (
X). - Virtual Page () is unmapped (
X). - Virtual Page () is unmapped (
X). - Virtual Page () maps to Frame ().
- Virtual Page () is unmapped (
X). - Virtual Page () maps to Frame ().
- Virtual Pages () are unmapped (
X).

- MMU Hardware Translation Operation:
- Virtual Address Decomposition:
- For a address space with () pages:
- Low-order define the offset within the page ( to ).
- High-order designate the virtual page number ( to ).
- Step-by-Step Translation Example (Virtual Address ):
- in binary:
0010 0000 0000 0100. - High =
0010( in decimal), selecting Virtual Page . - Low =
0000 0000 0100( in decimal), specifying an internal offset of . - Virtual page index is fed into the hardware page table array.
- Entry has its present/absent bit set to
1(valid) and contains frame number110( in decimal). - MMU attaches the frame number
110to the unaltered offset000000000100. - Physical address constructed:
110 0000 0000 0100. - Evaluated in decimal: .
- If the present/absent bit had been
0, the MMU would halt translation and trigger a page fault trap to the kernel.
Page Table Architecture and Acceleration

- Page Table Entry (PTE) Fields:
- Page Frame Number (PFN): The high-order bits specifying the physical frame in RAM mapped to this virtual page.
- Present / Absent Bit: A flag where
1signifies that the page is loaded in physical RAM, and0indicates the page is on backing storage (disk). - Protection Bits: Typically denoting access rights: Read (R), Write (W), and Execute (X).
- Modified Bit (Dirty Bit): Hardware sets this bit to
1whenever an instruction writes to the page. If the page is clean (0), the operating system can discard it on eviction without rewriting it to disk. - Referenced Bit: Hardware sets this bit to
1whenever the page is accessed for reading or writing. Used by page replacement algorithms to evaluate recency of usage. - Caching Disabled Bit: Disables CPU hardware caching for pages that map directly to memory-mapped I/O device registers, preventing stale register values.
- Speed and Capacity Challenges in Paging:
- Mapping must be extremely fast: each memory instruction involves address translation.
- Large address spaces make page tables huge:
- In a address space with pages: .
- With () per entry, a single process table requires of contiguous RAM.
- For concurrent processes, page tables alone consume .
- Placing the full page table in CPU registers avoids extra memory cycles but is prohibitively expensive.
- Keeping page tables purely in main memory doubles effective memory access time, cutting system throughput in half because each logical reference requires two RAM reads (one for the page table entry, one for the data/instruction).

- Translation Lookaside Buffer (TLB):
- A high-speed associative hardware cache integrated directly into the MMU.
- Typically holds a small number of entries (e.g., , , , or entries).
- Fields: Valid bit, Virtual page number, Modified bit, Protection attributes (e.g., RW, RX), Page frame number.
- Lookup Sequence:
- The CPU emits a virtual address to the MMU.
- Hardware performs a simultaneous parallel associative comparison against all TLB entries.
- TLB Hit: If a valid match is found and protection checks pass, the page frame is output directly without accessing memory.
- TLB Miss: If no match occurs, hardware or OS walks the main memory page table, retrieves the entry, evicts a TLB entry, and loads the new translation before restarting the instruction.

- Multilevel Page Tables:
- Avoids keeping full page tables in memory for sparsely populated virtual address spaces.
- Two-Level Paging Decomposition ( Address with Pages):
- PT1 (Top-Level Page Table): High ().
- PT2 (Second-Level Page Table): Middle ().
- Offset: Low ().
- Storage Savings:
- Consider a process with a address space that uses only of memory: text at the bottom, data above it, and stack at the top.
- The top-level table requires 1 page () with entries.
- Only entries (code), (data), and (stack) need to point to allocated second-level page tables.
- The remaining top-level entries are marked invalid (
null), saving vast amounts of memory compared to a single flat table.
Page Replacement Algorithms
- Eviction Policies and Dirty Pages:
- When a page fault occurs and all physical page frames are occupied, an existing page must be evicted.
- If the evicted page has its dirty bit () asserted, its current content must be written back to backing store. If clean (), it is overwritten immediately with zero disk write overhead.

- Optimal Algorithm (OPT / Bélády's Optimal):
- Evicts the page that will not be referenced for the longest duration in the future.
- Impossible to implement in real operating systems because it requires advance knowledge of future memory accesses. Serves as a theoretical benchmark.
- Reference String Trace ():
- String:
7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1 - Total accesses: .
- Step 1:
7loads into Frame 0 (Fault 1). - Step 2:
0loads into Frame 1 (Fault 2). - Step 3:
1loads into Frame 2 (Fault 3). Current frames:[7, 0, 1]. - Step 4:
2references. Frames full. Future references:0(step 5),1(step 14),7(step 18). Page7is furthest in the future; evict7, insert2. Current frames:[2, 0, 1](Fault 4, Replacement 1). - Step 5:
0hit. - Step 6:
3references. Future references:0(step 7),2(step 9),1(step 14). Evict1, insert3. Current frames:[2, 0, 3](Fault 5, Replacement 2). - Step 7:
0hit. - Step 8:
4references. Future references:2(step 9),3(step 10),0(step 11). Evict2or0or3based on ties; evicting0leaves[2, 4, 3](Fault 6, Replacement 3). - Continuing this process produces:
- Total Page Faults:
- Total Replacements:
- Page Fault Rate (PFR):

First-In, First-Out (FIFO) Algorithm:
- Tracks pages via a queue; evicts the oldest page currently in memory.
- Simple to implement, but frequently evicts heavily used base library routines or core program segments.
- Trace with Same Reference String ():
- String:
7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1 - Total Page Faults:
- Total Replacements:
- Page Fault Rate:
Bélády's Anomaly:
- Typically, allocating more page frames reduces the page fault rate.
- With FIFO, increasing the number of page frames can paradoxically increase page faults.
- Verification with Reference String:
1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 - Using 3 Page Frames:
- Reference
1:[1](Fault 1) - Reference
2:[1, 2](Fault 2) - Reference
3:[1, 2, 3](Fault 3) - Reference
4: Evicts1[4, 2, 3](Fault 4) - Reference
1: Evicts2[4, 1, 3](Fault 5) - Reference
2: Evicts3[4, 1, 2](Fault 6) - Reference
5: Evicts4[5, 1, 2](Fault 7) - Reference
1: Hit - Reference
2: Hit - Reference
3: Evicts1[5, 3, 2](Fault 8) - Reference
4: Evicts2[5, 3, 4](Fault 9) - Reference
5: Hit - Result for 3 frames: , .
- Reference
- Using 4 Page Frames:
- Reference
1:[1](Fault 1) - Reference
2:[1, 2](Fault 2) - Reference
3:[1, 2, 3](Fault 3) - Reference
4:[1, 2, 3, 4](Fault 4) - Reference
1: Hit - Reference
2: Hit - Reference
5: Evicts1[5, 2, 3, 4](Fault 5) - Reference
1: Evicts2[5, 1, 3, 4](Fault 6) - Reference
2: Evicts3[5, 1, 2, 4](Fault 7) - Reference
3: Evicts4[5, 1, 2, 3](Fault 8) - Reference
4: Evicts5[4, 1, 2, 3](Fault 9) - Reference
5: Evicts1[4, 5, 2, 3](Fault 10) - Result for 4 frames: , .
- Reference
- FIFO produces more page faults with frames than with frames on this reference string.

- Second Chance Page Replacement Algorithm:
- Modifies FIFO by checking the Referenced () bit of the oldest page before eviction.
- If , the page is both old and unreferenced; it is evicted immediately.
- If , the page is given a second chance: its bit is cleared to
0, its load timestamp is updated to the current time, and it is moved to the end of the FIFO queue. - If all pages have , the algorithm walks the full list, clears every bit, and evicts the first page examined (degenerating to pure FIFO).

- Clock Page Replacement Algorithm:
- Eliminates the overhead of moving nodes in the Second Chance linked list by storing page frames in a circular buffer (a clock).
- A hand points to the oldest page frame.
- On a page fault:
- If : Evict the page, load the incoming page into this frame, set its , and advance the hand clockwise by one position.
- If : Clear to
0, advance the hand to the next frame, and repeat the evaluation until a frame with is found.

- Least Recently Used (LRU) Algorithm:
- Exploits the principle of locality: pages unused for the longest duration are least likely to be needed soon.
- Evicts the page whose last memory reference occurred furthest in the past.
- Trace with Same Reference String ():
- String:
7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2, 1, 2, 0, 1, 7, 0, 1 - Total Page Faults:
- Total Replacements:
- Page Fault Rate:

- Implementing LRU:
- Hardware Counter: CPU includes a counter incremented after every instruction. Each page table entry stores a time-of-use field updated with this value on access. On a fault, the OS scans all page table entries to find the minimum counter value. Scanning is computationally expensive.
- Software / Hardware Stack: A stack tracks page numbers. When a page is referenced, it is removed from its current position and pushed to the top. The bottom of the stack always holds the LRU page. Manipulating a double-pointer stack on every single reference is too slow for software alone.
- Matrix Hardware: For frames, hardware maintains an matrix of bits initialized to zero. When frame is referenced, all bits in row are set to
1, then all bits in column are cleared to0. At any time, the row with the lowest binary value is the least recently used.
- Not Recently Used (NRU) Algorithm:
- Hardware maintains Referenced () and Modified () bits.
- The operating system periodically clears bits to zero on clock ticks.
- When a page fault occurs, pages are sorted into four classes based on their status:
- Class 0: (Not referenced recently, clean).
- Class 1: (Not referenced recently, dirty).
- Class 2: (Referenced recently, clean).
- Class 3: (Referenced recently, dirty).
- NRU randomly picks an arbitrary page from the lowest non-empty class.
- Not Frequently Used (NFU) Algorithm:
- Software approximation of LRU. Maintains a software counter for each page initialized to zero.
- At each clock tick, the OS adds the bit (
0or1) to each page's counter. - On a fault, the page with the lowest counter is evicted.
- Flaw: Retains historical frequency indefinitely without decay. A page heavily referenced during program initialization maintains a high counter and may never be evicted even after it becomes completely idle.

- Aging Algorithm:
- Resolves the NFU flaw to provide an effective software LRU approximation.
- Counters are (or ) shift registers.
- Tick Procedure:
- Shift all page counters right by .
- Insert the current bit into the most significant bit (MSB, bit 7).
- On a page fault, the page with the lowest numeric counter value is selected for eviction.
- Differences Between Aging and Pure LRU:
- Inability to differentiate access ordering within a single clock tick interval.
- Bounded history window: history is truncated by the finite bit-width of the counter register ().
- Most Recently Used (MRU) Exception Case:
- While LRU is generally near-optimal, it fails under specific cyclic patterns.
- Looping Array Case: If an application loops continuously through an array spanning pages while allocated only page frames, LRU evicts the page that will be accessed on the very next iteration, causing a page fault on every single reference ( fault rate). Under this pattern, MRU is preferable.
Working Set and WSClock Algorithms
- Working Set Model:
- Demand Paging: Loading pages only when referenced, initially causing bursts of page faults.
- Locality of Reference: Programs spend most of their execution time accessing a small subset of their overall address space.
- Working Set Definition: The set of pages referenced by a process during the most recent memory references, designated as .

- Working Set Dynamics:
- As the reference window expands, the working set size grows monotonically up to a saturation ceiling defined by the process's current execution phase.
- If a process's entire working set resides in physical memory, it executes with minimal page faults until it transitions to a new phase.
- Prepaging: Preloading a process's working set into RAM before scheduling it (e.g., after being swapped out) to prevent initial fault storms.

- Working Set Page Replacement Algorithm:
- Tracking the exact set over instructions is impractical in software.
- Approximation: Use execution time (e.g., in clock ticks) instead of instructions.
- Each page table entry tracks an bit and a "Time of Last Use" timestamp.
- On a page fault, the OS scans the full page table:
- If : The page was referenced during this tick. Update its "Time of Last Use" to current virtual time and set .
- If : Calculate page age:
- If : The page is outside the working set and is evicted immediately.
- If : The page remains in the working set. Record the smallest timestamp encountered in case all pages are within the working set, in which case the oldest page is evicted.

- WSClock Page Replacement Algorithm:
- Replaces the expensive full page table scan of the basic Working Set algorithm with a circular clock list of page frames.
- Each node stores: Page Frame, bit, bit, and Time of Last Use.
- Clock Hand Advance on Fault:
- If : Clear , update timestamp to current virtual time, and advance the hand.
- If and :
- If page is clean (): Page is not in working set and clean. Evict immediately and claim frame.
- If page is dirty (): Schedule asynchronous write to disk, advance hand to find a clean candidate without blocking.
- Full Cycle Fallbacks:
- Case 1 (Writes scheduled): Continue rotating until a clean page is found (a scheduled write completes).
- Case 2 (No writes scheduled): All pages reside within the working set. Evict any clean page found; if none exist, evict the current page and write it back synchronously.
Page Replacement Algorithms Comparison
| Algorithm | Operational Characteristics and Evaluation |
|---|---|
| Optimal (OPT) | Theoretical upper bound; unachievable in practice; requires future knowledge; useful as a baseline benchmark. |
| NRU (Not Recently Used) | Very crude LRU approximation; partitions pages into 4 classes; low CPU overhead. |
| FIFO (First-In, First-Out) | Discards the oldest loaded page regardless of usage frequency; simple to implement; exhibits Bélády's anomaly. |
| Second Chance | Meaningful improvement over FIFO; inspects bit and recirculates recently referenced pages to the tail. |
| Clock | Functionally equivalent to Second Chance; eliminates list manipulation using a circular array with a moving hand. |
| LRU (Least Recently Used) | Excellent performance; evicts least recently accessed page; difficult to implement exactly without expensive hardware. |
| NFU (Not Frequently Used) | Crude software LRU approximation; counters increment on access but never decay, causing old pages to linger. |
| Aging | Effective, highly practical software approximation of LRU using right-shift registers. |
| Working Set | Mitigates thrashing by keeping active pages in RAM; requires expensive page table scans on faults. |
| WSClock | Industrial-grade algorithm combining Clock circular pointers with Working Set timing and dirty bit handling. |
Page Replacement Exercises and Solutions
Exercise 1: Page Replacement Identification:
- System State: A system has four page frames with load time, last reference time, and status bits as follows:
- Page 0: Loaded = , Last Ref = , ,
- Page 1: Loaded = , Last Ref = , ,
- Page 2: Loaded = , Last Ref = , ,
- Page 3: Loaded = , Last Ref = , ,
- Questions and Step-by-Step Solutions:
- (a) Which page will NRU replace?
- Classify each page by : Page 0 is Class 2 ; Page 1 is Class 0 ; Page 2 is Class 1 ; Page 3 is Class 3 .
- Lowest non-empty class is Class 0. Result: Page 1.
- (b) Which page will FIFO replace?
- FIFO evicts the page with the earliest load time.
- Load times: Page 0 (), Page 1 (), Page 2 (), Page 3 ().
- Lowest value is . Result: Page 3.
- (c) Which page will LRU replace?
- LRU evicts the page with the earliest last reference time.
- Last Ref times: Page 0 (), Page 1 (), Page 2 (), Page 3 ().
- Lowest value is . Result: Page 1.
- (d) Which page will Second Chance replace?
- Evaluates pages in FIFO arrival order: Page 3 (), Page 1 (), Page 2 (), Page 0 ().
- Check Page 3: Its . Clear to
0, update load time to current, move to end of queue. - Next oldest is Page 1: Its . It is selected for eviction.
- Result: Page 1.
Exercise 2: FIFO vs LRU Fault Trace:
- Configuration: Four initially empty frames; reference string:
0, 1, 7, 2, 3, 2, 7, 1, 0, 3. - FIFO Trace:
- Step 1:
0(Fault 1) - Step 2:
1(Fault 2) - Step 3:
7(Fault 3) - Step 4:
2(Fault 4) - Step 5:
3references. Frames full; oldest is0. Evict0, load3(Fault 5, Replacement 1) - Step 6:
2references. Hit. - Step 7:
7references. Hit. - Step 8:
1references. Hit. - Step 9:
0references. Oldest is1. Evict1, load0(Fault 6, Replacement 2) - Step 10:
3references. Hit. - Total FIFO Page Faults: .
- LRU Trace:
- Step 1:
0(Fault 1) - Step 2:
1(Fault 2) - Step 3:
7(Fault 3) - Step 4:
2(Fault 4) - Step 5:
3references. Last referenced times:0(step 1),1(step 2),7(step 3),2(step 4). Least recent is0. Evict0, load3(Fault 5, Replacement 1) - Step 6:
2references. Hit. Access order:[1, 7, 3, 2]. - Step 7:
7references. Hit. Access order:[1, 3, 2, 7]. - Step 8:
1references. Hit. Access order:[3, 2, 7, 1]. - Step 9:
0references. Least recent is3. Evict3, load0(Fault 6, Replacement 2) - Step 10:
3references. Access order:[2, 7, 1, 0]. Least recent is2. Evict2, load3(Fault 7, Replacement 3) - Total LRU Page Faults: .
- Configuration: Four initially empty frames; reference string:
Exercise 3: Aging Algorithm Register Evaluation:
- Setup: A system has four page frames using shift registers initialized to
00000000. Over seven consecutive clock ticks, the observed bits across pages are: - Tick 0:
0 1 1 1 - Tick 1:
1 0 1 1 - Tick 2:
1 0 1 0 - Tick 3:
1 1 0 1 - Tick 4:
0 0 1 0 - Tick 5:
1 1 0 0 - Tick 6:
0 0 0 1 - Step-by-Step Bit Assembly (New bit shifts into MSB):
- Page 0: Sequence of bits across ticks:
0, 1, 1, 1, 0, 1, 0.- Construct register: Bit 7 = tick 6 (
0), Bit 6 = tick 5 (1), Bit 5 = tick 4 (0), Bit 4 = tick 3 (1), Bit 3 = tick 2 (1), Bit 2 = tick 1 (1), Bit 1 = tick 0 (0), Bit 0 =0. - Final register:
01011100( in decimal).
- Construct register: Bit 7 = tick 6 (
- Page 1: Sequence of bits across ticks:
1, 0, 0, 1, 0, 1, 0.- Construct register: Bit 7 = tick 6 (
0), Bit 6 = tick 5 (1), Bit 5 = tick 4 (0), Bit 4 = tick 3 (1), Bit 3 = tick 2 (0), Bit 2 = tick 1 (0), Bit 1 = tick 0 (1), Bit 0 =0. - Final register:
01010010( in decimal).
- Construct register: Bit 7 = tick 6 (
- Page 2: Sequence of bits across ticks:
1, 1, 1, 0, 1, 0, 0.- Construct register: Bit 7 = tick 6 (
0), Bit 6 = tick 5 (0), Bit 5 = tick 4 (1), Bit 4 = tick 3 (0), Bit 3 = tick 2 (1), Bit 2 = tick 1 (1), Bit 1 = tick 0 (1), Bit 0 =0. - Final register:
00101110( in decimal).
- Construct register: Bit 7 = tick 6 (
- Page 3: Sequence of bits across ticks:
1, 1, 0, 1, 0, 0, 1.- Construct register: Bit 7 = tick 6 (
1), Bit 6 = tick 5 (0), Bit 5 = tick 4 (0), Bit 4 = tick 3 (1), Bit 3 = tick 2 (0), Bit 2 = tick 1 (1), Bit 1 = tick 0 (1), Bit 0 =0. - Final register:
10010110( in decimal).
- Construct register: Bit 7 = tick 6 (
- Setup: A system has four page frames using shift registers initialized to
Exercise 4: Working Set Window Evaluation:
- Reference Sequence:
5 6 2 1 4 (t1) 5 6 3 4 3 3 4 3 4 4 3 4 2 3 1 (t2) 6 5 7 3 4 5 - Window Size: .
- Calculations:
- Working set at : The references up to end with
... 5, 6, 2, 1, 4. Extracting unique identifiers gives the set: (size ). - Working set at : The references immediately preceding are:
4, 3, 4, 4, 3, 4, 2, 3, 1. Extracting unique page identifiers gives the set: (size ).
- Reference Sequence:
Exercise 5: Matrix Multiplication TLB Miss Calculation:
- Code Routine:
c int a[1024][1024], b[1024][1024], c[1024][1024]; multiply() { unsigned i, j, k; for(i = 0; i < 1024; i++) for(j = 0; j < 1024; j++) for(k = 0; k < 1024; k++) c[i][j] += a[i][k] * b[k][j]; }
- Code Routine:
System Parameters:
- Page size = .
- Each
int= . - Row size for each matrix: .
- Entire matrix = .
- TLB capacity = with LRU replacement.
- Binary code and execution stack occupy each ( total).
Access Pattern Analysis in the Innermost Loop ():
- Code and stack consume , leaving for data.
- Matrix
c[i][j]is stationary across the loop, requiring only . - Matrix
a[i][k]is accessed along rowi. Across all values of , accesses stay on rowi, using only . - Matrix
b[k][j]is accessed along columnj. Each step of moves to a new row, meaning every single access touches a completely different page (). - Because pages exceed the available TLB slots (), every step of triggers a TLB miss for matrix
b. - Total TLB misses for matrix b: .
Allocation Policies, Sharing, and Implementation Issues

- Local versus Global Allocation Policies:
- Local Replacement: When a process page faults, it can only evict a page frame assigned to itself. Keeps process footprint bounded, but cannot dynamically adapt if the working set size changes.
- Global Replacement: Allows a faulting process to evict frames belonging to any process in memory (e.g., evicting the oldest page globally). Dynamically adapts to varying process workloads, but risks thrashing if a large process continually evicts other processes' working sets.

- Page Fault Frequency (PFF):
- Controls global allocation dynamically by tracking each process's page fault rate:
- Upper Bound : If a process faults more often than threshold , it is thrashing because its working set lacks sufficient frames. The OS allocates additional frames to it.
- Lower Bound : If a process faults less often than threshold , it has surplus frames. The OS reclaims frames from it to distribute to other processes.

- Separate Instruction and Data Spaces (I & D Spaces):
- Unified Address Space: Program instructions and data structures share a single address space (e.g., total).
- Split I & D Space: The hardware provides separate address spaces for instructions (I-space) and data (D-space). Effectively doubles addressable memory without widening register widths.

- Shared Pages:
- Multi-user operating systems prevent duplicate memory allocation when multiple processes run the same program (e.g., compilers, editors, shells).
- Shared code pages are marked read-only. Data pages remain private and are marked read-write.
- If a process writes to a shared data page, hardware triggers a trap, enabling the kernel to perform a Copy-on-Write (COW) operation: allocating a new physical frame, copying the page contents, and updating the faulting process's page table to point to the private replica.

- Shared Libraries and Linking:
- Static Libraries: Compiled directly into the target binary. Causes redundant disk and RAM usage across processes.
bash gcc -c func.c -o func.o ar rcs libfunc.a func.o gcc main.c -o main -static -L. -lfunc ./main
- Static Libraries: Compiled directly into the target binary. Causes redundant disk and RAM usage across processes.
- Dynamic Libraries (Shared Objects): Compiled once using position-independent code (
-fPIC). A single copy is loaded into RAM and shared across processes at runtime.bash gcc -fPIC -c func.c -o func.o gcc -shared -o libfunc.so func.o export LD_LIBRARY_PATH=$(pwd) ./main
Page Fault Handling and OS Mechanics
- Detailed Step-by-Step Page Fault Handling Routine:
- Hardware Trap: The CPU encounters an unmapped page (), pushes the program counter (PC) and CPU flags onto the kernel stack, and traps to the operating system.
- Assembly Context Save: Low-level assembly saves general-purpose registers and processor state into the process table entry.
- Fault Diagnosis: The OS reads MMU registers (such as CR2 on x86) to identify the faulting virtual address.
- Validation Check: The kernel verifies that the address is within valid process bounds and that access permissions match the attempted operation (e.g., checking write access against read-only pages).
- Frame Allocation & Victim Selection: The kernel locates a free page frame. If memory is full, the page replacement algorithm selects an existing frame for eviction.
- Disk Write-Back: If the selected victim frame is dirty (), the kernel schedules a write operation to backing store and switches context to another ready process.
- Page Ingestion: Once the frame is clean, the kernel issues a disk read request to fetch the missing page into the allocated frame.
- I/O Completion Interrupt: An interrupt signals that page reading is complete. The kernel updates the faulting process's page table entry with the new page frame number, marks the present bit as
1, and transitions the process from blocked to ready. - Instruction Restart: The kernel restores saved registers, backs up the program counter to the faulting instruction, and returns to user space to re-execute the instruction.

- Instruction Backup:
- Complex CISC instructions span multiple memory words and may auto-increment or auto-decrement register operands mid-execution.
- Example (Motorola 68000):
MOVE.L #6(A1), 2(A0)spans multiple words (Opcode at , first operand offset at , second operand offset at ). - If a page fault occurs during the final store at
2(A0), registersA1andA0may already have been modified, and the program counter has advanced. - Hardware must provide shadow hidden registers that capture original register states prior to execution, allowing the operating system to undo intermediate operand modifications and cleanly restart the instruction.

- Backing Store Management:
- Static Swap Area: Dedicated contiguous disk partition partitioned into fixed page-sized slots. Each virtual page has a preallocated static block on disk. Simple to manage, but reserves disk space even for unallocated or never-evicted pages.
- Dynamic Disk Map: Allocates disk blocks only when a page is actually evicted from RAM. The page table references an internal disk map structure that tracks dynamic block assignments. Minimizes swap space consumption, but increases table maintenance overhead.
Segmentation
- Motivation: Compiler Multi-Table Expansion:
- Compilers construct multiple data structures whose sizes expand continuously during compilation:
- Source text table (listing preservation for batch output).
- Symbol table (variable identifiers, scopes, attributes).
- Constant table (numeric literals, string constants).
- Parse tree (syntax analysis nodes).
- Call stack (subroutine invocations and local frames).

- The Collision Problem in One-Dimensional Memory:
- In a flat one-dimensional address space, tables are allocated contiguous contiguous blocks in memory.
- As the symbol table grows upward, it collides with the base of the source text table, causing an out-of-memory error even when substantial unallocated space exists elsewhere in the address space.

Segmented Memory Architecture:
- Memory is organized as a collection of independent, variable-length, one-dimensional address spaces called segments.
- Each segment represents a distinct logical unit (e.g., Segment 0 = Symbol table, Segment 1 = Source text, Segment 2 = Constants, Segment 3 = Parse tree, Segment 4 = Call stack).
- Segments grow and shrink independently without colliding with adjacent segments.
- Addresses are two-dimensional:
(Segment Number, Offset).
Paging versus Segmentation Comparison:
| Dimension | Paging | Segmentation |
|---|---|---|
| Programmer Awareness | Fully transparent; handled entirely by hardware and OS. | Explicitly visible; program components are divided into logical units. |
| Address Space Dimensionality | One-dimensional (single contiguous linear sequence). | Two-dimensional (Segment, Offset). |
| Block Size Uniformity | Fixed block size (e.g., ). | Dynamic, variable block size. |
| Total Address Space Boundary | Constrained by CPU hardware address bus width. | Can exceed physical limits via independent segments. |
| Protection and Sharing | Applied per uniform page. | Applied naturally along logical segment boundaries (e.g., code vs data). |
| Primary Motivation | Emulate large linear memory without external fragmentation. | Facilitate independent modular growth of separate data structures. |