Operating Systems · Lecture Notes

Chapter 8: Memory Management

A program can run only after it has been loaded into main memory. The CPU reads instructions and data only from registers and main memory; the disk is a slow store reached only through I/O operations. In a system that runs many processes at once, main memory has to be shared among them. Sharing raises three questions. How can one process be kept from reaching another's memory? How do addresses stay correct when a program is loaded anywhere in memory? How is free space tracked, and how is it kept from breaking into pieces? These notes begin with the memory hierarchy and the cache. They then describe address translation, starting from base and limit registers. Binding and loading, swapping, contiguous allocation, and free-space management follow. The emphasis is on paging, the foundation of today's systems: the page table, the TLB, effective access time, and multilevel, hashed, and inverted tables. The last sections cover segmentation and compare the real designs of x86-64, ARMv8, and RISC-V.

Learning outcomes

Abstraction
Explain the memory hierarchy, cache lines, and average access time; explain the address space and the problems of protection and relocation.
Addresses
Explain binding times, the distinction between logical and physical addresses, and the MMU's base–limit check.
Linking
Discuss dynamic loading, static and dynamic linking, shared libraries with the PLT/GOT, and swapping.
Contiguous allocation
Apply the fit algorithms to a request sequence; analyze internal and external fragmentation, bitmaps, and linked lists.
Paging
Split an address into (p, d), translate with a page table and a TLB, and compute the effective access time.
Real systems
Compare hierarchical, hashed, and inverted tables; four- and five-level paging on x86-64; huge pages; segmentation; and ARMv8.

8.1Memory hardware

To understand memory management one must first look at memory itself. The operating system sees memory as an abstract array of bytes, but behind that array lie several layers of very different speeds and sizes. Knowing which layer the hardware manages and which the operating system manages explains all the later design decisions.

8.1.1The memory hierarchy and the memory manager

The CPU can reach storage directly in only two places: registers and main memory. An instruction takes its operand from a register or from memory; it cannot reach data on disk directly. Data on disk must first be brought into memory by an I/O operation. That is why the code and data of a running program must be in main memory.

The memory unit also offers a very simple interface. It receives only a stream of addresses: either “read this address” or “write this data to this address.” The memory unit does not know where an address came from. It may have been produced from a program counter, an array index, or a pointer; to memory they are all the same. This simplicity also shows why a layer of hardware that modifies addresses before they reach memory is possible.

The speed gap is very large. A register is read in one clock cycle. A DRAM access in main memory takes hundreds of cycles, and the CPU stalls in the meantime. The gap is closed by small, fast memories inside the processor, the caches. Figure 8.1 shows typical values today: registers under a nanosecond, L1 and L2 cache 1–5 ns, L3 10–20 ns, DRAM 80–120 ns, NVMe SSD 10–100 µs, hard disk 5–10 ms. Going from top to bottom, latency and capacity grow and the cost per byte falls.

Registers< 1 ns~1 KBL1 / L2 cache1–5 nsKB–MBL3 cache10–20 ns10–100+ MBMain memory (DRAM)80–120 ns8–512 GBSSD (NVMe)10–100 µsTBHDD / tape5–10 msTB+fast, small, expensiveslow, large, cheap, nonvolatilelatency
Figure 8.1: The memory hierarchy. From registers toward disk, latency and capacity grow. The values are typical orders of magnitude as of 2026; they vary with core and model.

What a programmer expects of memory is in fact an impossible list: that it be unlimited, very fast, persistent, and protected. No single technology gives all these properties at once. The real solution is the hierarchy. Small, fast layers hold the frequently used data, and large, slow layers hold the rest. A well-built hierarchy gives the programmer the impression of a memory “almost as fast as the top layer and almost as large as the bottom layer.”

Different managers control the layers of the hierarchy. Hardware manages the caches entirely; the operating system does not interfere with their contents. The operating system manages main memory. The part of the operating system that handles this job is called the memory manager.

Definition 8.1

Memory management is the sharing of main memory among processes. The memory manager keeps track of which regions of memory are free and which are in use; it allocates memory to processes, takes it back when they finish, and protects processes from one another. When memory runs short, moving some of the processes or pages to disk is also its job.

The memory manager's job is often confused with the CPU scheduler's job. Choosing the next process from the ready queue is the scheduler's task. The memory manager deals with questions such as “which process is where, how much room does it occupy, and how much more can be given to whom.”

8.1.2Types of main memory

In everyday language the word “memory” is used for several different kinds of hardware. Table 8.1 compares the four basic types. The type used as main memory is RAM (random access memory). RAM can be read and written, is fast, but is volatile: its contents are lost when power is cut. DRAM cells are tiny capacitors, and because charge leaks away they must be refreshed at regular intervals. SRAM needs no refresh and is faster, but it is more expensive and takes more space. That is why main memory is DRAM (today DDR5, LPDDR5X) and the caches are SRAM.

Table 8.1: Types of main memory.
TypePropertiesUse
RAM (random access)Readable and writable, fast, volatile. DRAM needs refresh; SRAM is faster and more expensive.Main memory (DRAM: DDR5, LPDDR5X), caches (SRAM)
ROM (read-only)Written at manufacture, cannot be changed, persistent, cheap.Simple devices, fixed code in microcontrollers
EEPROM / FlashCan be erased and rewritten electrically, persistent; writes are slow and write endurance is limited.UEFI/BIOS firmware (SPI flash), SSDs, USB sticks, phone storage (NAND flash)
CMOS / NVRAMA small area kept alive by a battery or flash.Clock, boot settings

ROM (read-only memory) is written during manufacture and cannot be changed afterward. It is persistent and cheap; in simple devices and microcontrollers it holds code that will never change. EEPROM and its variant flash memory can be erased and rewritten electrically. They are persistent, but writing is much slower than reading, and a cell can be written only a limited number of times. In today's computers the BIOS/UEFI code is not in ROM but on an SPI flash chip on the motherboard, which is why firmware can be updated. SSDs, USB sticks, and phone storage also use NAND flash. Finally, CMOS or NVRAM is a small area kept alive by a battery or flash; the clock and the boot settings are kept there.

Memory management is concerned with only one of these types: the main memory in which processes run, that is, DRAM. In the rest of the chapter the word “memory” is used in this sense.

8.1.3Cache lines and locality

Data moves between the cache and main memory not byte by byte but in fixed-size blocks. This block is called a cache line. In most processors today a line is 64 bytes. Memory is thought of as divided into consecutive lines of this size: line 0 covers addresses 0–63, line 1 covers 64–127, and so on.

Which line an address a lies in is found by a simple division. The line number is ⌊a / 64⌋ and the position within the line is a mod 64. Since 64 = 26, the division is really a bit-splitting operation: the low 6 bits of the address give the position within the line, and the remaining upper bits give the line number. Figure 8.2 takes address 200 as an example. In binary 200 is 11001000. The low six bits are 001000, that is, 8; the upper two bits are 11, that is, 3. Indeed 3 × 64 + 8 = 200.

Address 200 (64 B lines):11001000line no = 3offset within line = 8 (6 bits)line 00–63line 164–127line 2128–191line 3192–255
Figure 8.2: Splitting address 200 with 64-byte lines: the upper bits give line number 3, the low 6 bits give offset 8 within the line.

When the CPU reads a word, the hardware looks in the cache first. If the line is in the cache, this is a hit, and the data arrives from L1 in 4–5 cycles. If not, there is a miss; the request goes down a level, in the worst case to DRAM, and takes hundreds of cycles. Because the cache is expensive it is small. Instead of one big cache, levels such as L1, L2, and L3 are built, each larger and slower than the one before.

A small cache is useful in front of a large memory because of how programs behave. Programs do not access memory at random; their accesses follow two patterns.

Temporal locality
A piece of data used a moment ago is used again soon. A loop counter, the instructions of a loop body, and a frequently called function are examples.
Spatial locality
A program that accesses one address soon accesses neighboring addresses too. Walking through an array from start to end and executing consecutive instructions are examples.

The cache line exploits spatial locality: because all 64 bytes are fetched on a miss for one byte, later accesses to neighboring bytes are hits. Temporal locality is exploited by the line staying in the cache.

8.1.4The path of a read through the hierarchy

Suppose the CPU wants to read variable x with the instruction LOAD R1, [x]. The hardware first looks at the nearest and fastest level, L1. If the line is not in L1, about 1 ns has been lost and the search continues in L2. If L2 and L3 miss too, the latencies of the levels add up: 1 + 4 + 15 = 20 ns. Finally the data comes from DRAM; this adds about 80 ns, for a total of 100 ns (Figure 8.3).

CPU(register)L1~1 nsmisslineL2~4 nsmisslineL3~15 nsmisslineDRAM~80 nstotal latency: ~100 ns
Figure 8.3: A read that misses at all three levels. The data comes from DRAM; not a single word but the whole 64-byte line is placed in L3, L2, and L1. The total latency is about 100 ns.

What comes from DRAM is not a single word but the whole 64-byte line containing the word. On the way the line is placed in L3, L2, and L1 as well. When another piece of data in the same line is accessed a second time, it is now an L1 hit and about 1 ns suffices (Figure 8.4). The 100 ns cost of the first access is thus shared with the accesses to the rest of the line. This is the locality that makes the cache worthwhile.

CPU(register)L1~1 nslineL2~4 nslineL3~15 nslineDRAM~80 nshit!total latency: ~1 ns
Figure 8.4: A second access to the same line is an L1 hit; the latency drops to about 1 ns.

8.1.5Code trace: a direct-mapped cache

Where in the cache can a line be placed? The simplest answer is direct mapping: the cache is divided into a number of sets, and each block can go to only one set. If the block number is b and the number of sets is K, block b goes to set b mod K. If another block is currently in the set, the newcomer evicts it.

The C fragment below simulates a direct-mapped cache with four sets and 64-byte lines. The array tag records which block is currently in each set; −1 means empty.

int addr[6] = {0, 8, 64, 256, 0, 72};
int tag[4] = {-1, -1, -1, -1};
int hits = 0, misses = 0;
for (int i = 0; i < 6; i++) {
  int block = addr[i] / 64;
  int set = block % 4;
  if (tag[set] == block) hits++;
  else { tag[set] = block; misses++; }
}

For each address the loop first computes the block number (addr / 64) and then the set (block % 4). If the tag in the set equals this block, the hit counter is incremented. Otherwise the block is written into the set and the miss counter is incremented. In this simplified model the whole block number is stored as the tag. Real hardware already knows the set number from the address, so it stores only the upper bits, the real tag.

Table 8.2: Trace of the direct-mapped cache code (4 sets, 64 B lines). The values were verified by recomputing them in Python.
iaddrblocksetResulttag[0..3] afterwardsComment
0000miss0, −1, −1, −1set 0 empty
1800hit0, −1, −1, −18 is in the same line as 0: spatial locality
26411miss0, 1, −1, −1set 1 empty
325640miss4, 1, −1, −1block 4 evicts block 0 (conflict miss)
4000miss0, 1, −1, −1block 0 evicts block 4 (conflict miss)
57211hit0, 1, −1, −172 is in the same line as 64

When the loop ends, hits = 2 and misses = 4; the hit rate is 33%. Two different kinds of miss show up in the trace. The first three misses are unavoidable: the blocks come into the cache for the first time. These are called compulsory misses. The misses at steps 3 and 4 have a different cause. Addresses 0 and 256 are in different blocks (0 and 4), but both fall into set 0. Although sets 2 and 3 of the cache sit empty, these two blocks evict each other. This kind of miss is called a conflict miss.

Access sequence0M8H64M256M0M72HCache (4 sets)setblock (tag)0block 01block 12—3—
Figure 8.5: The final state of the direct-mapped cache trace. M marks a miss and H a hit. Because 0 and 256 fall into the same set, they evicted each other.

The way to reduce conflict misses is to give a block more than one place. In a k-way set-associative cache each set holds k lines. A block still goes to a single set, but it can be placed in any of the k slots of that set.

Example 8.1

Let the same four-line cache be organized as 2 sets with 2 ways, and let the least recently used line be evicted when a set needs room. How many hits are there on the same sequence 0, 8, 64, 256, 0, 72?

  1. Sets. The blocks are 0, 0, 1, 4, 0, 1. The set number is now block mod 2: 0, 0, 1, 0, 0, 1.
  2. Trace. 0: set 0 empty, miss. 8: block 0 is in set 0, hit. 64: set 1 empty, miss. 256: block 4 goes to set 0; since the set has one more free slot, block 0 stays where it is, miss. 0: block 0 is still in set 0, hit. 72: block 1 is in set 1, hit.
  3. Result. 3 hits, 3 misses. Direct mapping had 2 hits. The gain comes entirely from the disappearance of the conflict miss.
Common mistake

Computing the set number from the address itself (for example 256 mod 4 = 0, 72 mod 4 = 0). What determines the set is not the address but the block number. First the address is divided by the line size, then the remainder of the block number modulo the number of sets is taken: 72 / 64 = 1, 1 mod 4 = 1.

8.1.6Code trace: average access time

How well a hierarchy works can be summarized in a single number: the average memory access time. Every access first goes to the top level and spends that level's time. If it misses, the request goes down a level and that level's average time is added. If a level's time is s, its miss rate is m, and the average time of the level below is Tbelow:

T = s + m · Tbelow

The formula repeats itself: the time of the level below is computed in the same way. DRAM, at the very bottom, satisfies every request, so there T is just DRAM's time. The code below does the computation from the bottom up.

/* L1, L2, L3, DRAM access time (ns) */
double lat[4] = {1, 4, 20, 80};
double miss[3] = {0.10, 0.40, 0.50};
double t = lat[3];          /* DRAM */
for (int k = 2; k >= 0; k--)
  t = lat[k] + miss[k] * t;
printf("average = %.1f ns\n", t);

t starts with DRAM's 80 ns. The loop goes down from k = 2 (L3) to k = 0 (L1) and computes the time of the next level up in each round. Table 8.3 shows each round.

Table 8.3: Trace of the average-access-time code. The values were verified by recomputing them in Python.
StepkLevelComputationt (ns)
start—DRAMt = lat[3]80
12L320 + 0.50 × 8060
21L24 + 0.40 × 6028
30L11 + 0.10 × 283.8
end−1—the loop ends, average = 3.8 ns is printed3.8
L11 nsmiss 10%t(L1) = 3.8 nsL24 nsmiss 40%t(L2) = 28.0 nsL320 nsmiss 50%t(L3) = 60.0 nsDRAM80 nst(DRAM) = 80.0 nsaverage = 3.8 ns
Figure 8.6: Access times and miss rates of the four levels, and the average times computed from the bottom up.

The result is striking. Although 10% of all accesses miss L1, the average is 3.8 ns. That is about 21 times faster than DRAM's 80 ns (80 / 3.8 ≈ 21.05). What makes the hierarchy worthwhile is the high hit rate at the upper levels.

The form of the formula also shows how much the miss rates matter. If L1's miss rate falls from 10% to 5%, the 28 ns below stays the same and the average becomes 1 + 0.05 × 28 = 2.4 ns. Reducing L1's own time from 1 ns to 0.5 ns saves only 0.5 ns. Misses dominate the average.

Example 8.2

L1 responds in 2 ns and misses on 5% of requests. L2 takes 10 ns and misses on 20% of the requests that reach it. DRAM takes 100 ns. What is the average access time? What would it be without L2?

  1. The L2 level. TL2 = 10 + 0.20 × 100 = 30 ns.
  2. The L1 level. T = 2 + 0.05 × 30 = 2 + 1.5 = 3.5 ns.
  3. Without L2. The L1 misses go straight to DRAM: 2 + 0.05 × 100 = 7 ns. The second level has halved the average.
Common mistake

Expressing the second level's miss rate relative to all accesses. L2's 20% miss rate applies to the requests that reach L2; only 5% of all accesses reach L2. So the fraction of accesses that go down to DRAM is not 20% but 0.05 × 0.20 = 1%. The formula performs this multiplication automatically.

8.1.7The four questions of cache design

Every cache design has to answer four questions.

  1. When is data put into the cache? Usually on a miss. The hardware also fetches the next lines ahead of time (prefetch) by predicting the access pattern.
  2. Where is it put? This is the mapping question: direct-mapped, k-way set-associative, or fully associative.
  3. Which line is evicted when room is needed? This is the replacement policy: approximations of LRU, random choice, or FIFO.
  4. Where does the evicted line go? If the line has been modified (is “dirty”), it is written to the level below when evicted (write-back). The other option is to pass every write to the level below at once (write-through).

Besides these four questions there are three trade-offs. A big cache gives more hits but is slower and more expensive. A smarter replacement policy increases hits but complicates the hardware. In multicore processors, copies of the same line in different cores have to be kept up to date; this is called coherence and is provided by protocols such as MESI.

The same four questions are not specific to hardware caches. They also appear in the “caches” managed by the operating system: the page cache that holds files, virtual memory, and the TLB. The TLB described in these notes is a cache directly; virtual memory uses main memory as a cache for the disk.

8.2The address space

For several programs to run safely in the same memory, two problems must be solved. The first is protection: a program must not be able to reach another program's memory. The second is relocation: a program must work correctly wherever in memory it is loaded. This section describes where the two problems come from and the simplest hardware solution.

8.2.1Memory without abstraction

The earliest computers had no abstraction for memory. On mainframes before the 1960s and personal computers before the 1980s every program saw physical memory as it was. The instruction MOV REGISTER1, 1000 read the word at physical address 1000. The address the program saw was the same as the address the memory chip saw.

In this arrangement two programs cannot be in memory at the same time. Both use the same physical addresses, and one overwrites the other's data. Memory can still be shared between the operating system and a single user program. Figure 8.7 shows three common layouts. In (a) the operating system is at the bottom of RAM. In (b) the operating system is at the top, in ROM. In (c) the device drivers are at the top in ROM and the rest of the operating system is at the bottom in RAM. In layouts (a) and (c) a bug in the user program can write into the region holding the operating system and crash it. Layout (b) was used in some embedded systems, and (c) in the first PCs running MS-DOS, where the BIOS drivers were in ROM.

User programOS (RAM)(a)0OS (ROM)User program(b)0Drivers (ROM)User programOS (RAM)(c)00xFFF…
Figure 8.7: Three ways of sharing memory between the operating system and a single user program without abstraction.

This approach has not become history. Microcontrollers without a memory management unit still work this way today. Most of them nevertheless have a memory protection unit (MPU). An MPU does no address translation; it only checks access permissions for certain regions.

8.2.2The relocation problem

The problem that arises when two programs are put in memory at once is shown clearly by Tanenbaum's example. A and B are two 16 KB programs, both compiled on the assumption that they start at address 0. A's first instruction is JMP 24 and B's first instruction is JMP 28. The operating system loads A at address 0 and B right above it, at address 16384.

A runs without trouble. B crashes at its first instruction. JMP 28 wants to jump to the CMP instruction at byte 28 of B. But 28 is an absolute address, and at physical address 28 there is A's ADD instruction. Instead of its own code, B jumps into the middle of A (Figure 8.8).

(a) Program AJMP 240ADD4MOV8⋮MOV24ADD28⋮…16380(b) Program BJMP 280MOV REG1, 284ADD8⋮MOV24CMP28⋮…16380(c) both togetherJMP 240ADD4MOV8⋮MOV24ADD28⋮JMP 2816384MOV REG1, 2816388ADD16392⋮MOV16408CMP16412⋮jumpsinto A!
Figure 8.8: The relocation problem. (a) and (b) two programs compiled to start at 0, (c) both in memory together. B's JMP 28 jumps into A.

This is called the relocation problem. The addresses in a program must be corrected according to where the program is loaded in memory. The first solution, found on the IBM 360, is static relocation: when the loader puts the program into memory, it adds the program's starting address to every address word. Since B is loaded at 16384, JMP 28 becomes JMP 16412 (Figure 8.9).

(a) Program AJMP 240ADD4MOV8⋮MOV24ADD28⋮…16380(b) Program BJMP 280MOV REG1, 284ADD8⋮MOV24CMP28⋮…16380(c) both togetherJMP 240ADD4MOV8⋮MOV24ADD28⋮JMP 1641216384MOV REG1, 2816388ADD16392⋮MOV16408CMP16412⋮+16384constant 28 must not change!
Figure 8.9: Static relocation. The loader adds 16384 to the jump address; but the 28 in MOV REG1, 28 is a constant and must not change.

Static relocation has two weaknesses. First, loading becomes slower, because every word of the program has to be examined. The second is subtler: the loader cannot tell which words are addresses and which are ordinary numbers. B's second instruction MOV REG1, 28 loads the number 28 into a register. This 28 is not an address; if 16384 is added to it, the program goes wrong. For the loader to decide correctly, the compiler has to produce extra relocation information indicating which words of the program are addresses.

8.2.3Base and limit registers

The abstraction that solves protection and relocation together is the address space.

Definition 8.2

An address space is the set of addresses a process can use in memory. Each process has an address space of its own, independent of those of other processes.

The simplest hardware for implementing an address space is two registers. The base register holds the process's starting address in memory, and the limit register holds the length of the region. The program is loaded as it is into a contiguous area of memory. In the example of Figure 8.10 the base is 300040 and the limit is 120900. The process can access addresses from 300040 to 300040 + 120900 − 1 = 420939.

Operating system0process256000process (active)300040process4209408800001024000300040base120900limit
Figure 8.10: Base and limit registers. The running process can access addresses from 300040 to 420939.

These two registers can be loaded only by privileged instructions, in kernel mode. A user program cannot change its own base or limit; if it could, protection would be meaningless. When the operating system switches context, it puts the new process's base and limit values into these registers.

History offers two extreme examples of this arrangement. The CDC 6600 supercomputer worked exactly this way. The segment registers of the Intel 8088 served only as a base; since there was no limit register, there was relocation but no protection.

8.2.4Hardware address protection

Base and limit registers provide protection with two comparisons on every memory access. The address produced by the CPU is first compared with the base: if the address is smaller than the base, a trap occurs. Then it is compared with base + limit: if the address is not smaller than this value, a trap occurs again. If both conditions hold, the access goes to memory (Figure 8.11). The comparisons are made by special hardware working in parallel and do not slow the access down.

CPUaddress420.940≥ base ?yes< base+limit ?MemoryTrap to the OS: addressing errornonobase = 300,040limit = 120,900valid: 300,040 … 420,939
Figure 8.11: Hardware address protection. Since 420940 = base + limit, the second comparison fails and a trap is raised to the operating system.
Table 8.4: Checking five addresses with base = 300040 and limit = 120900 (valid range 300040 … 420939).
Address≥ base?< base + limit?Result
300040yesyesaccess (first valid address)
356000yesyesaccess
420939yesyesaccess (last valid address)
420940yesnotrap
299999no—trap; another process's area is protected

When the trap occurs, control passes to the kernel. The kernel treats it as an addressing error and usually terminates the process; on Unix systems the process receives the signal SIGSEGV. The check is made only for accesses in user mode. In kernel mode there is no check, because the operating system must be able to reach all of memory: loading a process into memory and reading a system-call argument from a user buffer both require it.

Common mistake

Counting the address base + limit as valid. The limit is the length of the region; the valid addresses are base, base + 1, …, base + limit − 1. The last byte of a 120900-byte region is at 300040 + 120899 = 420939. 420940 is already outside the region.

8.2.5Address binding times

On its way from source code to a process in memory, a program passes through several stages (Figure 8.12). The compiler turns main.c into an object file (main.o). The linker combines this file with other object files and static libraries to produce the executable (a.out). The loader brings this file into memory, adds the dynamic libraries, and the process starts to run.

Sourcemain.cObjectmain.oExecutablea.outIn memoryprocesscompilerlinkerloader+ other .o, static .a+ dinamik .so (ld.so)MMUon every accesscompile timeload timeexecution time
Figure 8.12: A program passing through the compiler, linker, and loader and being placed in memory. Address binding can be done at any one of these three stages.

Addresses change form along this journey. In source code addresses are symbolic: the programmer writes a variable called count. The compiler binds this symbol to a relative address: “14 bytes from the start of this module.” The linker or loader converts the relative address into an absolute one, for example 74014. When a symbol is bound to an absolute address determines whether the program can be moved in memory. Table 8.5 compares the three options.

Table 8.5: Address binding times.
Binding timeCode producedIf the location changesHardware
Compile timeAbsolute code (e.g. MS-DOS .COM)recompilenot needed
Load timeRelocatable code; the loader fixes the addressesreloadnot needed
Execution timeLogical addresses; can be moved while the process runsnothingMMU (base–limit, paging)

In compile-time binding the compiler knows in advance where in memory the program will be loaded and produces absolute code. MS-DOS .COM files were like this. If the starting address changes, the program has to be recompiled. In load-time binding the compiler produces relocatable code; the absolute addresses are fixed at load time by static relocation. If the starting address changes, the program is reloaded. In execution-time binding, address translation is done on every access while the program runs. A process can be moved from one memory region to another while it is running. Special hardware is needed for this. All of today's general-purpose operating systems use execution-time binding.

8.2.6Logical and physical addresses, the MMU

Execution-time binding separates two kinds of addresses.

Definition 8.3

A logical address, also called a virtual address, is the address the CPU produces. A physical address is the address the memory unit sees, the one loaded into the memory address register (MAR). The set of all logical addresses a program produces is the logical address space, and the set of the corresponding physical addresses is the physical address space.

In compile-time and load-time binding the two addresses are the same. In execution-time binding they differ, and the conversion between them is done at run time by a piece of hardware: the memory management unit (MMU). The program sees and works with logical addresses only; it never sees physical addresses. A C program that prints the value of a pointer therefore always prints a logical address.

CPU chipCPUMMUvirtualphysical addressbusMemoryDisk controller
Figure 8.13: The MMU is inside the processor chip. The CPU gives the virtual address to the MMU; the MMU puts the physical address on the bus.

Figure 8.13 shows where the MMU sits. In older systems the MMU was a separate chip. In today's processors the MMU, with its TLBs and page-table walker, is inside every core. Every address that goes out on the memory bus is already a physical address.

8.2.7Dynamic relocation with the MMU

In its execution-time form, the base–limit arrangement has the MMU do two jobs. First it compares the logical address with the limit; if the address is not smaller than the limit, it raises a trap. Then it adds the base value to the address and obtains the physical address. Silberschatz calls this register the relocation register; it is the same thing as Tanenbaum's base register.

CPUlogical346< limit ?3.000limit registeryes+14.000base (relocation)physical14.346Memorynotrap: addressing error
Figure 8.14: Dynamic relocation with the MMU. Logical 346 is less than the limit 3000; it is added to the base and physical 14346 results.
Example 8.3

Let the limit be 3000 and the base 14000. Where do logical addresses 346, 2999, and 3500 go?

  1. 346. 346 < 3000, valid. The physical address is 346 + 14000 = 14346.
  2. 2999. 2999 < 3000, the last valid logical address. Physical 2999 + 14000 = 16999.
  3. 3500. 3500 ≥ 3000: a trap occurs before any addition. Because the comparison is made on the logical address, the result is the same whatever the base value is.

The program sees itself as occupying 0 through 2999. If the operating system moves the process somewhere else, it changes only the base register; not a single address in the program changes.

This arrangement also rescues program B in the relocation example. For B let base = 16384 and limit = 16384. The instruction JMP 28 stays in memory as it is. When the instruction executes, the MMU compares 28 with the limit, finds it valid, and produces the physical address 28 + 16384 = 16412 (Figure 8.15). Neither static relocation nor extra relocation information is needed; the constant in MOV REG1, 28 never changes, because only addresses that go to memory are translated.

CPUlogical28< limit ?16.384limit registeryes+16.384base (relocation)physical16.412Memorynotrap: addressing error
Figure 8.15: Program B runs with base = limit = 16384. JMP 28 stays unchanged; the MMU produces 16412.

This has a price: every memory access needs an addition and a comparison. The comparison is fast. The addition, because of carry propagation, remains slow relative to an access unless special circuits are used. This price is the first sign of a problem that will grow with paging: address translation lies on the path of every access, and it has to be very fast.

8.3Linking and loading

Loading a program into memory is not as simple as “copy the whole file into memory.” The program refers to libraries; will these libraries be loaded together with the program or separately? Should a large piece of code that may never be used be loaded up front? This section describes today's answers to these questions.

8.3.1Dynamic loading

Dynamic loading means that a routine is not brought into memory until it is called. The main part of the program is loaded and starts to run. When a routine is needed, the program has it loaded itself. Code that is never called is never loaded. This is useful for large but rarely executed parts such as error-handling code.

Dynamic loading needs no special hardware; the program is designed accordingly. The operating system only provides the necessary library functions. On POSIX systems these are dlopen, dlsym, and dlclose; their Windows counterparts are LoadLibrary and GetProcAddress. The program below loads the math library at run time and calls the sqrt function in it.

#include <dlfcn.h>
#include <stdio.h>

int main(void) {
  void *h = dlopen("libm.so.6", RTLD_LAZY);
  if (!h) { puts(dlerror()); return 1; }
  double (*root)(double) =
      (double (*)(double)) dlsym(h, "sqrt");
  printf("%.3f\n", root(2.0));
  dlclose(h);
  return 0;
}

The program runs line by line as follows.

  1. When the program starts, the address space contains only the code of main, the C library (libc), the heap, and the stack. The math library (libm) is not loaded.
  2. The call dlopen("libm.so.6", RTLD_LAZY) runs the dynamic linker (ld.so). The dynamic linker finds the file and maps it into the process's address space with mmap (Figure 8.16). Loading happens at the program's request, now. The returned h is a handle that represents the library; if the file is not found, NULL is returned and dlerror() reports the reason.
  3. dlsym(h, "sqrt") looks up the name sqrt in the library's symbol table and returns its address in this process's address space. The returned void * value is cast to a function pointer that takes a double and returns a double.
  4. The call root(2.0) is made through the function pointer, and 1.414 is printed (√2 in the %.3f format).
  5. dlclose(h) decrements the library's reference count. When the count reaches 0, the library is removed from the address space.
mainheaplibmlibcstackprocess address space0high
Figure 8.16: The address space after dlopen: libm is mapped between main and libc.

With older glibc versions the option -ldl was needed when compiling this program. Since glibc 2.34 these functions are inside libc and no extra option is needed.

8.3.2Static and dynamic linking

When a program calls a library function, the code of that function has to be somewhere. There are two ways. In static linking the linker (ld) copies the library routines into the executable after compilation; for example ld *.o -lc -lm. In dynamic linking only a small stub is left in the file. The real address of the routine is resolved at run time. Table 8.6 compares the two approaches.

Table 8.6: Static and dynamic linking.
Static linkingDynamic linking
Who, and when?The linker (ld), after compilationThe dynamic linker (ld.so), at load time or at run time
File.a, .lib.so, .dll, .dylib
MemoryA separate copy in every programCode pages once in memory, shared
UpdatingMust relinkReplacing the library is enough (versioning: soname)
RiskLarge file; security patches are delayedVersion mismatch (“DLL hell”)

The biggest gain of dynamic linking is in memory. Hundreds of processes use the same C library. With static linking every process would contain a separate copy. With dynamic linking the library's code pages exist once in physical memory and are mapped into every process's address space (Figure 8.17). A library of this kind is called a shared library.

Process 1codedatalibc.sostackProcess 2codedatalibc.sostacklibc codeone copyphysical memory
Figure 8.17: Two processes map the same libc code pages into their own address spaces; there is a single copy in physical memory.

Updating also becomes easier. When a security hole is closed in the C library, it is enough to install the new library; all programs that use it get the patched version the next time they run. Statically linked programs carry the hole until they are relinked. To keep incompatible versions from being mixed, libraries have a version name (soname); the 6 in libm.so.6, for example, is such a version. The confusion that results when this precaution is not taken is known in the Windows world as “DLL hell.”

8.3.3Lazy binding: the PLT and GOT

Textbooks usually describe dynamic linking like this: when the stub is called for the first time, it finds the routine's address and replaces itself with that address. This account is conceptually right, but on systems that use ELF files, like Linux, what changes is not the code. The real mechanism rests on two tables.

PLT (procedure linkage table)
A table of small jump stubs in the executable. The program does not call printf directly but calls the stub printf@plt. This is the “stub” of the textbooks.
GOT (global offset table)
A per-process, writable table of addresses. The PLT stub jumps indirectly to the address the corresponding GOT entry points to.

On the first call the GOT entry points not to the real printf but to the dynamic linker's resolver. The resolver looks the symbol up in the loaded libraries, writes the address it finds into the GOT entry, and jumps to printf. Later calls follow the path PLT → GOT → printf; only one indirect jump is added. This arrangement is called lazy binding, because a symbol is resolved only when it is first used. Table 8.7 lists the steps.

maincall printf@pltPLT entryjmp *GOT[printf]GOT[printf]→ resolverld.so resolver_dl_runtime_resolvelibc: printfreal code1st call
Figure 8.18: The first call under lazy binding: the PLT goes to the resolver through the address in the GOT.
Table 8.7: The first and later calls of printf.
StepWhat happens?GOT[printf]
1main goes to the PLT stub with call printf@plt.resolver
2The PLT jumps with jmp *GOT[printf] to the address in the GOT; this address is the resolver.resolver
3The ld.so resolver looks up the symbol and writes the address it finds into the GOT entry.printf
4The resolver jumps to printf. The code pages did not change; only the process-specific GOT page did.printf
5Later calls: PLT → GOT → printf, a single indirect jump.printf

That what changes is the GOT and not the code is critical for sharing. Since the code pages are never written, they remain shareable among all processes. Only each process's own GOT page is different. This work is done not by the operating system but by the dynamic linker running in user space.

Lazy binding has a weakness from the security point of view: because the GOT is writable, an attacker can use a buffer overflow to change an address there and take over control. That is why many distributions compile programs with the -z now option. In this “full RELRO” arrangement all symbols are resolved at load time and the GOT is then made read-only.

Common mistake

Thinking that after the first call the target of the call printf@plt instruction changes, or that the body of libc's printf is rewritten. Neither happens: the code pages are read-only and shared among processes. The only place that changes is the process-specific GOT entry.

8.3.4Building static and shared libraries

Two kinds of library can be built from a C source file (func.c). A static library is built and used with these commands:

$ gcc -c func.c -o func.o
$ ar rcs libfunc.a func.o
$ gcc main.c -o main -static -L. -lfunc
$ ./main

The ar tool gathers object files into a single archive (libfunc.a). The linker copies from this archive only the objects the program actually uses. The -static option asks for the static version of the C library (libc.a) to be used as well; the result is a file that depends on no shared library.

For a shared library the steps are as follows:

$ gcc -fPIC -c func.c -o func.o
$ gcc -shared -o libfunc.so func.o
$ gcc main.c -o main -L. -lfunc
$ export LD_LIBRARY_PATH=$(pwd)
$ ./main
$ ldd ./main   (libfunc.so => ./libfunc.so)

The key option here is -fPIC: position-independent code. Code compiled this way uses no absolute addresses. Jumps are made relative to the program counter, and global data is reached through the GOT. This allows the same physical page to be mapped at a different virtual address in each process. Address space layout randomization (ASLR) also rests on this. The ldd command shows which shared libraries the program will take from which files.

static: a copy in every programmain1funcmain2funcshared: one copy, two mappingsmain1main2libfunc.so
Figure 8.19: With static linking the library code is copied into every program; with a shared library a single copy is mapped into the address spaces of two processes.

The LD_LIBRARY_PATH variable is handy for experiments but is not a permanent solution. The permanent solution is either to embed the library's search path in the executable (-Wl,-rpath,'$ORIGIN') or to install the library in a system directory and run ldconfig. Today's distributions also compile the programs themselves as position-independent executables (PIE). In this way the program's own code is also loaded at a different address on each run, thanks to ASLR.

8.4Swapping

What happens if the total needs of the processes in memory exceed physical memory? One solution is to move the processes that are not running at the moment to disk temporarily. This idea is called swapping.

8.4.1Standard swapping

In standard swapping an entire process is written temporarily to a backing store, usually a fast disk. When the process is about to run again, it is brought back into memory (Figure 8.20). Thanks to swapping, the total memory needs of the processes can exceed physical memory and more processes can be run at the same time; that is, the degree of multiprogramming rises.

Operating systemuser spaceP1(room for P2)main memoryP1P2backing store① swap out② swap in
Figure 8.20: Standard swapping: the whole of process P1 is written to the backing store and P2 is read into memory.

A process returning from a swap may be placed not at its earlier location in memory but in some other place that happens to be free. That is why swapping requires execution-time binding. A process bound at compile or load time can return only to exactly its old place.

The cost of standard swapping is the transfer time. In Silberschatz's example a 100 MB process is written to a disk with a transfer rate of 50 MB/s. Writing it out takes 100 / 50 = 2 s and reading it back takes another 2 s; the round trip is 4 seconds. During this time the swapped process cannot run.

There is one more constraint in choosing the process to swap: a process with a pending I/O operation should not be swapped out. If the process is waiting for data from a device, the device will write the data into the process's buffer by direct memory access (DMA). If the process is swapped out and another is loaded in its place, the DMA transfer writes to the old physical address, that is, now into another process's memory. The remedy is either not to swap such a process or always to perform I/O through kernel buffers.

Example 8.4

A 200 MB process is swapped to a disk with a transfer rate of 50 MB/s; latencies are ignored. How long does the round trip take?

  1. Out. 200 / 50 = 4 s.
  2. In. Again 4 s.
  3. Total. 8 s. Considering that a time slice is tens of milliseconds, it is clear why moving a whole process is not acceptable today.

8.4.2Page swapping and today's systems

Today the sizes of processes are measured in gigabytes. A 1 GiB process takes about 2 × 1.07 / 3 ≈ 0.72 s for a round trip even on an NVMe SSD with a 3 GB/s read-write rate. That is why Linux, Windows, and macOS swap processes not as wholes but page by page (Figure 8.21). Only pages that have not been used for a long time, the “cold” pages, go to disk. A 4 KiB page comes back in tens of microseconds.

main memoryP1 p0P2 p3P1 p2P3 p1swap spaceP1 p1P1 p4P2 p0P3 p0P2 p1page outpage in
Figure 8.21: Swapping with paging: not whole processes but individual pages are moved between memory and the swap area.

Today's systems use one more intermediate step before going to disk: compression. Cold pages are first compressed in memory to make them smaller. In Linux zswap and zram, in Windows memory compression, and in macOS the compressor do this. Decompressing a compressed page is much faster than reading it from disk.

On mobile systems the situation is different. The write endurance of flash memory is limited, and every write costs energy. That is why phones have either no traditional swap or a very limited one. Android compresses with zram; if memory is still short, lmkd kills background applications. iOS also uses compression and kills applications when necessary (jetsam). From the user's point of view this shows up as an application restarting from scratch when one returns to it in the background.

8.5Contiguous allocation

In a system that works with base and limit registers, each process occupies a single unbroken region of memory. This section describes how free regions are chosen in such a system and why, over time, they break up into small, useless pieces.

8.5.1Contiguous memory allocation

Memory is first divided into two regions: one for the operating system and the other for user processes. The operating system can be placed at the low or the high end of memory. The Linux and Windows kernels put it at high addresses. In the user region each process occupies a single contiguous region, and protection is provided by the base–limit registers.

Definition 8.4

Contiguous allocation is giving each process a memory region made up of a single run of consecutive addresses.

There are two ways of dividing the user region among processes. In fixed partitioning memory is divided in advance into a certain number of partitions of certain sizes; the MFT version of IBM OS/360 worked this way. One process goes into each partition, so the number of partitions determines the number of processes that can be in memory at once, that is, the degree of multiprogramming. If a small process goes into a large partition, the rest of the partition is wasted. In variable partitioning (OS/360 MVT), each process is given exactly the space it needs. The free blocks left between processes are called holes.

There is one more problem: processes grow. A program asks for space from the heap with malloc, and function calls deepen the stack. If another process sits right above a contiguous region, growth is impossible. That is why processes are left some room to grow from the start (Figure 8.22). In (a) only the data segment grows. In (b) the stack grows from top to bottom and the data from bottom to top, and the spare room lies between the two. When the process is swapped out and brought back, only the part it uses is moved, not the free room.

(a)B (room to grow)BA (room to grow)AOS(b)B stack ↓room for growthB data + codeA stack ↓room for growthA data + code
Figure 8.22: Leaving room for growing processes: (a) the data segment grows, (b) the stack grows down and the data grows up.

8.5.2Variable partitioning

In variable partitioning the operating system keeps a table or list: which regions belong to which processes and which regions are holes. When a process arrives, a hole large enough to take it is found. The process is placed at one end of the hole, and the remainder stays as a smaller hole. When the process ends, its space returns to the hole list and is merged at once with neighboring holes.

Let the first 128 K of a 1024 K memory belong to the operating system, and let processes be placed in the first hole that fits. Table 8.8 follows the events in order.

Table 8.8: A sequence of events under variable partitioning (1024 K memory, OS at 0–128 K). Holes are written as “size @ start”; retraced with Python.
EventPlacementHoles afterwards
start—896 K @ 128
A (320 K) arrives128–448576 K @ 448
B (224 K) arrives448–672352 K @ 672
C (288 K) arrives672–96064 K @ 960
A terminates—320 K @ 128, 64 K @ 960
D (256 K) arrives128–38464 K @ 384, 64 K @ 960
B terminates—288 K @ 384, 64 K @ 960
E (192 K) arrives384–57696 K @ 576, 64 K @ 960

D goes into the 320 K hole that A left, and a small 64 K hole remains. When B terminates, its 224 K area merges with the 64 K hole to its left and forms a single 288 K hole. If adjacent holes were not merged, no room could be found for a 288 K request. After E goes into this hole, the total free space is 96 + 64 = 160 K, but it is split into two pieces. If a 100 K process arrived, it would not fit, even though the total space is enough.

01024 KOS128 KD256 KE192 K96 KC288 K64 Kholes: 96 K @ 576, 64 K @ 960
Figure 8.23: The end of the event sequence: D, E, and C are in memory; the two holes of 96 K and 64 K are separate.

8.5.3Placement algorithms

If several holes could take an incoming request, which should be chosen? The classic answers to this question are as follows.

First fit
The list is scanned from the start and the search stops at the first hole that is large enough. It is fast. Over time, small holes accumulate at the head of the list.
Next fit
A variant of first fit; the search continues from where the previous search stopped, not from the start. In Bays's 1977 simulations it gives slightly worse results than first fit.
Best fit
The whole list is scanned and the hole closest in size to the request is chosen. It is slow unless the list is kept sorted by size. It leaves behind holes too small to be of any use.
Worst fit
The largest hole is chosen; the aim is for the remainder to stay large enough to serve another request. It does not give good results in simulations.
Quick fit
Separate lists are kept for frequently requested sizes (4 K, 8 K, 12 K …). Finding a suitable hole is very fast; but finding the neighbors of a freed block and merging them is expensive.

All the algorithms can be sped up by keeping separate lists for processes and holes: the search is then made in the hole list only. Today's malloc implementations (jemalloc, tcmalloc) use a generalized form of quick fit, size classes. The outcome of the simulations reported by Silberschatz and Knuth is clear. In terms of both time and memory utilization, first fit and best fit are better than worst fit. First fit is usually faster.

8.5.4Code trace: best fit

The function below performs a best-fit search in an array holding hole sizes. It shrinks the hole it finds by the size of the request and returns the hole's index; if there is no room it returns −1.

int best_fit(int hole[], int n, int req) {
  int best = -1;
  for (int i = 0; i < n; i++)
    if (hole[i] >= req &&
        (best == -1 || hole[i] < hole[best]))
      best = i;
  if (best != -1) hole[best] -= req;
  return best;
}
/* hole = 120, 450, 230, 300, 180 (K) */
/* best_fit(hole, 5, 210); best_fit(hole, 5, 160); */

The variable best is the index of the best candidate found so far; −1 means “no candidate yet.” For each hole the loop checks two conditions. The first is that the hole is large enough for the request (hole[i] >= req). The second is that either there is no candidate yet or this hole is smaller than the current candidate. If both hold, the candidate changes. When the loop ends, the chosen hole is shrunk by the size of the request. The function walks the whole list on every call, so it spends O(n) time for n holes.

Table 8.9: Two calls of the best_fit function (holes 120, 450, 230, 300, 180 K). The values were verified with Python.
Callihole[i]Decisionbest
req = 2100120120 < 210, does not fit−1
1450fits, first candidate1
2230fits, smaller than 4502
3300fits but larger than 2302
4180does not fit2
Returns 2; hole[2] = 230 − 210 = 20. Holes: 120, 450, 20, 300, 180.
req = 1600120does not fit−1
1450fits, first candidate1
220does not fit1
3300fits, smaller than 4503
4180fits, smaller than 3004
Returns 4; hole[4] = 180 − 160 = 20. Holes: 120, 450, 20, 300, 20.
req = 160 K120[0]450[1]20[2]300[3]20[4]
Figure 8.24: The hole list after the two calls. Best fit twice left a useless 20 K hole.

The trace shows the typical behavior of best fit: because it picks the hole closest to the request each time, very small remainders are left behind. Had the same two requests been served by first fit, both would have gone into the 450 hole: first 240, then 80 K would have remained. With worst fit, 210 K would again go into 450 (240 remains), and 160 K would go into 300, the largest hole at that moment (140 remains). Which remainders will be useful in the future depends on later requests.

8.5.5Four algorithms on the same request sequence

Silberschatz's classic exercise shows the difference between the algorithms in a single example.

Example 8.5

The holes, in address order, are 100, 500, 200, 300, and 600 K. The requests, in order, are 212, 417, 112, and 426 K. Where do first fit, next fit, best fit, and worst fit put each request?

  1. 212 K. First fit and next fit put it into the first sufficient hole, 500 (288 remains). Best fit puts it into the smallest of those that fit (500, 300, 600), namely 300 (88 remains). Worst fit puts it into 600 (388 remains).
  2. 417 K. In first fit 288 is not enough, so it goes into 600 (183 remains). Next fit continues the search after 500; 200 and 300 are not enough, and it goes into 600 (183 remains). In best fit the holes that fit are 500 and 600; it goes into 500 (83 remains). In worst fit the largest hole at that moment is 500 (600 is now 388); it goes into 500 (83 remains).
  3. 112 K. First fit searches from the start: 100 is not enough, 288 is (176 remains). Next fit stops at 183, the remainder of the 600 hole where it last stopped (71 remains). Best fit puts it into 200, the smallest of those that fit (88 remains). Worst fit puts it into 388, the largest hole (276 remains).
  4. 426 K. In first fit the largest hole is 300, in next fit 300, and in worst fit 300: there is no room and the request waits. Only in best fit is the 600 hole still whole; the request goes there (174 remains).

In this sequence only best fit can place all four requests. In the others the total free space is more than 426 K, but it is not a single piece.

100 K500 K200 K300 K600 KFirst fit212112176417183426 K waitsNext fit21228841711271426 K waitsBest fit417831128821288426174426 K → 600 K hole (174 K left)Worst fit41783212112276426 K waits
Figure 8.25: The state of the four algorithms after the same request sequence. Only best fit could place 426 K.

This result does not mean that best fit is always superior. The example is a sequence in which keeping the large hole whole pays off. With other sequences the outcome changes. Take, for instance, holes of 150, 400, 80, 250, and 600 K and requests of 230, 120, 380, and 90 K. This time worst fit cannot place the 380 K request, while first fit and best fit satisfy all four requests.

Common mistake

In worst fit, still counting the hole chosen by the first request as the largest hole for later requests. Holes shrink after every placement. After 212 K the 600 hole drops to 388; for 417 K the largest hole at that moment is now 500.

8.5.6Internal and external fragmentation

The problem that arises in variable partitioning and that we saw in the earlier examples is called external fragmentation.

Definition 8.5

External fragmentation is the situation in which there is enough total free memory to satisfy a request but that memory is not contiguous. Internal fragmentation, on the other hand, is the situation in which the block given to a process is larger than requested and the difference is wasted inside the block.

The extent of external fragmentation is summarized by Knuth's 50-percent rule. In a system running first fit, with N allocated blocks, on average about 0.5 N blocks are lost to fragmentation. The share of lost blocks is 0.5 N / (N + 0.5 N) = 1/3; that is, one third of memory can become unusable.

Internal fragmentation appears in every arrangement that works with fixed-size blocks: in fixed partitioning, in paging, and in the buddy system described below. Tanenbaum's example shows an interesting cause as well (Figure 8.26). If there is a hole of 18,464 bytes and a process of 18,462 bytes arrives, a hole of 2 bytes would be left. The cost of tracking these 2 bytes as a separate hole in the list is greater than the hole itself. So the process takes all 18,464 bytes, and 2 bytes are wasted inside the block.

External fragmentationP1P2P3403040110 K free, but the largest piece is 40 Krequest 60 K ✗Internal fragmentationprocess 18,462 B2 B18,464 B block given; 2 B wasted (tracking the remaindercosts more than the hole)
Figure 8.26: Top: external fragmentation: 110 K is free, but because the largest piece is 40 K, a 60 K request does not fit. Bottom: internal fragmentation: 2 bytes of the given block are unused.

External fragmentation has two remedies. The first is compaction: processes are shifted and the holes are gathered into a single block. The second is more radical: remove the requirement that a process's address space be contiguous in physical memory. Paging and segmentation follow this second route.

A well-known source of internal fragmentation is the buddy system, which is also used in Linux for allocating physical frames. In this scheme blocks are always a power of two in size. A request is rounded up to the smallest power of two that satisfies it. If there is no free block of the right size, a larger block is split in two; the two halves are called each other's “buddies.” When a block is freed and its buddy is also free, the two merge again. The buddy's address is found with a single XOR: address ⊕ size.

Example 8.6

In a buddy system that starts with one free block of 1024 K, let A = 100 K, B = 240 K, C = 64 K, and D = 256 K be requested in turn. Where do the blocks go and how much internal fragmentation results?

  1. A = 100 K. Rounded up to 128 K. 1024 is split (512 + 512), the left 512 is split (256 + 256), the left 256 is split (128 + 128). A gets the 128 K block at address 0. Internal fragmentation 28 K. Free: 128 K @ 128, 256 K @ 256, 512 K @ 512.
  2. B = 240 K. Rounded up to 256 K and goes into the free block at 256. Internal fragmentation 16 K.
  3. C = 64 K. Exactly 64 K. The free block at 128 is split (64 + 64); C takes the half at 128. Free: 64 K @ 192, 512 K @ 512.
  4. D = 256 K. There is no free 256 K block; the block at 512 is split and D takes the half at 512. Free: 64 K @ 192, 256 K @ 768.
  5. Freeing. When A is freed, its buddy (0 ⊕ 128 = 128) is inside C's region, so there is no merging. When C is freed, its buddy at 192 is free: 128 K @ 128 results; its buddy, the block at 0 that was A's, is free too: 256 K @ 0 results. When B and D are also freed, the blocks merge up to 512 and then to 1024.

Total internal fragmentation is 28 + 16 = 44 K. (Traced step by step with Python.)

8.5.7Compaction

Definition 8.6

Compaction is shifting the processes in memory toward one end and gathering all the holes into a single large block.

Figure 8.27 shows the initial state. The operating system is at 0–128 K. P1 starts at 128 (160 K), P2 at 384 (192 K), P3 at 640 (128 K), and P4 at 928 (64 K). Between them are four holes of 96, 64, 160, and 32 K; although there is a total of 352 K of free space, the largest hole is 160 K.

01024 KOS128 KP1160 K96 KP2192 K64 KP3128 K160 KP464 K
Figure 8.27: Before compaction: four holes between four processes, 352 K in total.

Compaction moves the processes down in turn. P1 is already right above the operating system. P2 moves from 384 to 288 (128 + 160). P3 moves from 640 to 480 (288 + 192), and P4 from 928 to 608 (480 + 128). In the end a single 352 K hole remains between 672 and 1024 (Figure 8.28). For this, 192 + 128 + 64 = 384 K has been copied. The base register of each moved process is updated with the new address.

01024 KOS128 KP1160 KP2192 KP3128 KP464 K
Figure 8.28: After compaction: the processes are contiguous and there is a single 352 K hole.

Compaction is possible only in systems that use execution-time binding. If the addresses in a process were fixed at load time, after the process is moved they would point to the wrong places. In a system that uses a base register, only the value of the register changes.

Compaction is expensive. By Tanenbaum's calculation, a machine that copies 8 bytes in 8 ns, that is, 1 GB per second, compacts 16 GB of memory in about 16 s. Even at today's copy rate of about 20 GB/s the job takes about a second (16 / 20 = 0.8 s; ≈ 0.86 s for 16 GiB). The processes stop in the meantime. Compaction must not be confused with data compression. The aim is not to make data smaller but to make blocks adjacent.

Compaction has not entirely become history, either. To produce contiguous physical frames for huge pages, Linux performs page migration in the background; the kcompactd kernel thread does this work.

8.6Free-space management

The placement algorithms all rest on the same information: which regions are free? How this information is kept determines how fast searching and freeing can be. There are two basic structures: the bitmap and the linked list.

8.6.1Bitmaps and linked lists

Memory is first divided into fixed-size allocation units; a unit can be a few words or a few kilobytes.

Definition 8.7

A bitmap is an array that keeps one bit for each allocation unit: 0 shows that the unit is free and 1 that it is in use. In the linked-list approach, a node is kept for every process and every hole; the node holds the kind (P: process, H: hole), the starting unit, and the length.

Figure 8.29 gives two representations of the same memory. In a 32-unit memory there are processes A, B, C, D, and E and three holes. The first byte of the bitmap is 11111000: units 0–4 belong to A, and 5–7 are free. In the linked list the same information is kept in the nodes “P 0 5, H 5 3, P 8 6, ….”

(a) memory, 32 unitsABCDE08162432(b) bitmap11111000111111111100111111111000(c) linked list (P = process, H = hole, start, length)P 0 5H 5 3P 8 6P 14 4H 18 2P 20 6P 26 3H 29 3
Figure 8.29: (a) A 32-unit memory with five processes and three holes, (b) the bitmap of the same state, (c) its linked list.
Table 8.10: Comparison of the bitmap and the linked list.
BitmapLinked list
Structure1 bit per allocation unitA node for each process or hole
SizeFixed: 1/33 of memory if the unit is 4 B; 512 KiB for 16 GiB of memory and 4 KiB unitsProportional to the number of processes and holes
SearchFinding k consecutive 0s is slowThe hole list is walked; merging is easy if it is sorted by address

The size of a bitmap depends on the unit size and is fixed. If the unit is 4 bytes, that is, 32 bits, 1 bit is spent for every 32 bits of memory; the bitmap takes 1/33 of memory. If 16 GiB of memory is divided into 4 KiB units, there are 234 / 212 = 222 units. The bitmap then holds 222 bits, that is, 512 KiB. As the unit gets smaller, the bitmap gets larger; as the unit gets larger, the internal fragmentation in the last unit increases.

Example 8.7

A 512 MiB memory is tracked with a bitmap using 4 KiB units. How many bytes is the bitmap?

  1. Number of units. 229 / 212 = 217 units.
  2. Bytes. 1 bit per unit: 217 bits / 8 = 214 bytes = 16 KiB.

A common mistake is to take the number of bits (128 Ki) for bytes and get 128 KiB.

8.6.2Code trace: searching for free space in a bitmap

The weakness of the bitmap is searching. Finding room for a process of k units means finding k consecutive 0s in the array. The function below does this with a linear scan.

/* find k consecutive free (0) units */
int find(const char bit[], int n, int k) {
  int start = 0, len = 0;
  for (int i = 0; i < n; i++) {
    if (bit[i] == 0) {
      if (len == 0) start = i;  /* new run */
      if (++len == k) return start;
    } else
      len = 0;                /* run broken */
  }
  return -1;
}

len holds the length of the run of zeros currently in progress, and start the index at which the run began. When a 0 is seen and the run has just begun (len == 0), the start is recorded and the length goes up by one. When the length reaches k, the start is returned. When a 1 is seen, the run is broken and len is reset to zero. Table 8.11 traces the search for k = 3 in the 10-unit bitmap 1 1 0 0 1 0 0 0 1 1.

Table 8.11: Trace of find(bit, 10, 3). Verified with Python.
ibit[i]startlenComment
0100unit in use
1100unit in use
2021new run
3022the run grows, has not reached k yet
4120the 2-unit run is broken; this hole is too small for the process
5051new run
6052the run grows
7053len = k: 5 is returned
10110203140506071819orange: current free run · green: area found
Figure 8.30: The result of the search: units 5, 6, and 7 are allocated to the process.

The function returns 5. The allocator then sets bits 5, 6, and 7 to 1. The search starts from the beginning of the array every time and in the worst case walks the whole bitmap: O(n) for n units. In a large bitmap this is slow. Real implementations speed it up by scanning the bitmap word by word and using the hardware's “find first zero bit” instructions, but the linear structure does not change.

Example 8.8

The bitmap of an 18-unit memory is 1 1 0 1 0 0 1 1 0 0 0 1 1 0 0 0 0 1 (units start at 0). Requests of 3, 4, and 5 units arrive in turn under first fit. Where does each go?

  1. Runs of zeros. [2] (1 unit), [4–5] (2 units), [8–10] (3 units), [13–16] (4 units).
  2. 3 units. The first two runs are not enough; the run starting at 8 is exactly enough. 8–10 become full.
  3. 4 units. The remaining runs are [2], [4–5], [13–16]; only 13 is enough. 13–16 become full.
  4. 5 units. Only 3 free units are left and the longest run is 2: the request cannot be satisfied. There was no run longer than 4 at the start either.

8.6.3Freeing in a linked list

The strength of the linked list is freeing. If the list is kept sorted by address, the two neighbors of a terminating process X are right before and after it in the list. There are four cases, depending on the kind of the neighbors (Table 8.12).

Table 8.12: The four cases when process X is freed.
Left neighborRight neighborWhat happens?Number of nodes
processprocessX's node is turned into Hunchanged
processholeX merges with the hole on the rightdecreases by 1
holeprocessthe hole on the left grows by the size of Xdecreases by 1
holeholethree nodes shrink to one holedecreases by 2
before X terminatesholeXholeafterhole
Figure 8.31: When X terminates with holes on both sides, three nodes shrink to a single hole.

Merging is done in constant time, by looking only at the neighbors. In the last case the previous node has to be modified, so a doubly linked list makes the job easier. If the holes are kept in a separate list sorted by size, best fit gets faster. When the list is scanned from the start, the first hole that is big enough is already the smallest one that is big enough; first fit turns into best fit. But this time freeing gets slower, because neighboring holes are no longer next to each other in the list.

One more detail is important: no extra memory is needed to keep the hole list. The list can be stored inside the holes themselves. The first words of each hole hold that hole's size and the address of the next hole. Since the hole is free anyway, this space is free of charge.

8.6.4Inside malloc: the header and the embedded free list

The same ideas apply in user space. The malloc and free functions of the C library manage the region called the heap with a free list. A special problem has to be solved for this: a separate data structure cannot be built for the nodes of the free list, because allocating space for that structure would itself require calling malloc. The solution is to embed the node inside the free chunk itself.

In the example allocator each chunk begins with a 16-byte header. If the chunk is in use, the header holds its size and a fixed magic number; if it is free, the header holds its size and the address of the next free chunk. Table 8.13 traces the operations on a 4096-byte heap.

Table 8.13: An allocator with 16-byte headers on a 4096-byte heap. Verified with Python.
OperationComputationFree list afterwards
start4096 − 16 = 4080[4080]
p1 = malloc(200)200 + 16 = 216 B used; 4080 − 216 = 3864[3864]
p2 = malloc(100), p3 = malloc(300)3864 − 116 − 316 = 3432[3432]
free(p2)size 100 is read from the header at (char *)p2 − 16[100] → [3432]
free(p1)merges with the neighboring free chunk: 216 + 116 = 332, size 332 − 16 = 316[316] → [3432]
heap: 4,096 BBp1: 200Bfree: 100Bp3: 300Bfree: 3,432H = 16 B header: in use {size, magic number}, free {size, next}free list:head → [100] → [3,432] → NULLfree(p2): header = (char *)p2 − 16 → reads size 100, puts the chunk at the head of the list
Figure 8.32: The heap after free(p2): the free chunk of 100 bytes has been added to the head of the list. A request for 150 bytes no longer fits there.

The free function takes no size; it reads the size from the header 16 bytes before the address it is given. After free(p2) there is a free chunk of 100 bytes, but a request for 150 bytes does not fit in it: external fragmentation arises in user space too. With free(p1), p1's chunk merges with the free chunk that is its neighbor in address order, and the list gets shorter.

Magic number
The fixed pattern in the header can be corrupted by a buffer overflow, by freeing the same pointer twice, or by a wrong pointer. The library may notice this and stop the program.
The real request
malloc(n) consumes at least n + header bytes. In addition, because addresses must be aligned, the size is rounded up; in glibc the alignment is 16 bytes.
Is it a system call?
No, malloc is a library function. When the heap runs out of space it grows the heap with the brk/sbrk system calls. Large requests (128 KiB and above in glibc) it takes directly with mmap.
Example 8.9

In the same allocator with 16-byte headers, malloc(1000) is called three times on a 4096-byte heap. What is the size of the free chunk? Can a fourth malloc(1040) be satisfied?

  1. Each call. 1000 + 16 = 1016 bytes are consumed.
  2. What remains. 4080 − 3 × 1016 = 4080 − 3048 = 1032 bytes.
  3. The fourth request. Since 1040 > 1032, it cannot be satisfied from this heap. The allocator grows the heap with sbrk or mmap.
Common mistake

Giving free an address that malloc did not return, for example free(p + 4). The allocator looks for the header at address p + 4 − 16; there is no valid header there. The result is undefined behavior. An allocator with a magic-number check stops the program; one without it corrupts the free list, and the bug shows up much later, in an unrelated place.

8.7Paging

All the problems of contiguous allocation come from a single assumption: that the process sits in one piece in physical memory. Paging removes this assumption. The process is divided into small, equal pieces, and each piece can be put in any free place in memory. All of today's general-purpose operating systems use paging.

8.7.1The basic idea

Definition 8.8

In paging, physical memory is divided into fixed-size blocks, frames. Logical memory is also divided into blocks of the same size, pages. Each process has a page table; the table records in which frame each page of the process is located.

The consequences of this arrangement are seen at once. The process's location in physical memory need not be contiguous; consecutive pages can sit in frames far apart (Figure 8.33). Hence there is no external fragmentation: every free frame is suitable for every page of every process. For a process of N pages, any N free frames are enough. Internal fragmentation remains only in the last page of the process, because the process size need not be an exact multiple of the page size.

logical memorypage 0page 1page 2page 3page table01142337physical memory01page 023page 24page 1567page 3
Figure 8.33: Paging. Logical pages are mapped through the page table to non-contiguous physical frames: 0 → 1, 1 → 4, 2 → 3, 3 → 7.

The operating system keeps track of which frames are free and builds each process's page table. The backing store used for swapping is also divided into blocks of the same size; thus a page can be written to any block on disk and read back into any frame.

8.7.2Splitting the address into (p, d)

In paging, every logical address the CPU produces is split into two parts: the page number p and the offset d within the page. If the logical address space is 2m bytes and the page size is 2n bytes, the low n bits of the address give the offset and the upper m − n bits give the page number (Figure 8.34).

p: page numberm − n bitd: page offsetn bitlogical address space 2^m, page size 2^n32 bit, 4 KiB:p = 20 bitd = 12 bit
Figure 8.34: The logical address is split into the page number p and the offset d. With a 32-bit address and 4 KiB pages, p is 20 bits and d is 12 bits.

The page table translates p into a frame number f. The offset never changes. The physical address is found by adding the offset to the start of the frame:

p = ⌊a / page size⌋,   d = a mod page size,   physical = f × page size + d

Because the page size is a power of two, this division and remainder are a bit shift and a mask. With 4 KiB pages, p = a >> 12 and d = a & 0xFFF. The hardware does this for free; a page size that is not a power of two would need a real divider circuit.

Table 8.14: Examples of splitting an address (verified with Python).
ExampleComputationResult
32-bit address, 4 KiB page4096 = 212 → d 12 bits, p = 32 − 12 = 20 bits220 = 1,048,576 pages
0x12345678p = 0x12345678 >> 12, d = 0x12345678 & 0xFFFp = 0x12345 (74,565), d = 0x678 (1,656)
16-bit address, 4 KiB (Tanenbaum)8196 = 2 · 4096 + 4p = 2, d = 4
48-bit (x86-64), 4 KiBp = 48 − 1236-bit page number

In hexadecimal the split is especially easy: each hex digit is 4 bits, so a 12-bit offset is the last three digits. The last three digits of 0x12345678 give the offset 0x678, and the rest gives the page number 0x12345.

Common mistake

Forgetting the offset when finding the physical address, or adding the whole logical address to the frame start. For a 2 KiB page, logical 9000, and the mapping 4 → 7, the correct computation is: p = ⌊9000 / 2048⌋ = 4, d = 9000 − 8192 = 808, physical = 7 × 2048 + 808 = 15144. Writing just 7 × 2048 = 14336 forgets the offset; 14336 + 9000 = 23336 adds the whole address.

8.7.3Translation with the page table

Silberschatz's small example is suited to tracing a translation by hand. The page size is 4 bytes and physical memory is 32 bytes; that is, there are 8 frames. The process's 16-byte logical memory is filled with the letters a through p and occupies four pages. The page table is 0 → 5, 1 → 6, 2 → 1, 3 → 2.

Table 8.15: Translation with 4-byte pages (Silberschatz Figure 9.10).
LogicalLetterpdFramePhysical
0a0055 × 4 + 0 = 20
3d0355 × 4 + 3 = 23
4e1066 × 4 + 0 = 24
13n3122 × 4 + 1 = 9
logicala0b1c2d3e4f5g6h7i8j9k10l11m12n13o14p15page table05162132physical memory (32 bytes)0frame 04ijklframe 18mnopframe 212frame 316frame 420abcdframe 524efghframe 628frame 7address 13 → p = 3, d = 12 × 4 + 1 = 9
Figure 8.35: Translation with 4-byte pages: logical 13 (n) is page 3, offset 1; in frame 2 it corresponds to physical 9.

The example shows two important points. First, the letters of the process do not keep their order in physical memory: i…l are in frame 1, m…p in frame 2, a…d in frame 5. The program nevertheless sees its memory as consecutive from a to p. Second, the index of a page-table entry is the page number; the page number is not stored in the table separately. Looking at entry 3 of the table is the answer to the question “where is page 3?”

8.7.4Translation inside the MMU

In Tanenbaum's example the virtual address is 16 bits (64 KiB, 16 pages) and physical memory is 32 KiB (8 frames). Since the page size is 4 KiB, the upper 4 bits of the virtual address are the page number and the lower 12 bits are the offset. The frame number is 3 bits. The instructions below access five different addresses; the page table is given in the comments.

/* 16-bit virtual address, 4 KiB pages */
MOV REG, 0
MOV REG, 8192
MOV REG, 20500
MOV REG, 8196
MOV REG, 32780

/* page table (page → frame) */
/* 0→2 1→1 2→6 3→0 4→4 5→3 */
/* 9→5 11→7, others: absent */

The MMU does the same job for every address. It uses the upper 4 bits as the table index and takes the 3-bit frame number from the entry. It appends the lower 12 bits to this number unchanged. Table 8.16 shows the translation of the five addresses.

Table 8.16: MMU translation (16-bit virtual address, 4 KiB pages). Verified with Python.
VirtualBinary (p | d)pdFramePhysical
00000 0000000000000028192
81920010 00000000000020624576
205000101 000000010100520312288 + 20 = 12308
81960010 00000000010024624576 + 4 = 24580
327801000 000000001100812absentpage fault
virtual address 205000101000000010100p = 5d = 20frame 3 + d → physical 12308011000000010100
Figure 8.36: Translation of address 20500: the upper 4 bits (0101 = 5) are replaced by the frame number (011 = 3), and the lower 12 bits are copied as they are.

The last address is interesting. 32780 = 8 × 4096 + 12, and page 8 is not mapped; the present/absent bit of its entry in the table is 0. The MMU cannot produce a physical address and raises a page fault trap. Control passes to the operating system. If the page is on disk, the operating system brings it into a frame and updates the table; if the page is not valid at all, it terminates the process.

8.7.5Page size and internal fragmentation

In paging, internal fragmentation arises only in the last page, but it is important enough to influence the choice of page size.

Example 8.10

The page size is 2048 bytes and the process is 72,766 bytes. How many frames does the process occupy, and how much internal fragmentation results?

  1. Division. 72,766 = 35 × 2048 + 1086. The process occupies 35 full pages and a remainder of 1086 bytes.
  2. Frames. The remainder also needs a frame: 36 frames.
  3. Internal fragmentation. In the last frame 2048 − 1086 = 962 bytes are wasted.

In the worst case the process spills over a page by only one byte, and the internal fragmentation is one page minus one byte. If process sizes are randomly distributed, the average internal fragmentation is half a page. This is an argument in favor of small pages. On the other hand, small pages mean more pages and hence a larger page table and more TLB misses. Large pages give more efficient transfers between disk and memory and fewer table entries.

Tanenbaum measures this trade-off with a simple model. Let the average process size be s bytes, the size of a table entry e bytes, and the page size p. A process needs about s / p pages and s·e / p bytes of table per process; the internal fragmentation is p / 2 on average. The total overhead is:

overhead = s·e / p + p / 2

As p gets smaller the first term grows, and as it gets larger the second term grows. Differentiating and setting the derivative to zero gives −s·e / p2 + 1/2 = 0, that is, p = √(2·s·e). For s = 1 MiB and e = 8 bytes, p = √(2 × 220 × 8) = √(224) = 212 = 4096 bytes (Figure 8.37). At this value the overhead is 2048 + 2048 = 4096 bytes; with pages of 2048 and 8192 bytes it rises to 5120 bytes.

10 K20 K30 K5121 K2 K4 K8 K16 K32 K64 Kminimum: 4 KiBpage size p (log scale)
Figure 8.37: The overhead curve s·e / p + p / 2; for s = 1 MiB and e = 8 bytes the minimum is at 4 KiB.

Real systems stay in this neighborhood too. On x86-64 the base page is 4 KiB; there are also huge pages of 2 MiB and 1 GiB. ARM64 can use pages of 4, 16, or 64 KiB; Apple Silicon uses 16 KiB.

8.7.6Free frames

When a new process arrives, the operating system takes as many frames from the free-frame list as the process has pages and fills in the page table. In the example of Figure 8.38 the free list is 14, 13, 18, 20, 15. A process of four pages takes the first four frames of the list: page 0 → 14, 1 → 13, 2 → 18, 3 → 20. Only 15 stays on the list.

beforefree-frame list:14, 13, 18, 20, 15new process: 4 pagespage 0page 1page 2page 3131415161718192021afterfree list: 15page table01411321832013page 114page 015161718page 21920page 321
Figure 8.38: The four pages of the new process are placed in frames 14, 13, 18, and 20 of the free-frame list.

For this the operating system keeps a frame table: for every physical frame, whether the frame is free and, if it is in use, which page of which process it holds. This table is needed not only for allocation but for other jobs as well. For example, when a process gives a buffer address to the read system call, this address is logical. To be able to write the data there, the kernel translates the address into a physical address with the process's page table.

Because each process has a separate page table, on a context switch the hardware must be pointed at the new process's table. The dispatcher does this by updating a register; on x86 this register is CR3. This extra work lengthens the context-switch time.

8.7.7The page-table entry

A page-table entry (PTE) holds not only the frame number. Alongside it are a number of bits used by the hardware and the operating system. Figure 8.39 shows the 64-bit entry of x86-64.

NX63PK62–59—58–52frame number51–12—11–9G8PAT7D6A5PCD4PWT3U/S2R/W1P0x86-64 page-table entry (64 bits, 4 KiB page)
Figure 8.39: The x86-64 page-table entry (64 bits, 4 KiB page): NX, protection key, frame number, G, PAT, D, A, cache bits, U/S, R/W, and P.
Table 8.17: The bits of a page-table entry.
BitMeaning (Tanenbaum's name)Who writes it?
PPresent/absent: if 0, an access produces a page faultOS
R/W, U/S, NXProtection: writable? accessible in user mode? executable?OS
AAccessed (referenced): becomes 1 on a read or write; used in page replacementhardware (the OS clears it)
DDirty (modified): becomes 1 on a write; a dirty page is written to disk when evictedhardware
PCD, PWT, PATCache disabling and write policy: for memory-mapped I/OOS
GGlobal: not flushed from the TLB on a context switch (kernel pages)OS

The accessed and dirty bits give the operating system very valuable information. The hardware sets A to 1 on every access to a page and D to 1 on every write. The operating system periodically clears the A bits and learns which pages have been used recently. The D bit tells whether a page has to be written to disk when it is evicted from memory: the copy of an unmodified page on disk is already up to date.

The cache bits are needed for memory-mapped I/O. If a device's register is mapped to a memory address, the value read from that address must come from the device, not from the cache. Otherwise the program reads the device's old state.

If a page is not in memory, where is its place on disk kept? The disk address is not kept in the PTE; the hardware does not use it. For an entry whose P bit is 0, the remaining bits belong entirely to the operating system. Linux encodes the location in the swap area in these bits.

8.7.8The valid / invalid bit

The page table contains entries for the whole address space of the process, but the process does not use all of this space. The entries for the unused pages are marked invalid. In Silberschatz's example the address is 14 bits (0 … 16383) and the page is 2 KiB, so there are 8 pages. The process uses only 0 through 10468: pages 0–5 are valid and are in frames 2, 3, 4, 7, 8, 9; pages 6 and 7 are invalid.

Table 8.18: Translation with the valid/invalid bit (2 KiB pages). Verified with Python.
Addressp, dEntryResult
3,0001, 952valid, frame 33 × 2048 + 952 = 7,096
10,4685, 228valid, frame 99 × 2048 + 228 = 18,660 (the process's last address)
12,0005, 1760valid, frame 920,192 (outside the program, but not caught)
12,5006, 212invalidtrap
process: 0 … 10,468page 0page 1page 2page 3page 4page 5page 6page 7page table02v13v24v37v48v59v60i70i14-bit address: 0 … 16,3832 KiB pages → 8 pagesv = valid, i = invalidaddress 12,000= 5 × 2048 + 1760 → page 5valid → frame 9physical = 9 × 2048 + 1760 = 20,192
Figure 8.40: Address 12,000 is outside the program, but because it lies inside page 5, the hardware does not catch it.

The third row shows a limit of paging. The last address of the process is 10,468; 12,000 does not belong to the program. But page 5 covers 10,240 through 12,287 and is marked valid. Hardware protection is at page granularity: every address inside a page is either valid or none is. The unused part of the process's last page is another face of internal fragmentation. 12,500, on the other hand, is on page 6, and the invalid entry produces a trap. The operating system decides whether this trap is a programming error (SIGSEGV) or an access to a page not yet brought into memory.

Instead of keeping the whole table, a page-table length register (PTLR) can also be used. This register holds how many entries the table contains; a larger page number produces a trap directly. In this way no space is spent on the entries for unused pages.

8.7.9Protection bits

In paging, protection is also done at the page level. The permission bits are kept separately in every PTE and are checked on every access, together with the TLB entry.

Read / write (R/W)
Code pages are mapped read-only; an attempt to write to code produces a protection fault.
User / supervisor (U/S)
Kernel pages cannot be accessed in user mode. In this way the same table can hold both the kernel's and the process's mappings.
No-execute (NX / XD)
Code cannot be executed from data, stack, and heap pages. Operating systems enforce the W^X rule: a page is either writable or executable, never both. In this way attack code written onto the stack cannot be executed.
SMEP / SMAP
While in kernel mode, they prevent the execution of code in user pages (SMEP) and unauthorized access to user data (SMAP).
Protection keys (PKU)
With a 4-bit key in the PTE and a user register (PKRU), the permission of a group of pages can be changed without a system call.
Valid / invalid
The crudest form of access permission: if the page does not exist in the address space at all, every access is a trap.

8.7.10Shared pages

An important gain of paging is that common code can be shared easily. Reentrant code, that is, code that does not modify itself while running, can be shared among many processes. If three users run the same text editor, the editor's code pages are in memory only once. Each process's page table points to these frames; only the data pages are separate for each process (Figure 8.41).

P1ed 1 → 3ed 2 → 4ed 3 → 6P1 data → 1P2ed 1 → 3ed 2 → 4ed 3 → 6P2 data → 7P3ed 1 → 3ed 2 → 4ed 3 → 6P3 data → 2physical memory (frame no. below)0P11P32ed 13ed 245ed 36P27
Figure 8.41: Three processes map the three pages of the editor's code to the same physical frames (3, 4, 6); each process's data is in a separate frame.

Shared libraries are shared in this way too. Sharing has a consequence: when the process that “owns” a page terminates, the frame cannot be freed at once, because other processes may be using it. That is why a reference count is kept for every shared frame.

Today's systems have other forms of sharing as well. On a fork() call the parent and child share all pages by copy-on-write (COW). The pages are marked read-only in both processes; when one of the processes tries to write to a page, a protection fault occurs and the kernel makes a copy of only that page. Memory-mapped files (mmap) and shared memory (shm_open), on the other hand, let two processes see the same frames; the processes communicate without copying data.

8.8The TLB

Paging eliminates external fragmentation, but it has a price: every memory access first needs a table access. This section describes how this price is brought down to almost nothing.

8.8.1Where does the page table live?

If the page table were small, it could be kept inside the processor in special registers. But with a 32-bit address and 4 KiB pages a table has 220, that is, more than a million entries. That many entries do not fit in registers. The table therefore lives in main memory. Its starting address is held in the page-table base register (PTBR); on x86 this register is CR3, and on ARM it is TTBR0/TTBR1. On a context switch only this register changes.

The problem with this solution is obvious: every data access is now two memory accesses. First the entry at address PTBR + p is read, then the data is accessed. The memory access time doubles. The solution is a small hardware cache that holds recently used translations.

Definition 8.9

The TLB (translation look-aside buffer) is a small, fast, associative cache inside the MMU. It holds recently used (page number, frame number) pairs. Being associative means that a page number is compared with all the entries at the same time, in parallel.

Translation proceeds as follows (Figure 8.42). When the CPU produces an address, the page number is first looked up in the TLB. If it is found (a TLB hit), the frame number is obtained at once and no table access is made. If it is not found (a TLB miss), the table in memory is reached through the PTBR, the entry is read, and it is loaded into the TLB for the next access. If the TLB is full, an entry is evicted.

CPUpdTLB (associative memory)pageframehitfdphysical addressPhysical memorymisspage table (in memory)PTBRentry loaded into TLB
Figure 8.42: Paging hardware with a TLB. The page number is first looked up in the TLB; on a miss the table in memory is reached through the PTBR and the entry is loaded into the TLB.

In today's processors each core typically has an L1 TLB of 64 entries and an L2 TLB of 1–3 thousand entries. TLB entries can be tagged with an address-space identifier (ASID; PCID on Intel). In this way each entry knows which process it belongs to, and the TLB need not be flushed on a context switch.

8.8.2Tracing TLB hits and misses

Let the page table of Tanenbaum's MMU example (0 → 2, 2 → 6, 5 → 3, 9 → 5, 11 → 7) now be used with a TLB. The TLB has 4 entries and evicts the least recently used (LRU) entry when room is needed. The TLB starts out empty. The pseudocode below summarizes what is done on each access.

p = addr / 4096;  d = addr % 4096;
if (p in TLB) {           /* hit */
  f = TLB[p];  make p the newest;
} else {                  /* miss */
  f = page_table[p];
  if (TLB full) evict the oldest entry;
  add (p, f) to the TLB;
}
physical = f * 4096 + d;
Table 8.19: Trace of a 4-entry LRU TLB. In the TLB column the entries are ordered from oldest to newest. Verified with Python.
AccesspResultPhysicalEvictedTLB afterwards
0x00100miss0x2010—0
0x20042miss0x6004—0, 2
0x00200hit0x2020—2, 0
0x50105miss0x3010—2, 0, 5
0x90009miss0x5000—2, 0, 5, 9
0x20082hit0x6008—0, 5, 9, 2
0xB00411miss0x700405, 9, 2, 11
0x00300miss0x203059, 2, 11, 0
access sequence (16 bits, 4 KiB pages)0x0010p = 0miss0x2004p = 2miss0x0020p = 0hit0x5010p = 5miss0x9000p = 9miss0x2008p = 2hit0xB004p = 11miss0x0030p = 0missTLB (4 entries, LRU; oldest to newest, left to right)9 → 52 → 611 → 70 → 2physical2·4096 + 48 = 0x2030evicted: page 5
Figure 8.43: The last step of the trace: for 0x0030, page 0 is not in the TLB, and page 5, the least recently used, is evicted.

In eight accesses there are only 2 hits. On hits the page table is not consulted at all. After the hit on 0x0020, page 0 moves to the “newest” position. But when 0xB004 arrives, the TLB is full and the least recently used entry is again page 0, because 5, 9, and 2 have been used since 0x0020. The 0x0030 that follows immediately therefore misses. In short examples the ratio comes out low; in real programs, thanks to locality, the TLB hit rate exceeds 99%.

8.8.3Effective access time

The gain from the TLB is measured with a single number.

Definition 8.10

The effective access time (EAT) is the average memory access time, found by taking into account the probabilities of TLB hits and misses. If the TLB lookup time is ε, the memory access time t, and the TLB hit ratio α, then for a single-level table:

EAT = (t + ε) · α + (2t + ε) · (1 − α) = 2t + ε − t · α

The logic of the formula is simple. On a hit the TLB is consulted and a single memory access is made: t + ε. On a miss the TLB is consulted, and then one memory access is made for the table entry and one for the data: 2t + ε. The average is the sum of these two times weighted by their probabilities.

Example 8.11

Let ε = 20 ns and t = 100 ns. What is the effective access time for α = 80% and α = 98%?

  1. Two cases. Hit: 20 + 100 = 120 ns. Miss: 20 + 100 + 100 = 220 ns.
  2. α = 80%. 120 × 0.80 + 220 × 0.20 = 96 + 44 = 140 ns. With the closed form, 2 × 100 + 20 − 100 × 0.80 = 140 ns.
  3. Interpretation. Without a TLB every access would take 200 ns; 140 ns is better than that, but it is still 40% slower than the plain memory time.
  4. α = 98%. 120 × 0.98 + 220 × 0.02 = 117.6 + 4.4 = 122 ns. The slowdown falls to 22%. In real workloads the ratio is usually above 99%; at α = 99% the EAT is 121 ns.

With multilevel tables a miss is much more expensive. In x86-64's four-level table a miss needs four table accesses and one data access: 20 + 4 × 100 + 100 = 520 ns. In that case for α = 98% the EAT = 120 × 0.98 + 520 × 0.02 = 117.6 + 10.4 = 128 ns, and for α = 99% it is 118.8 + 5.2 = 124 ns. The more expensive a miss is, the more the hit ratio matters. That is why the hardware also keeps the intermediate levels of the table walk in a separate cache (a page walk cache). A real miss thus often comes down not to four but to one or two memory accesses.

Example 8.12

The memory access takes 80 ns, the TLB lookup 10 ns, the table is single-level, and the hit ratio is 95%. (a) What is the EAT? (b) What must the hit ratio be at least for the EAT to fall to 92 ns?

  1. Two cases. A hit takes 10 + 80 = 90 ns, a miss 10 + 80 + 80 = 170 ns.
  2. (a) 0.95 × 90 + 0.05 × 170 = 85.5 + 8.5 = 94 ns.
  3. (b) 90α + 170(1 − α) ≤ 92 → 170 − 80α ≤ 92 → α ≥ 78 / 80 = 0.975. The hit ratio must be at least 97.5%.

It is also instructive to count the effect of the TLB over a loop.

Example 8.13

The loop for (i = 0; i < 1000; i++) a[i] = 0; compiles to the four instructions below. The array a starts at virtual address 40,000, an int is 4 bytes, a page is 4 KiB, and the code lies in a single page. There is a linear page table. How many memory accesses are made in total without and with a TLB?

loop:  movl $0,(%edi,%eax,4)  /* a[i] = 0 */
       incl %eax              /* i++      */
       cmpl $1000,%eax
       jne  loop
  1. One iteration. Four instructions are fetched and movl writes to memory once: 5 accesses.
  2. No TLB. A PTE is read before every access: 10 per iteration, 10 × 1000 = 10,000 accesses in total.
  3. With a TLB. To the 5 × 1000 = 5000 accesses are added only the PTE reads on TLB misses. The array lies between 40,000 and 43,999 and spans pages ⌊40,000 / 4096⌋ = 9 and ⌊43,999 / 4096⌋ = 10. Together with the code page there are three misses: 5000 + 3 = 5003 accesses.

8.8.4TLB management

How the TLB is filled and flushed varies from architecture to architecture. Table 8.20 summarizes the main topics.

Table 8.20: TLB management.
TopicDescription
Hardware-managedx86-64, ARMv8, RISC-V: on a miss the MMU walks the page table itself (page walk); the operating system only builds the table.
Software-managedIn older RISC processors such as MIPS, SPARC, and Alpha, a miss traps to the operating system; the kernel finds the entry and writes it into the TLB. This is not true of all RISCs: ARMv8 and RISC-V are hardware-managed.
Soft / hard missSoft miss: the page is in memory and missing only from the TLB (nanoseconds). Hard miss: the page is on disk and I/O is needed (microseconds or milliseconds).
ASID / PCIDThe entry is tagged with a process ID; the TLB is not flushed on a context switch. PCID reduces the cost of KPTI, which was introduced after Meltdown (2018).
Global entriesKernel mappings are marked with the G bit and remain valid in all processes.
TLB shootdownOn a multicore system, when a mapping changes, the TLBs of the other cores are invalidated with inter-processor interrupts (IPIs); newer processors have broadcast instructions (AMD INVLPGB).
TLBASID 7 · page 0x400 → 0x1A2ASID 9 · page 0x400 → 0x3F0ASID — · page 0xFFFF8 → 0x001 · Gsame virtual page, two processes: entries told apart by ASIDG: valid in all processes (kernel)
Figure 8.44: A TLB tagged with ASIDs: the same virtual page (0x400) of two processes maps to different frames; the kernel entry marked G is valid in all processes.

The value of the ASID shows at context switch. Without tags, the whole TLB has to be flushed so that the new process does not use the old process's translations, and the new process then suffers a run of misses on its first accesses. With ASIDs, the same virtual page of two processes can sit side by side in the TLB (Figure 8.44). The TLB shootdown, on the other hand, is a problem of multicore systems: when one core changes a mapping, it has to tell the other cores that hold the same mapping in their TLBs. This communication is expensive and limits scaling in large systems.

8.9Page-table structures

A single-level, linear page table works for small address spaces. As the address space grows, the table itself becomes a memory problem. This section describes three ways of shrinking the table: hierarchical, hashed, and inverted tables.

8.9.1The hierarchical page table

With a 32-bit address and 4 KiB pages, a single-level table has 220 entries; with 4-byte entries the table takes 4 MiB. This table must be separate for each process and contiguous in memory. In a system with 100 processes, the page tables alone amount to 400 MiB. On 64 bits the situation is far worse. With 4 KiB pages and 8-byte entries, a single-level table takes 252 × 8 B = 32 PiB, about 33.6 million GiB. Even if only 48 bits of the address are used, 236 × 8 B = 512 GiB is needed.

The solution is to page the table itself. The virtual address is split into two indexes and an offset. On 32-bit x86, 10 bits index the top-level table (the page directory), 10 bits index the second-level table, and 12 bits are the offset (Figure 8.45). What is split here is not the table entry but the virtual address.

Definition 8.11

A hierarchical page table is a page table kept as a multilevel tree. Each entry of the top-level table points to a lower-level table; only the regions in use have lower-level tables.

PT110 bitPT210 bitoffset12 bit32-bit virtual addressouter table (1024)0: code1: data2⋮1023: stack2nd level: code2nd level: data2nd level: stackthe other 1021 outer entries: "absent"
Figure 8.45: A two-level page table. Only the code, data, and stack entries of the top-level table point to second-level tables; the remaining 1021 top-level entries are “absent.”

The gain comes from sparse address spaces. Consider a process that uses 4 MiB of code, 4 MiB of data, and 4 MiB of stack. Each second-level table covers a region of 1024 pages × 4 KiB = 4 MiB. For this process one top-level table and three lower tables are enough: 4 × 4 KiB = 16 KiB. A single-level table would take 4 MiB. The lower tables of unused regions are never created; their entries in the top-level table are simply marked “absent.”

8.9.2A two-level translation example

Example 8.14

In Tanenbaum's example the virtual address is 0x00403004 (4,206,596). This address lies between 4 MiB and 8 MiB, in the data region. How is it translated in a two-level table?

  1. Splitting. 0x00403004 = 0000000001 0000000011 000000000100. The upper 10 bits give PT1 = 1, the middle 10 bits PT2 = 3, and the offset = 4.
  2. Top-level table. Entry 1 of the top-level table points to the second-level table of the 4–8 MiB region. Each top-level entry covers a region of 4 MiB.
  3. Second level. Entry 3 of that table is consulted. This entry is the page at byte range 12,288–16,383 within the region; in absolute terms 4,206,592–4,210,687. If the entry's present bit were 0, a page fault would occur.
  4. Physical address. The entry gives the frame number (0x1F3 in the example). The offset is added: 0x1F3004.

On a TLB miss this translation needs two table accesses and one data access. The frame numbers in the example are for illustration.

virtual address 0x00403004 = 4,206,59600000000010000000011000000000100PT1 = 1PT2 = 3offset = 4outer table00–4 MiB14–8 MiB28–12 MiB3…2nd-level table (4–8 MiB)00x0A210x1C02absent30x1F340x0B7frame 0x1F3physical 0x1F3004
Figure 8.46: Translating address 0x00403004: PT1 = 1, PT2 = 3, offset = 4; frame 0x1F3, physical 0x1F3004.

On 32-bit x86 the address of the top-level table is in CR3. Each of the tables at the two levels fills exactly one 4 KiB page: 1024 entries × 4 bytes. This choice is no coincidence. That a table fits exactly in a page means that the lower tables can be placed in any frame like ordinary pages and, if necessary, swapped to disk.

8.9.3Code trace: two-level translation

What the MMU does can be written in C as follows:

/* 32 bits: 10 + 10 + 12 bits */
uint32_t translate(uint32_t va) {
  uint32_t p1 = va >> 22;
  uint32_t p2 = (va >> 12) & 0x3FF;
  uint32_t d  = va & 0xFFF;
  pte_t e1 = outer[p1];
  if (!e1.p) page_fault(va);
  pte_t e2 = e1.table[p2];
  if (!e2.p) page_fault(va);
  return (e2.frame << 12) | d;
}

va >> 22 takes the upper 10 bits. (va >> 12) & 0x3FF first drops the offset and then keeps the lower 10 bits, that is, the middle index. va & 0xFFF is the offset. The function goes to the entry of the top-level table and from there to the entry of the second-level table; at both steps it raises a page fault if the present bit is 0. At the end it shifts the frame number left by 12 bits and combines it with the offset.

Table 8.21: Trace of the translate function with two addresses. In the top-level table only entry 2 is valid; in its table, entry 1 → frame 0x2F. Verified with Python.
Variableva = 0x00801A3Cva = 0x01403004
p1 = va >> 2225
p2 = (va >> 12) & 0x3FF0x801 & 0x3FF = 10x1403 & 0x3FF = 3
d = va & 0xFFF0xA3C0x004
e1 = outer[p1]P = 1 (1st memory access)P = 0 → page fault
e2 = e1.table[p2]frame 0x2F, P = 1 (2nd access)—
return(0x2F << 12) | 0xA3C = 0x0002FA3C—
va = 0x014030040000000101p1 = 50000000011p2 = 3000000000100d = 0x004outer[5]: absentP = 0 → page fault (trap)
Figure 8.47: For 0x01403004, entry 5 of the top-level table is invalid: there is no second-level table at all for the 20–24 MiB region.

For the first address the third memory access goes to the data. The second address lies in the 20–24 MiB region. No second-level table has been created for this region; the MMU raises a trap at the top-level table. That no memory has been spent on the table is the whole gain of the hierarchical table.

Example 8.15

With the same 10 + 10 + 12 split, a process uses the lowest 12 MiB and the topmost 4 MiB of its address space. How many page tables are needed?

  1. Lower tables. Each lower table covers 4 MiB: 3 tables for the lowest 12 MiB and 1 for the topmost 4 MiB.
  2. Total. 4 lower tables + 1 top-level table = 5 tables = 20 KiB. A linear table would be 4 MiB.

8.9.4x86-64: four- and five-level paging

On x86-64 each page table is 512 entries × 8 bytes = 4 KiB; that is, again exactly one page, and each level uses a 9-bit index. With four levels and a 12-bit offset, 4 × 9 + 12 = 48 bits of virtual address are obtained; this is an address space of 256 TiB (Figure 8.48). The levels are named, from top to bottom, PML4, PDPT, PD, and PT.

x86-64, 4 levels (48-bit virtual address, 256 TiB)sign63–48PML49 bitPDPT9 bitPD9 bitPT9 bitoffset12 bitx86-64, 5 levels (LA57: 57 bits, 128 PiB)sign63–57PML59PML49PDPT9PD9PT9offset12
Figure 8.48: The split of an x86-64 virtual address in four- and five-level paging: each level 9 bits, the offset 12 bits.

The upper 16 bits of a 64-bit address are unused, but they cannot be arbitrary either: all of them must be copies of bit 47. Such addresses are called canonical addresses. As a result the address space is divided in two: the lower half goes to the user and the upper half to the kernel. Five-level paging (LA57) adds a PML5 level and gives a 57-bit, 128 PiB virtual address. Intel Ice Lake server processors and AMD Zen 4 and later support it; Linux has been able to use it since 4.14.

This is why the hierarchical table works on 64 bits too: not all 64 bits are used, and the address space in use is sparse. Today's x86-64 and ARMv8 use exactly a hierarchical table. If the PS bit in an intermediate-level entry is 1, the walk ends there: a huge page has been found, 2 MiB at the PD level or 1 GiB at the PDPT level.

8.9.5The four-level walk

Example 8.16

How is VA = 0x00007FFE12345678, an address near the user stack, translated in four levels?

  1. Splitting (9 + 9 + 9 + 9 + 12). PML4 = (VA >> 39) & 0x1FF = 255, PDPT = (VA >> 30) & 0x1FF = 504, PD = (VA >> 21) & 0x1FF = 145, PT = (VA >> 12) & 0x1FF = 325, offset = 0x678.
  2. PML4. CR3 gives the frame of the PML4 table (0x1A2B). Entry 255 is read; the frame of the PDPT table is 0x3C4.
  3. PDPT. PDPT[504] gives the frame of the page directory (PD): 0x7D10. Had PS = 1 here, a 1 GiB page would have been found.
  4. PD. PD[145] gives the frame of the last-level table: 0x2E95. Had PS = 1, a 2 MiB page would have been found.
  5. PT. PT[325] gives frame 0x5A3F7; the offset is added: physical 0x5A3F7678.

On a TLB miss, 4 table accesses and 1 data access are made. The frame values are illustrative; the indexes were computed with Python.

VA = 0x00007FFE12345678PML4[255]PDPT[504]PD[145]PT[325]offset 0x678CR30x1A2BPML4 table[255] → 0x3C4frame 0x1A2BPDPT table[504] → 0x7D10frame 0x3C4PD table[145] → 0x2E95frame 0x7D10PT table[325] → 0x5A3F7frame 0x2E95physical 0x5A3F7678
Figure 8.49: The end of the x86-64 four-level page-table walk: PT[325] gives frame 0x5A3F7.
Common mistake

Using a 10-bit index on x86-64 as on 32-bit x86. Because the entry grows to 8 bytes, 512 entries fit in a 4 KiB table; the index is 9 bits. Indexes are masked with 0x1FF, not 0x3FF.

8.9.6Huge pages

Programs with a large working set, such as databases, virtual machines, and AI workloads, suffer constant TLB misses with 4 KiB pages. The measure of the problem is the TLB reach: the number of entries × the page size. A TLB of 1536 entries covers only 6 MiB with 4 KiB pages; with 2 MiB pages the same TLB covers 3 GiB (Figure 8.50).

TLB reach = entries × page size, 1536 entries4 KiB pages6 MiB2 MiB pages3 GiB(log scale)
Figure 8.50: TLB reach: with 1536 entries, 6 MiB with 4 KiB pages and 3 GiB with 2 MiB pages.

The table size shrinks as well. Mapping 1 GiB with 4 KiB pages takes 230 / 212 = 262,144 PTEs, that is, a 2 MiB table. With 2 MiB pages only 512 PD entries, that is, 4 KiB, are enough.

Linux offers huge pages in three forms. hugetlbfs is for programs that explicitly ask for pre-reserved 2 MiB or 1 GiB pages. With transparent huge pages (THP), the kernel maps suitable regions with huge pages on its own. mTHP in recent versions uses intermediate sizes of 16–64 KiB. On Windows the same job is done by “large pages.”

Huge pages have two costs: internal fragmentation increases, and a contiguous 2 MiB physical region has to be found. The problem of finding contiguous regions explains why the buddy allocator and compaction are still important today. ARMv8 offers an intermediate solution to this problem: 16 adjacent 4 KiB entries marked with the contiguous bit can be held as a single TLB entry, as 64 KiB.

8.9.7The hashed page table

For address spaces larger than 32 bits, another approach is the hash table.

Definition 8.12

In a hashed page table the virtual page number is passed through a hash function. Each bucket of the table is a linked list of the entries (virtual page, frame, next) that fall on the same hash value.

Example 8.17

In a table with 8 buckets, h(p) = p mod 8. The chain of bucket 2 is (p = 10 → f = 7), (p = 26 → f = 3). Where is virtual address 0x1A0AB translated to? (4 KiB pages)

  1. Splitting. p = 0x1A = 26, d = 0x0AB.
  2. Hash. h(26) = 26 mod 8 = 2.
  3. Chain. The first entry is p = 10: no match, move on to the next. The second entry is p = 26: it matches, frame 3.
  4. Physical address. 3 × 4096 + 0xAB = 0x30AB.
virtual address 0x1A0AB → p = 26 (0x1A), d = 0xABh(p) = p mod 8h(26) = 2hash table0p=8 → f=4p=16 → f=612p=10 → f=7p=26 → f=3345p=13 → f=167p=31 → f=2frame 3physical 0x30AB
Figure 8.51: Looking up page 26 in a hashed page table: in the chain of bucket 2 the second entry matches.

The size of a hash table is proportional to the number of pages in use, not to the size of the address space. This is an attractive property for sparse 64-bit address spaces. In the clustered variant each entry holds the frames of several (for example 16) consecutive pages instead of a single page. This variant suits address spaces that are sparse but locally dense.

8.9.8The inverted page table

In all the tables so far there was one table per process, and the size of the table depended on the virtual address space. The inverted table turns the point of view around.

Definition 8.13

An inverted page table is a single table in the system that keeps one entry per physical frame. Each entry records which page of which process is in that frame, that is, a (pid, page) pair. The index of the entry is the frame number.

Translation is a search. For the address (pid = 2, p = 5, d = 0x123) the table is scanned from the start. Entry 0 (1, 0), entry 1 (2, 3), entry 2 (1, 5), and entry 3 (3, 1) do not match. Entry 4 (2, 5) matches. Since the index itself is the frame number, the physical address is 4 × 4096 + 0x123 = 0x4123 (Figure 8.52).

logical address: (pid = 2, p = 5, d = 0x123)inverted table: one entry per frame0pid 1, page 01pid 2, page 32pid 1, page 53pid 3, page 14pid 2, page 55pid 1, page 26pid 3, page 07pid 2, page 0framematch: index 4 = framephysical 0x4123
Figure 8.52: Looking up (pid 2, page 5) in the inverted page table: a match is found at index 4, and the physical address is 0x4123.

The size of the table is proportional to physical memory and independent of the number of processes. With 16 GiB of RAM and 4 KiB frames there are 4,194,304 entries; with 8 bytes per entry the table takes 32 MiB. This is a single table for the whole system.

There are three costs. The first is searching: a linear scan is unacceptably slow on every access. Real systems therefore hash the (pid, p) pair, go straight to the relevant entry, and put a TLB in front. The second is sharing: since a frame can hold only one (pid, page) pair, shared memory becomes hard. The third is page faults: the place on disk of a page that is not in memory cannot be found in the inverted table; for this a separate external table per process is needed. The PowerPC and IBM POWER architectures use a hashed inverted table; IA-64 also adopted this approach.

8.10Segmentation

Paging is a mechanism completely hidden from the programmer: the address space is a one-dimensional array of bytes, and page boundaries have nothing to do with the logical structure of the program. Segmentation, on the other hand, divides the address space according to the program's own parts.

8.10.1Why segmentation?

Tanenbaum's example is a compiler. While running, a compiler builds many tables: the source text, the symbol table, the table of constants, the parse tree, and the call stack. All of these tables grow and shrink during the run. In a one-dimensional address space each table is given a consecutive region. When a table fills up, it collides with its neighbor even if the neighbor has free space (Figure 8.53). The symbol table overflows into the source text's region; the compiler either stops or has to shift the tables by hand.

(a) one-dimensional spacecall stackparse treeconstantssource textsymbol tablethe symbol table grewand hits the source text!(b) separate segmentssymbols0source1consts2tree3stack4each segment starts at 0 and grows on its own
Figure 8.53: (a) In a one-dimensional address space the compiler's tables collide with each other. (b) In separate segments each table starts at 0 and grows independently.
Definition 8.14

Segmentation is giving a process several independent, variable-length address spaces. Each address space is called a segment. An address has two parts: (segment number, offset within the segment).

Segmentation matches the programmer's view. The programmer thinks of the program not as a single array of bytes but as separate units such as the main program, functions, the stack, arrays, and the symbol table. Segmentation gives each of these units its own address space. Each segment starts at 0 and can grow and shrink without affecting the other segments.

8.10.2Translation with the segment table

Translation is done with a segment table. Each entry of the table holds the base (physical starting address) and the limit (length) of one segment. The location of the table in memory is held by the segment-table base register (STBR), and the number of entries by the segment-table length register (STLR). For an address (s, d) the hardware first checks the condition d < limit[s]. If it holds, the physical address is base[s] + d; if not, a trap occurs. Segmentation is really a separate base–limit pair for each segment.

Table 8.22: Silberschatz's five-segment example. Segment table (limit, base): 0 → (1000, 1400), 1 → (400, 6300), 2 → (400, 4300), 3 → (1100, 3200), 4 → (1000, 4700). Verified with Python.
(s, d)d < limit?Result
(2, 53)53 < 4004,300 + 53 = 4,353
(3, 852)852 < 1,1003,200 + 852 = 4,052
(1, 399)399 < 4006,300 + 399 = 6,699
(0, 1,222)1,222 ≥ 1,000trap
segment tablelimitbase01.0001.40014006.30024004.30031.1003.20041.0004.700physical memorysegment 01.400segment 16.300segment 24.300segment 33.200segment 44.700(s, d) = (0, 1,222)d < limit ? 1,222 < 1,000no → trap (addressing error)
Figure 8.54: Address (0, 1,222): segment 0 is only 1,000 bytes long, so the hardware raises a trap.

Without the check in the last row, the address would be 1,400 + 1,222 = 2,622. This address is outside segment 0; it might belong to another segment of the process or to the memory of another process. The limit check prevents exactly this.

Common mistake

Counting an access as valid when the offset equals the limit. Valid offsets are 0 … limit − 1. In a segment with limit 400, (1, 399) refers to the last valid byte; (1, 400) is already a trap.

8.10.3The bits that select the segment, and the downward-growing stack

The segment number need not be a separate part of the address; the upper bits of the virtual address can also select the segment. In an example similar to the one in OSTEP, the virtual address is 14 bits (16 KiB). The upper two bits select the segment: 00 code, 01 heap, 11 stack. The remaining 12 bits are the offset, so a segment can be at most 4 KiB. The segment registers are as follows:

Table 8.23: Segment registers (14-bit virtual address).
SegmentBaseSizeDirectionProtection
00 code24,5763,072+r-x
01 heap40,9602,048+rw-
11 stack32,7682,048−rw-

The “direction” bit of the stack segment is negative: the stack grows downward. In such a segment the offset is interpreted as negative. The largest segment size (4,096) is subtracted from the offset; the absolute value of the negative number obtained must not exceed the size. The physical address is the base plus the negative offset.

Example 8.18

Where do virtual addresses 1,000, 4,500, 16,000, and 7,000 go?

  1. 1,000. Binary 00 001111101000: segment 00 (code), offset 1,000. 1,000 < 3,072, valid. Physical 24,576 + 1,000 = 25,576.
  2. 4,500. 01 000110010100: segment 01 (heap), offset 4,500 − 4,096 = 404. 404 < 2,048, valid. Physical 40,960 + 404 = 41,364. Adding the whole virtual address to the base (40,960 + 4,500 = 45,460) would be wrong.
  3. 16,000. 11 111010000000: segment 11 (stack), offset 3,712. Because the stack grows downward, 3,712 − 4,096 = −384. |−384| ≤ 2,048, valid. Physical 32,768 − 384 = 32,384.
  4. 7,000. 01 101101011000: segment 01 (heap), offset 2,904. 2,904 ≥ 2,048: the hardware raises a trap, and the operating system terminates the process with SIGSEGV.
segmentbasesizegrowsprotection00 code24.5763.072+r-x01 heap40.9602.048+rw-11 stack32.7682.048−rw-virtual address 16,00011111010000000segmentoffset (12 bits) = 3,712segment 11 → stackgrows down: negative offset = 3,712 − 4,096 = −384|−384| ≤ 2,048 → valid32.768 − 384 = 32.384physical memory24 K42 Kcodeheapstack32.384
Figure 8.55: Address 16,000: the upper bits 11 select the stack; because the stack grows downward, the offset is interpreted as −384 and the physical address is 32,384.
Example 8.19

With the same registers, where do virtual addresses 13,000 and 14,500 go?

  1. 13,000. 13,000 − 12,288 = 712; segment 11 (stack), offset 712. 712 − 4,096 = −3,384; since |−3,384| > 2,048, a trap.
  2. 14,500. Segment 11, offset 2,212. 2,212 − 4,096 = −1,884; |−1,884| ≤ 2,048, valid. Physical 32,768 − 1,884 = 30,884.

Protection bits also make sharing possible. A code segment with r-x permission can be mapped to the same physical region in many processes. Because the segment is read-only, if one of the processes tries to write to it, a protection fault occurs and the others are not affected.

8.10.4Pros and cons of segmentation

The advantages of segmentation come from the logical structure of the program:

  • Tables that grow or shrink do not affect one another.
  • Segments can be compiled separately. If a function is in its own segment, the addresses of the other segments do not change when the function changes.
  • A library can be put in a separate segment and shared among processes.
  • Protection is set per segment: code is only executable, constants only readable, data readable and writable.

The disadvantages are familiar from contiguous allocation. Segments are of variable length; as they move around in memory, holes form between them. This external fragmentation is also called checkerboarding because of its pattern (Figure 8.56). The remedy is again compaction. In addition, a segment has to be in memory in its entirety; a very large segment may not fit in memory. The solution to this last problem is to page the segments as well; MULTICS and the Intel 386 followed this route.

(a)S0 4KS1 8KS2 5KS3 8KS4 7K(b)S0 4KS7 5K3KS2 5KS3 8KS4 7K(c)S0 4KS7 5K3KS2 5KS5 4K4KS4 7K(d)S0 4KS7 5KS2 5KS5 4KS4 7K7K(b)–(c) external fragmentation (checkerboarding), (d) compaction
Figure 8.56: The checkerboard that results from segments being moved around: (b)–(c) external fragmentation, (d) compaction.

8.10.5Comparison with paging

Table 8.24 gives Tanenbaum's comparison table, adapted to today's hardware.

Table 8.24: Paging and segmentation (adapted from Tanenbaum Figure 3-32). * Tanenbaum says “no” for paging here; today's R/W/NX bits and shared pages do the same job at page level.
IssuePagingSegmentation
Must the programmer be aware of the technique?NoYes
How many linear address spaces are there?1Many
Can the total address space exceed physical memory?YesYes
Can code and data be separated and protected separately?Yes, with page bits*Yes
Can tables whose size varies be accommodated easily?NoYes
Is sharing of functions among users easy?With shared pages*Yes
FragmentationInternal (last page)External
Why was it invented?A linear address space larger than physical memoryTo split program and data into independent logical spaces; sharing, protection
paging: one linear space, equal pagessegmentation: separate logical spacescodedatastacksymbols
Figure 8.57: In paging, the single linear address space is divided into equal pages; in segmentation, code, data, and stack are separate segments of different sizes.

The two techniques were born to solve different problems. Paging was invented to provide a single linear address space larger than physical memory; segmentation to split the program into logical pieces and to protect and share these pieces separately. History has come down on the side of paging: the protection and sharing advantages of segmentation can be had with page bits, while paging's advantage of escaping external fragmentation cannot be had in any other way.

8.11Real architectures and practice

8.11.1x86: segmentation, paging, and the flat model

The x86 family carries the whole history of segmentation. In the 8086's real mode the physical address is computed as segment × 16 + offset. The result is 20 bits, giving a 1 MiB address space; there is no protection. In the 80386's protected mode, a logical address consists of a selector and an offset. Of the 16-bit selector, 13 bits are the index, one bit selects the table (GDT or LDT), and two bits are the requested privilege level (RPL). The selector picks an 8-byte descriptor from the table; the descriptor holds the base and limit of the segment. Base + offset gives the linear address. The linear address then goes through two-level paging and is translated into a physical address (Figure 8.58). This is the hardware counterpart of MULTICS's idea of “paged segments.”

selectoroffset (32 bits)logical address (selector : offset)GDT / LDTdescriptor: base, limit+linear addresssegmentationpagingCR3 →page tablesphysical
Figure 8.58: In the Intel 32-bit architecture, segmentation translates a logical address into a linear address and paging translates the linear address into a physical address.

Despite this rich hardware, Linux and Windows effectively turned segmentation off even on 32 bits. All segments were given base 0 and limit 4 GiB. The linear address is then the same as the logical address; this is called the flat model. Protection is provided entirely by page bits. One reason for this is portability: segmentation existed only on x86, whereas paging exists on every architecture.

The long mode of x86-64 reflected this in hardware. The bases of the CS, DS, ES, and SS segments are taken as 0 by the hardware and the limit is not checked. Only the bases of the FS and GS segments are still used: in user space to point to thread-local storage (TLS), in the kernel to point to per-CPU data. CS additionally carries the current privilege level.

8.11.2ARMv8-A and RISC-V

The two other big architectures of today implement the same ideas under different names (Table 8.25).

Table 8.25: Memory management in ARMv8-A and RISC-V.
ARMv8-A (AArch64)RISC-V
Page (granule)4, 16, or 64 KiB; Apple Silicon and some Android 15+ devices use 16 KiB4 KiB (+ 2 MiB, 1 GiB, 512 GiB huge pages)
Virtual address48 bits (4 levels with 4 KiB, L0–L3); 52 bits with LVA/LPA2Sv39 (3 levels), Sv48 (4), Sv57 (5)
Table baseTTBR0_EL1 lower half (user), TTBR1_EL1 upper half (kernel)satp (mode + ASID + root frame)
Process tagASID 8/16 bitsASID (up to 16 bits)
ProtectionAP bits, UXN/PXN (no-execute), PAN (≈ SMAP)R/W/X/U bits, SUM
TLBHardware walk; A/D bits optionally in hardware (v8.1); contiguous bitHardware walk (in most implementations); sfence.vma
sign extension (25)VPN[2] 9VPN[1] 9VPN[0] 9offset 12Sv39: 3 levels × 512 entries; satp holds the root table's frame and the ASID
Figure 8.59: A RISC-V Sv39 virtual address: three 9-bit indexes (VPN[2], VPN[1], VPN[0]) and a 12-bit offset; the upper 25 bits are copies of bit 38.

Neither architecture has segmentation. The virtual address is flat; translation is done with a multilevel page table, the TLB, and ASIDs. ARMv8's two table base registers correspond to x86-64's canonical address split: user and kernel addresses are translated through separate tables. RISC-V's Sv39 gives a 39-bit, 512 GiB address space (3 × 9 + 12 = 39); Sv48 and Sv57 exist for larger spaces. In short, the same ideas as on x86-64 are implemented under different names.

8.11.3Separating policy from mechanism

The operating system takes part in paging at four moments. When a process is created, the page table is built. On a context switch the new process's table is activated and the TLB is set up. On a page fault the missing page is brought in. When the process terminates, the frames and the swap space are released.

Some of these jobs depend on the machine (the MMU's table format) and some do not (which page is placed where and when). The Mach kernel made this distinction explicit. The mechanism stayed in the kernel: a machine-dependent MMU handler and a machine-independent page-fault handler. The policy was given to an external pager running in user space (Figure 8.60). On a page fault, the handler in the kernel asks the external pager for the needed page. The pager reads the page from disk and hands it back. The MMU handler then maps the page into the process's address space.

user spacekernel spaceUser processExternal pagerFault handlerMMU handlerDisk1 page fault2 needed page3 request4 arrived5 here's the page6 map
Figure 8.60: A page fault with an external pager: the fault handler in the kernel asks the pager in user space for the page; the MMU handler maps the page.

This design gives flexibility and modularity: different applications can use different paging policies. The price is crossing the user–kernel boundary several times on every page fault. The idea has present-day counterparts too. Linux's userfaultfd mechanism forwards page faults to a program in user space; live migration of virtual machines and freezing a process and resuming it on another machine (CRIU) rest on it. In microkernels such as seL4 and Fuchsia the pager is already in user space.

8.12Summary

  • The CPU reaches only registers and main memory directly. In the memory hierarchy hardware manages the caches and the operating system manages main memory. The cache works with 64-byte lines and pays off thanks to temporal and spatial locality.
  • In a direct-mapped cache, block b goes to set b mod K; blocks that fall in the same set evict one another (conflict misses). The average access time is computed from the bottom up with T = s + m · Tbelow; in the example it is 3.8 ns, about 21 times faster than DRAM.
  • The address space solves the problems of protection and relocation. With base and limit registers the valid addresses are base … base + limit − 1; anything outside raises a trap.
  • Address binding can be done at compile, load, or execution time. Today's systems bind at execution time: the CPU produces a logical address and the MMU translates it into a physical address.
  • Dynamic loading (dlopen) loads code when it is called. With dynamic linking the library code is in memory once and shared; in ELF, what changes on the first call is not the code but the process-specific GOT entry. -fPIC produces position-independent code.
  • Standard swapping moves a whole process and is slow; today's systems swap cold pages and compress them first.
  • In contiguous allocation the hole is chosen by first fit, next fit, best fit, or worst fit. In external fragmentation the total free space is enough but not contiguous; by the 50-percent rule one third of memory can be lost. Internal fragmentation is the unused part inside a block. Compaction merges the holes but is expensive.
  • Free space is tracked with a bitmap (one bit per unit; looking for k consecutive zeros is linear) or a linked list (merging takes constant time if it is sorted by address). malloc embeds the free list inside the free chunks.
  • In paging logical memory is divided into pages and physical memory into frames; the address becomes (p, d) and physical = f × page size + d. There is no external fragmentation; internal fragmentation averages half a page. The optimal page size is about √(2se).
  • The page-table entry holds the P, R/W, U/S, NX, A, D, and G bits along with the frame number. The valid/invalid bit catches addresses outside the address space, but protection is at page granularity.
  • The TLB holds recent translations. The effective access time is EAT = (t + ε) α + (2t + ε)(1 − α); for ε = 20 and t = 100 ns it is 140 ns at α = 80% and 122 ns at 98%. With multilevel tables a miss is much more expensive.
  • The hierarchical table keeps lower tables only for the regions in use; x86-64 uses four (48-bit) or five (57-bit) levels with 9 bits per level. Huge pages enlarge the TLB reach. The size of a hashed table is proportional to the number of pages in use, that of an inverted table to physical memory.
  • Segmentation divides the address space into logical pieces of the form (segment, offset); each segment is a base–limit pair, and it leads to external fragmentation. On x86-64 only the FS/GS bases remain of segmentation; ARMv8 and RISC-V have no segmentation.

8.13Key terms

  • memory management
  • cache, cache line
  • hit / miss
  • base and limit registers
  • relocation
  • logical / physical address
  • memory management unit (MMU)
  • shared library
  • swapping
  • contiguous allocation
  • internal / external fragmentation
  • compaction
  • bitmap
  • buddy system
  • paging, page, frame
  • page table, page-table entry
  • valid–invalid bit
  • translation lookaside buffer (TLB)
  • effective access time
  • hierarchical page table
  • hashed page table
  • inverted page table
  • segmentation

8.14Test Yourself

  1. A direct-mapped cache with 4 sets and 64-byte lines starts out empty, and addresses 16, 80, 40, 272, and 20 are accessed in turn. Which accesses are hits?

    Answer

    The blocks are 0, 1, 0, 4, 0; the sets are 0, 1, 0, 0, 0. 16: miss. 80: miss. 40: block 0 is in set 0, hit. 272: block 4 evicts block 0, miss. 20: block 0 is gone, miss. In total 1 hit and 4 misses.

  2. A process's base register is 5000 and its limit register is 2000. The MMU first checks the limit and then adds the base. What happens to logical addresses 1999 and 2000?

    Answer

    1999 < 2000, so it is valid and goes to physical 6999. 2000 equals the limit; since the valid offsets are 0 … 1999, a trap occurs.

  3. The holes, in address order, are 300, 120, 500, and 200 K. The requests, in order, are 180, 100, and 450 K. In which of first fit, best fit, and worst fit can a request not be satisfied?

    Answer

    First fit: 180 → 300 (120 remains), 100 → the 120 remainder of the same hole (20 remains), 450 → 500 (50 remains); all are placed. Best fit: 180 → 200 (20), 100 → 120 (20), 450 → 500 (50); all are placed. Worst fit: 180 → 500 (320), 100 → 320 (220); for 450 the largest hole is 300, so the request cannot be satisfied.

  4. The page size is 1 KiB and page 4 is mapped to frame 9. What is the physical address corresponding to logical address 5000?

    Answer

    p = ⌊5000 / 1024⌋ = 4, d = 5000 − 4096 = 904. Physical = 9 × 1024 + 904 = 9216 + 904 = 10120.

  5. The TLB lookup takes 5 ns, a memory access 100 ns, the table is single-level, and the hit ratio is 90%. What is the effective access time? What must the hit ratio be for the EAT to be 125 ns?

    Answer

    A hit takes 105 ns and a miss 205 ns. EAT = 0.9 × 105 + 0.1 × 205 = 94.5 + 20.5 = 115 ns. From 205 − 100α = 125, α = 0.8, that is, 80%.

  6. In 32-bit x86 two-level paging (10 + 10 + 12), what are the top index, the bottom index, and the offset for virtual address 0x00C05123?

    Answer

    The top index is 0x00C05123 >> 22 = 3, the bottom index is (0x00C05123 >> 12) & 0x3FF = 0xC05 & 0x3FF = 5, and the offset is 0x123. The address lies in the 12–16 MiB region.

  7. How much space does an inverted page table occupy with 8 GiB of RAM, 4 KiB frames, and 8-byte entries? Would this value change if the system had 200 processes?

    Answer

    233 / 212 = 221 = 2,097,152 entries; × 8 bytes = 16 MiB. It would not change: the inverted table is proportional to physical memory and is a single table in the system, independent of the number of processes.

  8. In Silberschatz's segment table (segment 2: limit 400, base 4300; segment 4: limit 1000, base 4700), where do addresses (4, 999) and (2, 400) go?

    Answer

    (4, 999): 999 < 1000, physical 4700 + 999 = 5699. (2, 400): the offset equals the limit; since the valid offsets are 0 … 399, a trap.

  9. In a 1024 K buddy system, what size of block does a 70 K request get, and how much internal fragmentation results?

    Answer

    The smallest power of two that satisfies 70 K is 128 K. The process gets a 128 K block; the internal fragmentation is 128 − 70 = 58 K.

  10. In a dynamically linked program, which page changes after puts is called for the first time, and why does it matter?

    Answer

    Only the puts entry in the process-specific GOT page changes; the resolver writes the real address there. Because the code pages of the program and of libc do not change, they stay read-only and continue to be shared among all processes.

8.15Further reading

  • R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapters “Address Translation,” “Segmentation,” “Free-Space Management,” “Paging: Faster Translations (TLBs),” and “Paging: Smaller Tables”: treat segment registers and the TLB with short, runnable simulations. The book is free at ostep.org.
  • A. S. Tanenbaum and H. Bos, Modern Operating Systems, Chapter 3: treats the relocation problem, bitmaps and linked lists, and the MMU and multilevel-table examples, with the originals of the figures in these notes.
  • U. Drepper, “What Every Programmer Should Know About Memory,” 2007: a long paper that shows with measurements the effect of the cache, the TLB, and NUMA on program performance.
  • Linux kernel documentation, “Transparent Hugepage Support”: describes how transparent huge pages work, when they pay off, and how they are tuned.

8.16References

  1. A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018 — Chapter 9: Main Memory.
  2. A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th ed. (2014) / 5th ed. (2023), Pearson — Chapter 3: Memory Management (§3.1–3.3, 3.5–3.7).
  3. R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), ostep.org — “Address Spaces”, “Address Translation”, “Segmentation”, “Free-Space Management”, “Paging”, “TLBs”, “Smaller Tables”.
  4. D. E. Knuth, The Art of Computer Programming, Vol. 1, §2.5 Dynamic Storage Allocation (the 50-percent rule).
  5. Intel 64 and IA-32 Architectures Software Developer's Manual, Vol. 3A, Chapters 4–5 (Paging, Protection); Arm Architecture Reference Manual for A-profile (VMSAv8-64); RISC-V Privileged Specification (Sv39/48/57).
  6. U. Drepper, “How To Write Shared Libraries,” 2011; U. Drepper, “What Every Programmer Should Know About Memory,” 2007; Linux kernel documentation: mm/, “Transparent Hugepage Support,” userfaultfd.

Related pages: Chapter 8 slides · © Sercan Külcü. All rights reserved.