OSTEP - Notes on the Virtualization Section
Last updated on July 24, 2026 pm
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
Preface
The in-class teaching uses the textbook Operating System Concepts.
- I feel it's written rather mediocre...
The order of in-class teaching:
- OS Overview
- Computer Architecture
- Processes, Threads
- CPU Scheduling
- Deadlock
- Memory Management
- Virtual Memory
- File Systems
- Device Management
- Disk Structure
This differs greatly from OSTEP, which puts the virtualization part at the very front. However, for the I/O persistence / file system parts, both books place them near the end.
Chapter 4: Processes
A so-called process: it has its own address space, registers, program counter, etc.
Managing processes: use the PCB (Process Control Block).
Chapter 5: Process API
fork()
代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
printf("Hello, world (pid: %d)\n", (int) getpid());
int rc = fork();
if (rc < 0) {
fprintf(stderr, "fork failed\n");
exit(1);
}
else if (rc == 0) {
printf("Hello, I'm child (pid: %d)\n", (int) getpid());
}
else {
printf("Hello, I'm parent of %d (pid: %d)\n", rc, (int) getpid());
}
return 0;
}> ./fork_p1
Hello, world (pid: 3972)
Hello, I'm parent of 3973 (pid: 3972)
Hello, I'm child (pid: 3973)My understanding of this execution process:
After int rc = fork(), a child process is immediately created. The child process is an almost exact copy of the parent, and the child does not start running from main, but from the point where fork was called.
- For the parent process, the return value obtained is the child's PID
- For the child process, a return value of
0means the child process was successfully created
The specific order of execution depends on CPU scheduling, and each run may produce different results.
wait()
After the parent process calls it, it blocks until any child process finishes, at which point it returns the child's ID.
Change part of the code above to this:
else {
int wc = wait(NULL);
printf("Hello, I'm parent of %d (wc: %d) (pid: %d)\n", rc, wc, (int) getpid());
}Then the output becomes deterministic: the child process runs first
Hello, world (pid: 7835)
Hello, I'm child (pid: 7836)
Hello, I'm parent of 7836 (wc: 7836) (pid: 7835)exec()
First fork to create a child process, then in the rc == 0 branch, call execvp(), which loads code and static data from another executable, overwrites its own code segment, and executes it. A successful call to exec() never returns.
Why Not Combine fork and exec
For example, running:
cat < input.txt > output.txtWhat the shell does:
- fork a child process
- Inside the child process:
- Redirect standard input to input.txt
- Redirect standard output to output.txt
- (So-called redirection: modifying the file handle (
fd) of STDOUT)
exec("cat")
The key point is that redirection needs to happen between fork and exec; if they were combined, there would be no room for this.
Chapter 6: Limited Direct Execution
The core idea: the OS wants to "virtualize" a real CPU so that many processes all seem to run simultaneously, but it cannot truly hand over control. So it must accomplish two things at once:
- First, let programs run fast, executing directly on the CPU as much as possible — direct execution
- Second, always retain the ability to "keep the program under control at any time and take the CPU back at any time" — limited
Starting from direct execution:
- Load the program into memory,
- Set up the stack and registers,
- Then let it run directly on the CPU.
But this has two problems:
- The program keeps holding onto the CPU and won't let go;
- The program wants to perform sensitive operations like I/O
So we propose two kinds of restrictions:
Restricted Operations Must Not Be Done Freely
The hardware provides two modes: user mode and kernel mode.
- Ordinary programs run in user mode, with limited privileges
- The operating system executes in kernel mode, and can perform sensitive actions like I/O, modifying page tables, controlling devices, etc.
But ordinary programs also need to perform sensitive operations. At this point, what is actually executed inside the OS is:
- For high-level languages: on the surface, it's no different from calling an ordinary procedure call, e.g.,
read() - In reality, the library function's code, at the assembly level, ultimately executes a
trapinstruction, switching the CPU from user mode to kernel mode; - The OS pushes the values of this program's registers onto the kernel stack
- The kernel set up a trap table at boot time; the trap makes the hardware jump to a fixed entry point based on the trap number, and the entry code then selects the specific system call implementation based on the syscall number
- After completion, the OS executes a return-from-trap instruction, pops the values from the kernel stack, and returns to user mode.
On the purpose of the trap table
At boot time, the kernel uses privileged instructions to register the "trap vectors/entry addresses" with the hardware (user mode cannot modify them), so that even if a user program triggers a trap, it can only enter the entry points the kernel permits, rather than jumping to arbitrary kernel addresses
On the kernel stack
Each process usually has its own kernel stack; after trapping into the kernel, this stack is used, not the user stack.
Programs Must Not Hog the CPU Forever
How does the OS regain control?
The core: timer interrupts
At boot time, the OS sets up a hardware timer that forcibly triggers an interrupt every short interval. The hardware helps save part of the current program's state (register values), switches back to kernel mode, and jumps to the kernel's interrupt handling code. Thus the OS regains the CPU and can decide whether to "let the current process keep running" or "switch in another process." — This decision is controlled by the scheduler.
If a process switch is needed, the core is: context switching.
- The OS helps save some register values of the currently running process, such as the PC, general-purpose registers, and kernel stack pointer, saving them to the kernel stack;
- Then, it switches the kernel stack
- Specifically, it saves the current process's register state into its process structure (PCB);
- When switching to another process, it restores that process's register state
Chapter 7: Scheduling: Introduction
This chapter mainly provides an introduction to the simplest scheduling policies.
First, five unrealistic assumptions are made: all jobs take the same time, arrive at the same time, run to completion once started, perform no I/O, and their runtimes are known.
Two core metrics are clarified:
- Turnaround time: task completion time - task arrival time in the system
- Response time: from when a job first arrives in the system to when it is first scheduled to run
There are trade-offs between these two metrics.
Below are several example scheduling methods:
FIFO
Performs reasonably well when all jobs are the same length, but once jobs vary in length, later short tasks get stuck behind earlier long tasks.
SJF STCF
- SJF: Shortest Job First, optimal under the condition of "known job lengths and simultaneous arrival"
- STCF: Shortest Time-to-Completion First, at any moment selects the job with the shortest remaining time; when a short job arrives, it can preempt a long job, further optimizing turnaround time
Response Time and RR
STCF/SJF may cause some job to "wait a long time before first getting the CPU," resulting in poor response time.
Introducing time slices, RR is Round Robin: each job runs for only one time slice before switching to the next.
The time slice length usually needs to match the timer interrupt period (e.g., an integer multiple of it)
There are trade-offs here:
- The shorter the time slice, the better the response time, but context switching becomes too frequent, causing performance loss;
- The switching overhead is not just saving/restoring registers, but also includes performance loss from hardware state like caches, TLB, and branch predictors being flushed
Summary: policies like RR that emphasize fairness (evenly dividing the CPU on a small time scale) tend to make turnaround time very poor; conversely, policies favoring short jobs have good turnaround but poor response. This is a classic system trade-off.
Chapter 8: Scheduling: Multi-Level Feedback Queue
The core of MLFQ (Multi-Level Feedback Queue): use historical behavior as feedback to predict the future, learning as it runs, judging whether a process is interactive or CPU-bound.
The basic structure of MLFQ: maintain multiple ready queues, each with its own priority.
Specifically, five rules:
- Rule 1/2: higher priority runs first; same priority uses RR, each level has a different time slice, customizable; usually higher-priority queues use shorter time slices (more interactive-like), lower-priority queues use longer time slices (reducing switching overhead)
- Rule 3 (new arrivals are treated as short jobs first): when a new task enters the system, it is placed at the highest priority
- Rule 4 (demoted after using up its "quota"): when a task has cumulatively used up its allotment (time quota) at a certain priority level, it is demoted to the next level; the key point is "regardless of whether it gave up the CPU in between" — once the cumulative usage is reached, it is demoted
- Rule 5 (periodic priority boost, preventing starvation / handling phase changes): every period S, all tasks are moved to the highest priority
Some concept explanations:
- Starvation: when there are too many interactive tasks, low-priority long tasks may never get the CPU; the solution is Rule 5
Chapter 9: Scheduling: Proportional Share
This is another scheduling philosophy: instead of optimizing turnaround time/response time as the core metric, it tries to ensure each task gets a certain proportion of the CPU.
Lottery Scheduling
The basic concept is intuitive: tickets represent the CPU share a process deserves. For example, if A has 75 tickets and B has 25 tickets, A is expected to get 75% of the time and B 25%.
Scheduling method: draw a lottery for each time slice
- Maintain the total ticket count totaltickets
- Randomly generate winner ∈ [0, totaltickets-1]
- Scan the process list, accumulating tickets; the first process whose cumulative value exceeds the winner wins and runs
Why use randomness? The law of large numbers. It guarantees fairness in a probabilistic sense.
This chapter also emphasizes the engineering value of "randomization": lightweight implementation, little state, avoiding some strange edge-case behaviors, and usually fast enough.
Lottery Mechanisms
- Ticket currency: each user allocates tickets in their own "currency," and the system converts them to global tickets (proportional conversion)
- Ticket transfer: a client temporarily gives tickets to a server, making the server more likely to be scheduled when handling the request, then takes them back afterward
- Ticket inflation: in an environment where processes mutually trust each other, a task can temporarily raise or lower its own ticket count
Stride Scheduling
Designed to solve the problem of fair ticket allocation.
- Each process has stride = constant / tickets (more tickets means smaller stride)
- Each time, select the process with the smallest pass to run; each time slice, pass += stride
Problem: when a new process joins, it is difficult to assign this process's constant.
Therefore, MLFQ is still usually used.
Chapter 10: Multiprocessor Scheduling (Advanced)
Skipping for now; will come back after studying concurrency.
Chapter 13: Abstraction: Address Spaces
This chapter mainly introduces the abstraction of an "address space": the OS needs to allocate an "address space" to each process, but in reality all processes share the same physical memory.
Multiprogramming and time-sharing: for efficiency, we want "processes to stay in memory and take turns running," rather than saving the entire memory to disk and restoring it on every switch, because that would be extremely slow.
Address space: divided into three segments

The key to virtualization: even if a process tries to access address 0, the OS + hardware must translate these virtual addresses into the correct physical addresses.
That is, three key goals:
- Transparency: it seems transparent, so the process doesn't notice;
- Efficiency;
- Protection: there must be isolation between the OS and processes, preventing them from reading and writing each other's memory.
Chapter 14: Interlude: Memory Operation API
This chapter mainly covers the memory allocation API in C.
- Stack memory is automatically managed by the compiler during function calls and returns
- Heap memory requires explicitly requesting with
malloc()and freeing withfree()when no longer in use
Here are some common memory errors:
- Writing to memory without allocating it first
- Out-of-bounds writes caused by insufficient allocation
- Reading uninitialized regions
- Forgetting to free, causing memory leaks
- Continuing to use memory after freeing (dangling pointers)
- Double free
Chapter 15: Mechanism: Address Translation
Hardware-based address translation:
Core trade-offs:
- Efficiency (the OS should not be involved most of the time)
- Protection (a process can only access its own memory)
- Flexibility
As with the scheduling algorithms before, we start from a simple, even unrealistic assumption, and gradually extend it.
Assumptions:
- Each process's address space can be placed contiguously in physical memory
- Each is smaller than the size of physical memory
- Every address space is exactly the same size
Required hardware support:
- Base register (base): treat the "virtual address" as an "offset relative to base," i.e.,
physical = virtual + base; - Bounds register (bound):
virtual >= boundis illegal, triggering a trap instruction
The combination of the two is called the Memory Management Unit (MMU).
Required OS involvement:
- Free list: a data structure in the OS that marks memory space as free / in use;
- Context switching: each CPU has only one pair of base/bounds registers; when switching processes, the OS must save the old process's base/bounds into a structure like the PCB, then restore the new process's base/bounds to the CPU;
- Exception handling: the OS installs various processor exception handlers at boot; once a process accesses memory out of bounds, the hardware switches to kernel mode and jumps to the corresponding handler, and the OS decides how to handle it (commonly, kill the process and reclaim the memory).
Based on these three simplistic assumptions, we have implemented memory virtualization, but there are problems:
- Each process occupies the same amount of memory, causing huge waste; specifically, the large space between the heap and stack is wasted.
Chapter 16: Segmentation
Segmentation is mainly to solve the aforementioned problem of massive space waste.
So-called segmentation: divide a single process's address space into several segments by logic (i.e., code, stack, heap), with each segment using its own MMU for relocation and protection, and segments placed at different locations in physical memory.
The essence of segmentation is mapping different processes' segments to completely different physical locations (where exactly is found via the search in the next chapter).

Note that there is also space reserved for the OS here
How to Determine Which Segment Is Referenced
Explicit approach: we have a virtual address; use the high bits (the first few bits) of the virtual address to identify different segments. For example, with three segments, we use the first two bits for identification, then use the remaining part as the intra-segment offset, and add this offset to the base register, so the hardware obtains the final physical address. Also, when checking, we only need to check whether the offset is less than the bound (the segment's bounds register).
Implicit approach:
- If the address comes from the PC (instruction fetch), assume it is in the code segment.
- If the address is based on the stack pointer / frame pointer, assume it is in the stack segment.
- Otherwise, it is generally assumed to be in the heap segment.
Special Handling for the Stack
We need to note that the stack grows downward, i.e., the stack extends toward smaller addresses.
Therefore, there is actually one more bit in the virtual address used as a flag, indicating the segment's growth direction.
Assuming it grows in reverse, the handling of the virtual address is as follows:
- Get the offset
- Subtract the maximum segment address from the offset (essentially the size of the bounds register)
- Add this negative number (an assert can be added here) to the base register to get the actual physical address
Sharing
Sharing memory between address spaces only requires a little extra hardware support.
Add a few more bits to each segment to mark the program's permissions on that segment: read-write, read-only, execute code, etc.
This way, the same code can be shared by multiple processes, without worrying about breaking isolation.
Accordingly, the hardware algorithm described earlier also needs to change: check whether the virtual address is out of bounds, and check whether a specific access conforms to the permissions.
Problems
- External fragmentation: segments are variable-length, so free blocks in physical memory get carved into scattered small holes, resulting in "plenty of total free space, but no sufficiently large contiguous block"; there are many mitigation approaches for this problem, but it can never be fully solved.
Chapter 17: Free-Space Management
This is mainly about trying to solve the external fragmentation problem.

We assume that once memory is allocated to a user, it cannot be relocated to another location.
Low-Level Mechanisms
Suppose we manage memory with a free list; then the following mechanisms exist:
- splitting: suppose there is a 100-byte free block and someone requests 20 bytes; the memory block should be split into 20+80, giving the user only 20, rather than the entire 100
- coalescing: suppose the 20 bytes are freed; they need to be merged with the 80, so there is once again a complete 100-byte memory block
- header: recall the call process of
free(ptr)— the parameter is only a pointer, with no size of the memory block, so each allocated memory block has a header in front of it to store metadata, recording the size of the memory block; it also contains a magic number for sanity checks.
Next, we analyze: "when there are many free blocks that can satisfy a request, which one to choose?" Several strategies:
- First fit: search from the beginning and allocate the first block that is large enough. Its advantage is simplicity and speed — no need to scan the entire free list. The disadvantage is that the free blocks near the front tend to get split into smaller and smaller pieces.
- Best fit: scan all free blocks that can hold the request and pick the "smallest but sufficient" one. Its intuition is "try not to waste large blocks," but the cost is slower searching, and the actual results are not always the best, because it may create many extremely small fragments that no one can use later.
- Worst fit: pick the largest block to split. The idea is "split a large block, and the remainder is still relatively large," but in practice it usually doesn't perform well, and it likewise requires considerable searching.
- Next fit: similar to first fit, except it doesn't search from the beginning of the list each time, but continues from where it stopped last time, trying to distribute fragmentation more evenly.
Trade-offs always exist here.
But relying only on a free list is somewhat inefficient; here are a few more ideas:
- segregated free lists: pre-allocate a separate free list for commonly used sizes, such as 16 bytes, 32 bytes, so allocation doesn't have to slowly search through one big list, making it much faster.
- buddy allocator: the rule: memory block sizes are all managed in powers of $2^k$. Given a 64KB free space, if 8KB is needed, keep halving; the advantage is that merging is easy, the disadvantage is that requesting 7KB still gets you 8KB, producing fragmentation.
Summary:
- The most core problem in variable-size memory management is external fragmentation.
- The foundation for an allocator to work is splitting, coalescing, and headers.
- Fit strategies solve "which block to pick," essentially a trade-off between speed and fragmentation.
- In engineering practice, segregated lists/slab or buddy allocators are commonly used to further improve efficiency and manageability.
Chapter 18: Paging: Introduction
Segmentation solved the problem of "treating the entire address space as one block being too wasteful," but it brought the problem of external fragmentation.
So-called "paging" is cutting both virtual memory and physical memory into fixed-size small blocks; unlike segmentation, which cares about logic, paging does not care about logic.
Specifically:
- Cut the process's virtual address space into fixed-size pages;
- Then cut physical memory into page frames of the same size
- Addressing is similar to segmentation:
- The first few bits represent the virtual page number (VPN)
- The last few bits represent the offset
- Look up the physical address corresponding to the virtual page number via the page table
- Note that here the VPN is directly replaced with the binary of the PFN (Physical Frame Number) found in the page table, and then directly concatenated with the OFFSET, not added
- The page table is a per-process data structure; note that the address space is also per-process.
Benefits:
- Allocating free space is simplified — just find a few free page frames and stuff the process's pages into them
- The virtual space can be contiguous, but the mapping into physical space can be non-contiguous
Drawbacks:
- Page tables are large and take up a lot of memory
- Because page tables are so large, they can't fit into a small number of hardware registers (MMU), so they can only be placed in memory
- Suppose a 32-bit system with a 4GB address space and 4KB pages: the offset takes 12 bits, since 4KB = $2^{12}$, so the VPN is the remaining 20 bits, giving $2^{20}$ virtual pages. Assuming each page table entry is only 4B, that's still 4MB — and remember, every process has its own page table.
- Address translation becomes slower, because every memory access requires looking up the page table
Page Table Entry (PTE):
The OS uses the VPN to index into the page table, finding the PTE at that index in order to find the PFN. The PTE contains a lot of information:
- valid bit: whether this mapping is valid, i.e., page frames that haven't been allocated are not allowed to be used (invalid)
- protection bit: whether this page can be read, written, executed
- present bit: whether the page is currently in physical memory or has been swapped to disk; dirty bit: whether this page has been modified; reference/accessed bit: whether this page has been accessed recently (not important for now)

Time overhead of paging:
The work the CPU needs to do to access a virtual address:
- Extract the VPN from the virtual address
- Find the starting location of the current process's page table from the page table base register
- Compute the address of the target page table entry
- Fetch that PTE from memory
- Check the various bits
- Get the PFN and obtain the physical address
- Fetch the data
Looking up the page table is one load, and actually fetching the data is another load — very slow.
Chapter 19: Paging: Faster Address Translation (TLB)
The TLB is a very small, very fast page table cache located inside the MMU, caching recently used address translation results — that is, "which physical frame number PFN corresponds to a given virtual page number VPN."
Specifically, the flow of a program accessing a virtual address:
- The CPU splits the address into VPN and OFFSET
- Use the VPN to look up the TLB:
- If TLB Hit, the CPU immediately gets the PFN and obtains the real physical address
- If TLB Miss, only then does it need to look up the page table, both obtaining the PFN and inserting this mapping into the TLB
The core evaluation metric: Effective Memory Access Time (EMAT), which depends on the TLB hit rate.
Why Is the TLB So Effective?
Because program accesses exhibit locality:
- Temporal locality: a page just accessed will likely be accessed again soon
- Spatial locality: neighboring addresses (neighboring in the virtual sense) may be accessed together, typically as in looping over an array
Contents of the TLB
The TLB contains only part of the PTE's contents, including:
- valid bit: whether valid
- protection bit: permissions
- dirty bit: whether it has been written to
- address-space identifier ASID: which process this mapping belongs to
The most important here is the ASID, because of context switching:
Context Switching
For example, when switching from process A to process B, the TLB originally stores entries all related to A's page tables; now that we're switching to B, those TLB entries are all useless. Solutions:
- The simple, brute-force approach is to flush the entire TLB, but the hit rate will be very poor afterward
- So we need to support ASID, so that mappings from different processes can coexist in the TLB:
- The TLB is a global hardware cache, but there are many processes in the system, and VPNs will certainly overlap, so from this alone one can see the ASID is important (you can think of the primary key of this database as
(ASID, VPN)); no special handling of the TLB is needed during switches.
Handling TLB Misses
- For CISC, handled entirely by hardware;
- For RISC, handed to the OS: the hardware raises an exception, trapping into kernel mode, and the OS's exception handler handles it.
The former has a direct access path; the latter is more flexible but traps into the kernel, incurring large performance loss.
TLB Replacement
We will study such policies in detail when discussing swapping pages out to disk.
Here we briefly mention LRU, i.e., replacing the least-recently-used entry.
The smaller the TLB, the more important the replacement policy; but what usually matters more is whether program accesses exhibit locality. If a program constantly accesses a large number of scattered pages, no matter how clever the TLB is, it will miss frequently.
Summary
- TLB = a high-speed cache of the page table, used to cache recently used VPN -> PFN translation results.
- Address translation first checks the TLB; a hit is fast, a miss requires consulting the page table.
- The TLB's value comes from locality: programs often repeatedly access a small number of pages.
- When the TLB hit rate is high, it can greatly reduce the extra memory access overhead introduced by paging.
- With multiple processes, context switching must be considered; common approaches are flushing the TLB or using ASIDs.
- TLB miss handling can be hardware-oriented, or involve software by trapping into the OS.
Chapter 20: Paging: Smaller Tables
Recall that paging brought two problems:
- Page tables are too large
- Translation is too slow
In the previous chapter, we solved the problem of slow translation via the TLB; in this chapter, we solve the problem of page tables being too large.
Why Not Simply Enlarge Pages
The larger the page, the fewer the pages, the fewer the page table entries — but this leads to too much waste within pages, forming internal fragmentation. Therefore, the OS mainly still uses relatively small pages, such as 4KB or 8KB.
Hybrid Approach: Combining Paging and Segmentation
- First segment: segments are responsible for dividing the address space into several logical regions;
- Then page: responsible for mapping within each segment by pages.
But this structure is actually not very reasonable, because the very advantage of "paging" is that it does not depend on the program's logical structure.
Multi-Level Page Tables
Core idea: in a linear page table, many page table entries are actually invalid, so we might as well not allocate those invalid page table pages.
Introduce a higher-level structure: the page directory
- Each entry in the page directory points to a page of the page table
- Page table entries are responsible for pointing to the actual page frames
That is:
- In the original linear case, each process is allocated one large page table
- In the current case, each process is allocated a page directory, and the page directory entries (PDEs) in the page directory point to page tables
- The pointed-to page tables, like the original linear page table, are arrays of PTEs
- The key point is that these small page tables are created on demand, allocating page table space only for virtual address regions actually in use.
Trade-off of multi-level page tables: on a TLB Miss, two loads from memory are required (first loading from the page directory, then loading the PTE itself).
How is a virtual address looked up in a two-level page table?
In a two-level page table, the virtual address is split into three parts:
- Page Directory Index -> used to determine which process's page directory
- Page Table Index
- Intra-page offset
Lookup flow:
- First use the PDIndex to look up the page directory, computing the address of the corresponding page directory entry (PDE)
- If the PDE is invalid, raise an exception
- If the PDE is valid, continue; based on the PTIndex, compute the starting address of the corresponding page table entry (PTE)
- If invalid, jump out
- If valid, look up the PFN based on the PTE
- Finally combine with the OFFSET to get the answer.
Here is an example from GPT; you'll understand after reading it:
引用
To make the math easy, let's assume a very small system.
Given conditions
- Virtual address length: 8 bits
- Page size: 16B = 2^4
- So:
- Intra-page offset takes 4 bits
- The remaining high 4 bits represent the "virtual page number VPN"
But now we have a two-level page table, so this 4-bit VPN is split into two parts:
- High 2 bits: Page Directory Index (PDI)
- Low 2 bits: Page Table Index (PTI)
So a virtual address is split into:
| 2-bit page directory index | 2-bit page table index | 4-bit intra-page offset |For example, suppose we now have a virtual address:
01100101Split it apart:
01 | 10 | 0101 PDI PTI offsetSo it represents:
- Page directory index PDI = 01 = 1
- Page table index PTI = 10 = 2
- Intra-page offset = 0101 = 5
Step 1: Look up the page directory
Suppose the current process's page directory is as follows:
Page Directory Index Valid Points to which page table 0 1 Page table A 1 1 Page table B 2 0 Does not exist 3 0 Does not exist We just got PDI=1; looking it up, it exists and is page table B.
Step 2: Look up the page table
Suppose page table B's contents are as follows:
Page Table Index Valid Physical frame number PFN 0 1 4 1 0 - 2 1 9 3 1 3 We just got PTI=2, so we get PFN=9.
Step 3: Assemble the address
Physical address = PFN * page size + offset = 9 * 16 + 5 = 144 + 5 = 149Final result: virtual address 01100101 is translated into physical address 149.
Pros and cons of multi-level page tables:
- Pros: significantly reduces page table size
- Cons: on a TLB Miss, the translation path is longer, costing one extra load
More Advanced
If the address space is far larger than the page size, then a two-level page table is not enough, and multi-level page tables are needed.
The goal is "to keep the size of each level of page table structure within one OS page as much as possible, and allocate only when needed."
Inverted Tables
We have been emphasizing one page table per process.
The idea of the inverted page table:
- The entire system has only one table
- Each physical page frame has one entry
- The entry records which process this physical page frame belongs to, and which virtual page of that process it corresponds to
But a purely linear search would be very slow (since the primary key is (PID, VPN)), so usually a hash table is added.
A very important point of view: Page tables are essentially just data structures. Since they are data structures, there can be many different designs; everyone makes different trade-offs between "space" and "time."
Chapter 21: Beyond Physical Memory: Swap Mechanism
We have so far assumed that memory can hold all pages, but in reality:
- A process's address space may be very large, and there may also be many processes running simultaneously,
- So physical memory actually cannot hold all the pages that need to be used.
We solve this problem by putting currently infrequently used pages into the swap space on disk.
Core flow diagram:
flowchart TD
CPU["CPU 访问某个虚拟地址"] --> TLB["先查 TLB"]
TLB -->|命中| MEM["直接访问物理内存中的页"]
TLB -->|未命中| PT["查页表"]
PT -->|页在内存中| MEM
PT -->|页不在内存中| PF["触发 page fault"]
PF --> OS["OS 的 page-fault handler 介入"]
OS --> DISK["从 swap / 磁盘把页读回内存"]
DISK --> MEM
MEM --> RETRY["重试原来的指令"]
Valid Pages and Pages in Memory
Two bits: valid and present.
- valid bit: whether this page is part of the process's legal address space.
- present bit: whether this valid page is currently in physical memory.
When valid=1 but present=0, it means the page is on disk, and accessing it triggers a page fault.
A page fault is a normal part of how a virtual memory system works.
How to Handle a Page Fault
- First check whether the TLB has this address translation
- If the TLB misses, then look up the page table
- After looking up the page table, we find this page has valid = 1 but present = 0
- The hardware triggers a page fault and hands control to the OS
- The OS's page-fault handler starts working.
- The OS finds a physical page frame, preparing to read the missing page in.
- The OS reads this page back into memory from the swap area on disk.
- The OS updates the page table, changing this page table entry to:
- present = 1
- PFN = some new physical frame number
- If necessary, the TLB is also updated.
- Then the faulting instruction is re-executed.
- This time, since the page is already in memory, the access completes normally
When accessing a valid page not in memory, the OS is responsible for "filling it back in," then letting the program continue as if nothing had happened.
After the retry, it will very likely first experience another TLB miss, because the TLB does not yet have this new translation; only after another retry will there be a true TLB hit, finally accessing the data.
Page Faults Are Expensive
Accesses that trigger disk I/O are extremely, extremely slow, so as soon as page faults increase, program speed drops dramatically.
What If Memory Is Full When the Page Fault Wants to Fill a Page Back In
Then a physical page frame currently in memory must first be kicked out — so-called page replacement or eviction.
This mechanism is discussed in the next chapter.
What Is the Process Doing During a Page Fault
Because disk I/O is a very expensive operation, recall our earlier scheduling algorithms: this process is in the blocked state, so during this time, the OS can run other processes.
Why Page Faults Are Handed to the OS Rather Than Hardware
- Hardware handling would be too complex
- The real time cost is disk I/O, so even if the OS executes some extra software logic, compared to the slowness of the disk, this extra overhead is negligible.
When Does Swapping Actually Happen
We just said the OS swaps out pages only when memory is full, but that's not actually the case; the OS is actually more proactive:
The system sets two watermarks:
- low watermark (LW)
- high watermark (HW)
Working mechanism:
When the OS finds the number of free pages below LW, a background thread starts running, proactively swapping some pages out, until the number of free pages rises back to HW.
This background thread is often called the swap daemon or page daemon.
Chapter 22: Beyond Physical Memory: Policies
The core question of this chapter: page replacement policy
Overall goal: physical memory can be viewed as a cache of virtual pages on disk; what a page replacement policy must do is keep this cache's hit rate as high as possible and the miss rate as low as possible.
Because disk I/O is far slower than accessing memory, once a miss occurs, performance deteriorates rapidly, so the goal can also be stated as minimize misses.
Optimal
The ideal optimum for replacement: always replace the page that "will be accessed last in the future."
The significance of Optimal: this is the theoretically best approach, but it is hard to implement; our subsequent implementations need to approximate this direction.
Some Policies
FIFO
As the name suggests: whoever entered memory earliest is replaced first.
Problem: "entered earliest" $\neq$ "least important"
Random
As the name suggests.
- Random isn't necessarily particularly good;
- But it has one advantage: no particularly strange fixed bad patterns.
Although it isn't clever, it also isn't as prone as FIFO to performing especially terribly on certain special access sequences.
LRU
- If a page was recently accessed, it will likely be accessed again soon
- If a page hasn't been touched in a long time, it is more like a candidate for sacrifice
It relies on locality: temporal locality & spatial locality
This leads to LRU (Least Recently Used):
- Evict the page that was least recently accessed
LRU's failure scenario: cyclic sequential scanning
For example, with 50 pages total, suppose memory can only hold 49 pages, and the program keeps accessing in order:
0,1,2,3,...,49,0,1,2,3,...,49 ...But this is extremely bad for both LRU and FIFO, with a hit rate close to 0%.
LRU depends heavily on locality.
Perfect LRU is hard to implement efficiently, because it is difficult to track recent accesses — memory accesses are extremely frequent.
Clock: An Approximation of LRU
- Arrange the physical pages in a ring;
- Maintain a "clock hand" rotating over it;
- Each page has a reference bit / use bit.
When a page needs to be evicted, Clock works like this:
- Look at the page the hand currently points to.
- If its
use bit = 1, it was accessed recently and we don't want to evict it immediately. - Then clear its
use bitto 0, and the hand continues moving forward. - If a page's
use bit = 0is seen, it means it hasn't been accessed again recently, so it is chosen as the victim.
flowchart TD
A["需要淘汰页面"] --> B["看时钟指针当前页"]
B --> C{"use bit = 1 ?"}
C -->|是| D["清零 use bit"]
D --> E["指针前进到下一页"]
E --> B
C -->|否| F["选择该页作为 victim"]
Dirty Pages
- If a page hasn't been modified, it is a clean page
- If a page has been modified, it is a dirty page
Evicting a clean page is cheap, because it doesn't need to be written back to disk. Evicting a dirty page is often more expensive, because it must first be written back to disk.
If two candidate pages are roughly equal, it is usually preferable to evict the clean page first rather than the dirty page.
This seems contrary to the philosophy of LRU, but real-world algorithms do indeed take this into account.
Thrashing
When the OS is completely overloaded:
- Memory is clearly insufficient;
- The system swaps pages constantly;
- Pages are swapped in only to be swapped out again;
- The CPU spends a large amount of time on paging rather than doing truly useful work.
At this point the swapping strategy largely fails, and the OS will decide to suspend some memory-hungry processes or even kill them outright.
Summary by GPT
- The root question of this chapter is: when a page fault occurs and memory is full, who should be kicked out.
- The optimal policy is "evict the page used latest in the future," but real systems can only approximate it with historical information, hence LRU and Clock.
- Real page replacement isn't just about an algorithm's name; it must also face practical issues like locality, dirty page costs, the bad sequential-scan example, and thrashing.
Chapter 23: The VAX/VMS Virtual Memory System
This chapter studies a real, complete virtual memory system. A complete system is the result of many design compromises, not just a stack of individual mechanisms.
VAX/VMS
The virtual address space is 32 bits, and the page size is only 512B. The smaller the pages, the more pages there are, and the linear page table becomes very large.
[!TIP] $$ 页数=\frac{虚拟地址空间大小}{页大小} $$
VAX/VMS first divides the address space into three large regions: P0, P1, and S;
- P0 manages code/heap, P1 manages the stack, and S manages the kernel.
- P0 and P1 are each paged separately and each have their own page table, so there is no need to waste page table entries on the large hole between the heap and the stack.
- Furthermore, the user page tables themselves are placed in kernel virtual memory, so the page tables can also be managed by the VM system; this saves memory, because user page tables can also be swapped out. But the address translation path becomes more complicated.
There are also several design points:
- The kernel is mapped into every process's address space, that is, every process's virtual space contains the kernel (note: the virtual space), but in reality they all point to the same region of physical memory storing the kernel; although user programs "share the kernel mapping in the same address space," they have no permission to read or write it
- VMS has no
reference bit, but the OS can useprotection bitto restrict read/write permissions and simulate it via traps - Page 0 is defined as invalid, making it easy to make null-pointer accesses invalid
- It uses a resident set size (RSS), which is an upper limit on how many page frame entries each process can have in physical memory; when exceeded, FIFO is used to perform swapping
- In the FIFO swapping policy, the one at the tail of the queue gets swapped out, but there is also a second chance: the clean-page list and the dirty-page list. This can be understood as temporarily swapping it out, but it is still in physical memory; if it is requested again later, there is no need to run disk I/O again
- Demand-zero: a paradigm of the OS's lazy optimization. After a user requests a block of memory, the heap region's memory needs to be cleared (accessing remnants of a previous process is risky), but what actually happens is that the OS first records this page, and the clearing operation is only performed when it is actually called
- Copy-on-right: if a copy is needed, it is not actually copied immediately; instead, a mapping is first established and both are marked read-only, and only when one side needs to write is a trap triggered and a real copy created