Operating Systems · Lecture Notes
Chapter 12: Multiprocessor Systems
Even an ordinary laptop today has eight or sixteen cores. On servers the number runs into the hundreds, and in a data center thousands of computers work together on a single job. An operating system designed for a single processor cannot exploit this hardware. How cores share the same memory, how caches stay coherent, how locks are implemented in this environment, and how threads are distributed over processors are new questions. The notes first describe the hardware of shared-memory multiprocessors: the bus, the crossbar and omega networks, NUMA, directory-based coherence, the MESI protocol, and false sharing. They then move on to multiprocessor operating system models, locks, and scheduling. Multicomputers that do not share memory, message passing, remote procedure call, and load balancing follow. The last sections cover virtualization, containers, middleware in distributed systems, and the cloud.
Learning outcomes
- Hardware
- Compare UMA (bus, crossbar, omega) and NUMA architectures; trace directory-based coherence on one address.
- Cache coherence
- Apply MESI state transitions to a sequence of reads and writes; find and fix false sharing.
- Operating system and locks
- Evaluate the separate-OS, master-slave, and SMP models; the TSL, ticket, TTAS, and MCS locks; and spinning versus switching.
- Scheduling
- Apply the limits of a shared ready queue, space sharing, and gang scheduling to an example.
- Multicomputers
- Compute the diameter of topologies; explain message passing, RPC, DSM, and load-balancing methods.
- Virtualization and distributed systems
- Recognize the hypervisor types, VT-x and EPT, containers, the kinds of middleware, and the cloud.
12.1Why multiple processors?
The oldest way to speed up a computer was to raise the clock speed. From the 1980s to the early 2000s, processor clock speeds doubled every few years. This road hit a wall around 2005. Even today the clock speed of desktop processors is between 3 and 5 GHz. Semiconductor makers continue to fit more transistors onto a chip every year. But these transistors are no longer spent on a single faster core; they are spent on more cores. This section describes the three basic organizations of parallel systems and the limit on the gain that parallelism brings.
12.1.1Three parallel organizations
There are three main ways to put several processors to work together (Figure 12.1). In the first, all processors are attached to a single shared memory. Every processor can read and write every memory word with ordinary LOAD and STORE instructions. This is called a shared-memory multiprocessor. In the second, each processor has its own memory, and the processors are connected to one another by a fast interconnect. One processor cannot read another's memory directly; data can only be sent as messages. This arrangement is called a multicomputer or a cluster. In the third, complete computers, that is, machines with their own disks, peripherals, and operating systems, are linked by a wide-area network such as the Internet. This is a distributed system.
The difference among the three is how tightly they are coupled. In a multiprocessor, communication is a memory access at the nanosecond level. In a multicomputer, a message takes a few microseconds. In a distributed system, messages take milliseconds. As the coupling loosens, the system can be scaled up, but it becomes harder to program and manage.
Shared-memory multiprocessors themselves divide in two. In a symmetric multiprocessor (SMP), all processors have equal rights to memory and to input/output (I/O) devices. Kernel code can run on any processor. In an asymmetric multiprocessor (AMP), the processors are not equal. Either only one of them runs the operating system, or each processor runs separate software. All of today's desktop and server operating systems are SMP. The asymmetric arrangement is met mostly in embedded chips.
A multiprocessor puts new jobs on the operating system. Which thread will run on which processor? What happens if two processors touch the same kernel table at the same time? How is data carried between processors? How are the copies of shared data kept consistent? The rest of this chapter answers these questions.
12.1.2The clock-speed limit and Amdahl's law
To understand why clock speed stopped, we have to look at power consumption. For many years, as transistors shrank, the operating voltage fell too. So power per unit area stayed constant. This observation is called Dennard scaling. In the mid-2000s the voltage could no longer be lowered. Raising the clock speed now meant overheating the chip. Manufacturers began to spend the transistor budget on more cores.
Increasing the number of cores does not speed up every program in the same proportion. Part of a program can only be executed sequentially: reading input, combining results, protecting a shared structure with a lock. This sequential part finishes in the same time no matter how many cores there are.
If a fraction p of a program's running time on a single processor can be parallelized and the fraction 1 − p stays sequential, then the speedup on n processors is
S(n) = 1 / ((1 − p) + p / n)
As n goes to infinity, p / n approaches zero; the speedup can never exceed 1 / (1 − p).
It is easy to see where the formula comes from. Let the time on a single processor be 1 unit. The sequential part takes 1 − p on n processors too. If the parallel part is divided evenly among n processors, it takes p / n. The new time is the sum of the two; the speedup is the ratio of the old time to the new time.
95% of a program can be parallelized (p = 0.95). What is the speedup on 8 and on 64 processors? What is the maximum speedup possible? How many processors are needed for a 10-fold speedup?
- n = 8. The parallel part takes 0.95 / 8 = 0.11875. The total time is 0.05 + 0.11875 = 0.16875. The speedup is 1 / 0.16875 ≈ 5.93. Eight processors give a gain of about 6 instead of the expected 8.
- n = 64. 0.05 + 0.95 / 64 = 0.05 + 0.0148 = 0.0648. The speedup is ≈ 15.42. The number of processors rose eightfold, and the speedup did not even triple.
- The limit. As n grows, the time approaches 0.05. The speedup cannot exceed 1 / 0.05 = 20. Even on 1024 processors the speedup is ≈ 19.64.
- For 10×. We need 0.05 + 0.95 / n = 0.1. From this 0.95 / n = 0.05 and n = 19.
The saying “performance grows as you add processors” is true only if the sequential part is very small. Even a 5% sequential part caps the gain at 20.
Amdahl's law assumes a fixed problem size. In reality, as the number of processors grows, the problem people want to solve grows too: a bigger simulation, more data. In that case the share of the sequential part shrinks, and the gain is greater than Amdahl predicted. This view is called Gustafson's law. Still, Amdahl's lesson holds: as the number of cores grows, shrinking the sequential part of the software becomes more important than adding cores. The operating system's own locks are part of this sequential part. A single kernel lock puts all processors in a queue and limits how far the system scales.
Computing the speedup as p × n. A program that is 95% parallel does not speed up by 0.95 × 64 ≈ 61 times on 64 processors. The sequential part takes the same time at every processor count and stays constant in the denominator; the correct value is about 15.4.
12.2Multiprocessor hardware
To understand how the operating system should behave on a multiprocessor, we first need to know how the hardware is built. This section describes the ways of connecting processors to memory, why memory access time is not the same everywhere, and how caches are kept coherent.
12.2.1UMA: the bus-based architecture
In a UMA (Uniform Memory Access) multiprocessor, every CPU reaches every memory word in the same time. In a NUMA (Non-Uniform Memory Access) multiprocessor, on the other hand, the access time varies with which memory the word is attached to.
UMA is the most comfortable arrangement for the programmer. Where the data is placed does not change performance; a program can be written for a multiprocessor just as it is written for a single processor. The simplest UMA machine attaches all processors and the memory to a single bus (Figure 12.2 (a)). When a CPU wants to read from memory, it first checks whether the bus is free. If it is free, it puts the address on the bus, asserts a few control signals, and waits until memory puts the response on the bus. If the bus is busy, it waits for it to become free.
This arrangement works well with two or three processors. As the number of processors grows, the bus saturates. With thirty-two or sixty-four processors, the CPUs spend most of their time waiting for the bus; adding a processor does not speed the system up. In arrangement (b), a cache is added to each CPU. Most reads are served from the local cache and do not go out on the bus; traffic drops sharply. The price is a new problem: a copy of the same memory line can exist in several caches. If one CPU changes its own copy, the other copies become stale. Keeping these copies coherent is the job of the hardware, and it is described in detail in later sections.
In arrangement (c), each CPU also has private memory. The compiler puts the program's code, constants, stack, and local variables in this private memory. Shared memory is used only for variables that are truly shared. This reduces bus traffic still further. But the compiler has to know which data is shared, and that makes programming harder.
In today's chips there is no longer a single shared bus. Cores, cache slices, and memory controllers are connected inside the chip by a ring or mesh network. Intel's “mesh” and AMD's Infinity Fabric are examples. The idea is still the same: a common communication medium, and large caches to protect that medium's limited bandwidth.
12.2.2The crossbar switch
The most direct way out of the single bus's bottleneck is to connect every CPU to every memory module by a separate path. The crossbar switch does this with a grid (Figure 12.3). The horizontal lines represent the CPUs and the vertical lines the memory modules. At every crosspoint there is a small electronic switch. When the switch closes, a direct path is established between that CPU and that memory module.
In the figure, CPU 2 first wants to access M5: the crosspoint (2, 5) closes and the path is established. Then the connections CPU 0 → M1 and CPU 6 → M3 are established at the same time. Requests going to different memory modules never wait for one another. For this reason the crossbar is a nonblocking network. If CPU 4 also wants M5, there is a path in the network, but the module itself is busy. The only point of contention is the memory module, not the network.
The cost of the crossbar is its size. For n CPUs and n memory modules, n² crosspoints are needed. An 8 × 8 switch has 64 crosspoints; a 64 × 64 one has 4096, and a 1024 × 1024 one has 1,048,576. That is why large crossbars are expensive. The old Sun Fire E25K server used an 18 × 18 crossbar. Today crossbars are used mostly inside the chip, at small scale, between the cores and the L3 cache slices.
12.2.3The omega network
To escape the n² cost, the network can be built in stages from small switches. The building block is a 2 × 2 switch: it has two inputs and two outputs. A message arriving at one input is routed to one of the two outputs. The message carries four fields: the destination memory module (Module), the address within the module, the opcode (read or write), and the value to write. The switch looks only at the Module field (Figure 12.4).
The omega network arranges these switches in log₂n stages. For 8 CPUs and 8 memories, 3 stages are needed; each stage has four switches (1A–1D, 2A–2D, 3A–3D). The wiring between stages is the perfect shuffle. The number of an output is rotated left by one bit to find the number of the input in the next stage. For example, line 011 is connected to input 110.
The routing rule is very simple. The switch in stage k looks at the k-th bit of the destination address from the left. If the bit is 0, it sends the message to the upper output; if 1, to the lower output. The source address plays no part in routing.
In an 8 × 8 omega network, CPU 011 wants to read memory 110. Which switches does the message pass through?
- Arriving at the input. Line 011 is connected by the shuffle to input 110. This input belongs to switch 1D (the inputs are 110 and 111).
- Stage 1. 1D looks at bit 1 of the destination: 1. The message leaves by the lower output. The number of this output is 111.
- Stage 2. 111 goes through the shuffle to 111 again; the message enters 2D. Bit 2 of the destination is 1; the message leaves by the lower output of 2D.
- Stage 3. The message enters 3D. Bit 3 of the destination is 0; the message leaves by the upper output and reaches memory 110.
The path is 1D (lower) → 2D (lower) → 3D (upper). (These paths and the conflict below were also verified with a short Python simulation that applies the shuffle rule.)
The response returns through the same network. For this, each switch, as it passes the message on, writes into the Module field which input it received it from, that is, one bit of the source address. By the time the message reaches memory, the Module field has accumulated the source address, 011. Memory sends the response back with this tag, and the response reaches CPU 011 by the same rule.
An omega network can carry many transfers at the same time, but not always. Suppose that at the same moment CPU 001 wants to go to memory 111. This request leaves 1B by the lower output and, after the shuffle, enters 2D. Since bit 2 of the destination is 1, it too wants the lower output of 2D. The two requests land on the same output and one has to wait (Figure 12.6). This is why the omega network is a blocking network.
An omega network uses n / 2 × log₂n switches. With 8 inputs, 4 × 3 = 12 switches are needed; with 64 inputs, 32 × 6 = 192; with 1024 inputs, 512 × 10 = 5120 switches. Compared with the more than one million crosspoints of a 1024 × 1024 crossbar, this is very little hardware. The price is twofold: requests wait when they conflict, and latency grows because every request passes through log₂n stages.
| n | Crossbar: n² crosspoints | Omega: (n/2)·log₂n switches | Omega stages |
|---|---|---|---|
| 8 | 64 | 12 | 3 |
| 64 | 4.096 | 192 | 6 |
| 1.024 | 1.048.576 | 5.120 | 10 |
Doing the routing in an omega network with the bits of the source address. On the way out, the switches look only at the destination address; the bits of the source address are recorded along the path only so that the response can find its way back. Another mistake is to think the omega network is nonblocking: if two requests want the same switch output, one waits.
12.2.4NUMA multiprocessors
UMA machines built with a bus or a switch network cannot be scaled beyond a few dozen processors. For machines with hundreds of processors, a compromise is needed: the wish to reach every memory word in the same time is given up. These machines are called NUMA multiprocessors (Definition 12.1).
In a NUMA machine, memory is divided into nodes. Each node has a few CPUs and a memory close to them. In today's two-socket server, each socket is a node (Figure 12.7). The socket's cores read from the DRAM attached to their own memory controller in about 80 ns. The memory of the other socket is reached over the inter-socket link (UPI on Intel, Infinity Fabric on AMD), in 140 ns for example. These latencies are example values; real values vary from machine to machine.
NUMA machines have three common properties. First, all CPUs see a single physical address space. Second, remote memory is also reached with ordinary LOAD and STORE instructions; the program does not send messages. Third, remote access is slower than local access. NUMA machines divide in two according to whether they have cache coherence. Those without it are called NC-NUMA and those with it CC-NUMA (cache-coherent NUMA). All of today's servers are CC-NUMA, and they mostly maintain coherence with a directory.
For the operating system, NUMA means a new responsibility: keeping data next to the processor that uses it. The average access time depends on what fraction of accesses are local.
average access = f · tlocal + (1 − f) · tremote
Here f is the local fraction of accesses.
Local access takes 80 ns and remote access 140 ns. What is the average access time when 90% and when 50% of accesses are local?
- f = 0.9. 0.9 · 80 + 0.1 · 140 = 72 + 14 = 86 ns.
- f = 0.5. 0.5 · 80 + 0.5 · 140 = 40 + 70 = 110 ns.
- Comparison. 110 / 86 ≈ 1.28. When the local access ratio falls from 90% to 50%, the program slows down by about 28%.
To avoid this loss, the operating system does three things. The first is the first-touch policy: a page is allocated from the memory of the node whose CPU uses it first. Second, the scheduler runs a thread, as far as possible, on the node where its data lives. Load balancing is done first within a node, and moves across nodes only if necessary. Third, Linux's automatic NUMA balancing samples which node accesses which pages of a process. It moves pages next to processes or processes next to pages. On the application side, too, a process and its memory can be bound to a particular node with the numactl tool.
NUMA is not specific to multi-socket servers. Large single-socket chips can be NUMA internally too. For example, the NPS (nodes per socket) setting on AMD EPYC and SNC (sub-NUMA clustering) on Intel split a socket into several NUMA nodes.
12.2.5Directory-based CC-NUMA
With a small number of processors, caches can be kept coherent by listening to a common bus. With hundreds of nodes, broadcasting every request to all nodes chokes the network. The solution is to keep a record of which caches hold each memory line. This record is called a directory. For a given line, messages are sent only to the nodes holding a copy of that line.
Tanenbaum's example makes the idea concrete. The system has 256 nodes. Each node has a CPU and 16 MiB of memory; the total memory is 256 × 16 MiB = 232 bytes. Cache lines are 64 bytes. A 32-bit physical address splits into three fields (Figure 12.8):
- the leftmost 8 bits are the node number (256 nodes);
- the next 18 bits are the block (line) number within that node's memory: 16 MiB / 64 B = 218 lines;
- the last 6 bits are the offset within the line (64 bytes).
Each node keeps a directory entry for each of the 218 lines in its own memory. In this simple design, if the line is currently in a cache, the entry stores the node number of that cache. A line can be cached in only one node at a time.
The CPU at node 20 executes LOAD 0x24000108 and then LOAD 0x24000080. Initially, in node 36's directory, entry 2 holds 82 and entry 4 is empty. What happens at each request?
- Decoding the address. The leftmost byte of 0x24000108 is 0x24 = 36: the line is in node 36's memory. The remaining 24 bits are 0x000108 = 264; 264 = 4 · 64 + 8, so block 4, offset 8.
- Request. The address is not local. Node 20's memory controller sends node 36 the message “I want block 4”.
- Directory. Node 36 looks at its directory: entry 4 is empty, so the line is in no cache. The current copy is in node 36's own RAM.
- Reply. Node 36 sends the line to node 20 and writes 20 in entry 4: “a copy of this line is at 20”.
- Second request. In 0x24000080 the node is again 36; since 0x80 = 128 = 2 · 64 + 0, it is block 2, offset 0. In the directory, entry 2 says 82: the line is in node 82's cache.
- Invalidation. Node 36 sends node 82 the message “invalidate the line”. If the line has been modified at 82, it is written back first. Then the line is sent to node 20 and 20 is written in entry 2.
All this communication is done with point-to-point messages. No bus has to be listened to by all the caches. The cost of the directory is memory. If each entry holds an 8-bit node number and a valid bit, it comes to 9 bits. A node's directory is 218 × 9 bits = 294,912 bytes. This is an overhead of 9 bits for every 64-byte line, that is, about 1.76% of memory.
It is not realistic for a line to be cacheable at only one node; a line that is read often should have many copies. Real systems keep the copy set in a bit vector with one bit per node, or in a list of a limited number of pointers. Inside multicore chips, structures called “snoop filters” do the same job: they track which line is in which core's private caches.
12.2.6The cache coherence problem
Each core has its own private cache, and these caches hold copies of the same memory. Figure 12.10 shows the problem. In memory, x = 5. Both cores have read x and brought it into their caches. Core 1 writes 7 to x. The write changes only the copy in its own cache. If core 0 now reads x, it sees the old value 5 in its own cache. From the program's point of view this is wrong: the last write to x was 7.
Cache coherence is the condition that writes to the same address are seen in the same order by all cores, and that a read returns the value most recently written to that address.
Hardware provides coherence in two ways. In the snooping method, all cache controllers listen to the common bus continuously. If someone else is about to write a line that a cache holds a copy of, the cache sees this on the bus and updates or invalidates its copy. This method suits a small number of cores. In the directory method, a list of copies is kept and messages go only to the nodes concerned. This method scales to multicore chips and NUMA machines.
There are two basic policies for writes. In the write-invalidate policy, a core invalidates the other copies before writing; they ask for the line again on their next read. In the write-update policy, the new value is sent to all copies. On repeated writes to the same line, updating produces traffic every time, while invalidation does so only on the first write. That is why nearly all of today's processors use invalidation.
Coherence concerns a single address. In what order writes to different addresses are seen by other cores is a separate matter. This topic is called the memory consistency model. The x86 model (x86-TSO) is fairly strong; ARM and RISC-V use weaker models. Lock implementations therefore include memory barriers: they force the writes in the critical section to be visible to everyone before the lock is released.
12.2.7The MESI protocol
The most common of the write-invalidate protocols is MESI. It takes its name from the initials of the four states a cache line can be in (Table 12.2).
| State | Meaning |
|---|---|
| M (Modified) | The only copy of the line is in this cache and it is dirty: the value in memory is stale. The line is written back to memory when it is evicted from the cache. |
| E (Exclusive) | The only copy is here and it is clean: it matches memory. A write turns the line into M without going out on the bus. |
| S (Shared) | Clean copies may be in several caches. To write, the other copies must first be invalidated. |
| I (Invalid) | The copy is invalid; an access is a cache miss. |
The state of a line changes with two kinds of events: its own core's reads and writes, and another core's requests seen on the bus. Figure 12.11 shows all the transitions together. Three kinds of requests circulate on the bus. BusRd asks to read a line. BusRdX asks exclusively, with the intent to write a line; the other copies are invalidated. BusUpgr asks only for invalidation so that a line in state S can be written; since the data is already at hand, the line is not transferred.
The table reads as follows. If a line in state I is read locally, BusRd is sent. If another cache says “I have it”, the line becomes S; if nobody does, it becomes E. If a line in state I is to be written, BusRdX is sent and the line becomes M. Writing a line in state E is silent: since it is known that there is no other copy, nothing goes out on the bus. Writing a line in state S requires BusUpgr. If another core wants to read a line in state M, its owner puts the data on the bus (Flush), also writes it back to memory, and makes the line S. If another core wants to write, the owner again supplies the data and makes the line I.
The reason the E state exists is to make a common case cheaper: a thread first reads its private data and then writes it. Without E, the read would make the line S, and the following write would generate a needless BusUpgr. The protocol has commercial derivatives too. In Intel's MESIF, the F (Forward) state decides which of the shared copies answers requests. In AMD's MOESI, the O (Owned) state denotes a line that is dirty but shared; the line can be given to other caches without being written back to memory.
12.2.8MESI step by step
How the protocol works is best seen on a sequence of operations. In a two-core system, x is initially only in memory and its value is 0. The line of x is in state I in both caches.
C0 and C1 perform the following operations in turn: C0 reads x, C1 reads x, C1 writes x = 1, C0 reads x, C0 writes x = 2, C0 writes x = 3. After each step, what are the states of the line in the two caches, the value in memory, and the bus message?
| Step | Operation | C0 | C1 | Memory | Bus | Explanation |
|---|---|---|---|---|---|---|
| 0 | — | I | I | 0 | — | x only in memory |
| 1 | C0 reads | E | I | 0 | BusRd | no other copy: exclusive and clean |
| 2 | C1 reads | S | S | 0 | BusRd | C0 snoops the request and says “I have it” |
| 3 | C1: x = 1 | I | M | 0 | BusUpgr | invalidation to write from S; memory is now stale |
| 4 | C0 reads | S | S | 1 | BusRd, Flush | C1 supplies the dirty line to both C0 and memory |
| 5 | C0: x = 2 | M | I | 1 | BusUpgr | invalidation again |
| 6 | C0: x = 3 | M | I | 1 | — | already M: no bus traffic |
Six operations produce five bus operations. At the end of the sequence the current value of x is 3, and it is only in C0's cache; memory still says 1. (The table was produced with a Python simulation that applies the MESI rules.)
The last step shows an important result. Repeated writes by one core to data that only it uses are cheap: as long as the line stays in state M, it generates no messages. What is expensive is different cores writing to the same line in turn. Each write moves the line from one cache to another. False sharing in the next section rests on this observation.
Confusing the E and S states. Both are clean, but E means “no other copy”; writing to a line in E silently makes it M. To write to a line in S, the other copies must first be invalidated. Another mistake is to think memory is not updated at step 4: when a line in state M is handed to another cache, it is also written back to memory.
12.2.9False sharing
Coherence protocols track cache lines, not variables. In today's processors a line is 64 bytes. If two completely independent variables fall on the same line, the hardware treats them as shared data.
False sharing is needless coherence traffic caused by different variables used by different cores being in the same cache line.
In the code below, two threads increment two separate counters. In logic there is no sharing whatsoever and no lock is needed.
struct counters { /* bad */ long a; /* offset 0 */ long b; /* offset 8 */ }; struct padded { /* good */ _Alignas(64) long a; _Alignas(64) long b; }; /* thread 0: for(..) s.a++; thread 1: for(..) s.b++; */
In struct counters, a is at byte 0 and b at byte 8; both fall in the same 64-byte line. Thread 0 runs s.a++ in a loop on C0, and thread 1 runs s.b++ on C1. The events unfold as follows (Figure 12.13):
- C0 does
a++. It gets the line in state M; C1's copy becomes invalid. - C1 does
b++. The line moves to C1 and becomes M there; the copy in C0 becomes invalid. - C0 does
a++again and pulls the line back.
When both cores write often, back to back, the line goes from one core to the other every time. This is called “ping-pong”. Moving a line takes between tens and a hundred and fifty nanoseconds; the increment itself is a few cycles. As a result, the two-thread program can run even slower than the single-thread version doing the same work.
The fix is to put each counter in a separate line. In struct padded, C11's _Alignas(64) specifier aligns each field to a 64-byte boundary. The size of the structure rises to 128 bytes and 56 bytes per counter are wasted. In return the ping-pong disappears entirely; the gain is often a many-fold speedup. In Java the same job is done with the @Contended annotation, and in the Linux kernel with the ____cacheline_aligned macro. The kernel's per-CPU counters are likewise kept in separate lines for each CPU for this reason.
Mistaking false sharing for a race condition and adding a mutex. There is no race on separate variables; the results are correct, only the program is slow. Adding a mutex does not solve the problem; on the contrary, the lock's line too starts bouncing between cores. The right fix is to place the data on separate lines.
The same problem appears on a larger scale too. In distributed shared memory the unit of coherence is not a line but a page. If two independent variables are on the same 4 KiB page, the page goes back and forth between machines over the network.
12.2.10Multicore and heterogeneous chips
Most of today's processors host several independent cores on a single chip. These chips are called multicore or chip multiprocessors (CMP) (Figure 12.14). In a typical layout each core has private L1 and L2 caches. The L3 cache is shared and is distributed in slices over the on-chip network. On server sockets the number of cores runs into the hundreds: the AMD EPYC 9005 series has 192 cores and the Intel Xeon 6900E series has 288 efficiency cores.
Multicore chips have four properties that concern the operating system:
- Chiplets: Large processors are no longer a single piece. Groups of cores are placed on separate dies and combined in one package. Even within a single socket, a core's distance to the L3 and to memory is not the same everywhere. The scheduler tries to keep cooperating threads on the same chiplet.
- Big and little cores: ARM's big.LITTLE design, Apple's chips, and Intel's P/E cores combine fast but power-hungry cores with slow but efficient ones. The operating system places work according to energy. On Linux, energy-aware scheduling (EAS) does this job. Intel's Thread Director hardware also gives Windows hints about which thread suits which core.
- Accelerators: A GPU and, for AI workloads, an NPU sit on the same chip and share the same memory. These are not scheduled directly; the operating system sends them work through a driver.
- Shared resources: The L3 cache and memory bandwidth are common. A memory-intensive job on one core can slow down a job on another core.
12.2.11Simultaneous multithreading
A superscalar core can execute several instructions every cycle. But a single thread rarely fills these slots. A cache miss or a dependency between instructions makes the core wait, and execution units sit idle (Figure 12.15 (a)).
In simultaneous multithreading (SMT), a single physical core executes the instructions of two or more hardware threads in the same cycle. The core appears to the operating system as several logical CPUs.
Intel calls this Hyper-Threading; AMD uses the name SMT. The logical CPUs have separate register sets. The execution units and the L1 and L2 caches, however, are shared. The gain is typically between 10% and 30%. If two threads want the same unit, for example the floating-point unit, there may be no gain at all. For this reason the scheduler places jobs on empty physical cores first. It uses the two logical CPUs of one physical core together only when all physical cores are busy.
SMT has a security side as well. Two threads that share the same core can infer each other's data through the shared caches. Side-channel attacks such as L1TF and MDS exploit this. Linux's core scheduling puts only mutually trusting threads on the same physical core. Some vendors have begun to give up SMT altogether; the P cores of Intel's Lunar Lake (2024) chip have no SMT.
12.2.12GPUs and heterogeneous computing
CPUs and GPUs are designed for different purposes (Figure 12.16). A CPU consists of a small number of large, complex cores; with large caches and mechanisms such as branch prediction, it tries to minimize the latency of a single thread. A GPU contains thousands of simple lanes and maximizes total throughput. The lanes execute the same instruction in groups of 32. NVIDIA calls these groups warps, AMD wavefronts. This design suits data-parallel jobs in which the same operation is applied to every data element: graphics, AI, and scientific computing.
GPU programs are written in CUDA, ROCm/HIP, OpenCL, or SYCL. The CPU launches the function that will run on the GPU (this too is called a kernel, not to be confused with the operating system kernel), moves data to GPU memory, and waits for the result. In the meantime the operating system and the driver manage GPU memory and time-share the GPU contexts of different processes. Today's systems also offer a unified or shared virtual memory between CPU and GPU. When the GPU accesses a page, a page fault can occur through the IOMMU and the page is moved to the GPU. In large AI clusters each node has 4–8 GPUs. The GPUs are connected to one another by NVLink and the nodes to one another by InfiniBand or RoCE, and data is moved directly with RDMA.
12.3Multiprocessor operating system types
Once the hardware connects several processors to the same memory, one has to decide how the operating system will use those processors. Three models have emerged in history. This section describes the three in turn and compares them.
12.3.1Each CPU has its own operating system
The simplest way is to divide memory into as many partitions as there are CPUs and run an independent copy of the operating system on each CPU in its own partition (Figure 12.17). The operating system's code is read-only and so can be shared; its data is separate in each copy. When a process makes a system call, the call is trapped on its own CPU and that CPU's operating system handles it.
The appeal of this model is its simplicity. A single-processor operating system can be used almost unchanged. Because the partitions are independent of one another, no locks are needed between them either. But the absence of sharing creates four problems:
- Processes are not shared. Each operating system has its own process table. While one CPU is overloaded, another may sit idle; work cannot easily be moved from one to the other.
- Pages are not shared. Memory may run out in one partition while another partition still has free pages.
- Each operating system keeps its own buffer cache. The same disk block can be in two caches in different states. If both copies are modified, the disk block becomes inconsistent. The only way to avoid this problem is to remove the buffer caches, which lowers performance.
- One CPU's operating system does not know what the others are doing; common scheduling cannot be done.
This model lives on today under other names. The hardware partitioning of large servers and the separate virtual machines running on a hypervisor rest on the same idea. In research, the Barrelfish operating system uses it as a deliberate design. In this “multikernel” design, each core is treated as a separate node that communicates by messages.
12.3.2The master-slave model
In the second model, a single copy of the operating system and all its tables are on one CPU only; this CPU is called the master (Figure 12.18). The other CPUs, the slaves, run only user processes. When a process on a slave CPU makes a system call, the call is redirected to the master and handled there.
The master-slave model solves most of the problems of separate operating systems. There is a single ready list. When a slave becomes idle, it asks the master for a new process; the load is thus balanced automatically. Memory pages are handed out from a single pool, and since there is a single buffer cache, no inconsistency arises. Because only the master touches kernel data, no locks are needed either.
The model's weakness is that it does not scale. All system calls are handled on a single CPU. Under a system-call-heavy workload, the master becomes the bottleneck. As the number of slaves grows, calls queue up in front of the master and adding new CPUs gains little. If the master crashes, the whole system stops too. For this reason the master-slave model is useful in systems with few CPUs.
This is the classic form of asymmetric multiprocessing (AMP). Today the asymmetric arrangement is met mostly in embedded chips. For example, next to the Cortex-A cores running Linux there is a Cortex-M core running a real-time operating system. Linux starts this core through the remoteproc infrastructure and communicates with it over OpenAMP.
12.3.3Symmetric multiprocessors
The third model removes the master's bottleneck. There is a single copy of the operating system in memory, but every CPU can run it (Figure 12.19). A system call is handled on the CPU that makes it. Load and memory are balanced dynamically, as in master-slave. This model is called symmetric multiprocessing (SMP).
The price of SMP is concurrency. Two CPUs can touch the same kernel table at the same time: one adds a process to the ready list while another removes a process from the same list. To prevent these races, the kernel's shared structures must be protected with locks. The easiest first step is to protect the whole kernel with a single lock. A CPU takes this lock when entering the kernel and releases it when leaving. Linux 2.0 started out exactly this way; this lock is called the “Big Kernel Lock” (BKL). A kernel with a single lock is really a somewhat more flexible form of the master-slave model: only one CPU can be in the kernel at a time.
To scale, the kernel is divided into mutually independent critical regions, and each region is protected by its own lock. Linux whittled the BKL down step by step over more than a decade and removed it entirely in version 2.6.39 (2011). Today the kernel has thousands of fine-grained locks. Alongside them are used RCU (read-copy-update), a mechanism in which readers take no lock at all, and per-CPU data structures, in which each CPU touches only its own copy.
Fine-grained locks have their own danger. If one code path takes locks A and B in that order and another path takes them in reverse order, two CPUs can wait for each other forever. To prevent this, kernel developers give the locks an order and require every code path to take locks in the same order. Linux's lockdep tool catches violations of this rule at run time.
12.3.4Comparing the three models
Table 12.3 puts the three models side by side.
| Separate OS | Master-slave | SMP | |
|---|---|---|---|
| OS copies | one per CPU | one (on the master) | one (everyone runs it) |
| Where is a system call handled? | local CPU | master CPU | local CPU |
| Ready list | per CPU | single, on the master | single or per CPU + balancing |
| Load balancing | none | good | good |
| Scalability | good but no sharing | the master is a bottleneck | depends on lock design, best |
| Complexity | lowest | low | highest |
| Today | virtual machines, partitioning | embedded AMP, legacy systems | Linux, Windows, macOS, BSD |
These three models are for shared-memory multiprocessors. Its difference from multicomputer operating systems must be kept in mind. In a multiprocessor, all CPUs see the same physical memory. In a multicomputer, each node has its own memory and its own copy of the operating system; the nodes communicate only by messages.
Attributing problems to the wrong model. Inconsistent buffer caches and unbalanced load are problems of the “each CPU has its own operating system” model. The master being a bottleneck is a problem of the master-slave model, and races in kernel tables and lock-order bugs are problems of SMP.
12.4Synchronization
An SMP kernel protects its shared structures with locks. On a single processor, a lock can be implemented easily by disabling interrupts or with an indivisible instruction. On a multiprocessor, both approaches raise new problems. This section describes the hardware foundation of the lock, more scalable kinds of locks, and the choice between spinning and sleeping while waiting.
12.4.1TSL and bus locking
The TSL (test and set lock) instruction reads a memory word, puts its old value in a register, and writes 1 to the word. On a single processor this instruction is indivisible: no interrupt arrives in the middle of the instruction. If the lock word is 0 the lock is free, and if 1 it is held. If TSL returns 0 as the old value, the lock has been acquired.
On a multiprocessor, the indivisibility of the instruction alone is not enough. The read and the write of TSL are two separate bus cycles. Another CPU can slip in between these two cycles (Figure 12.21):
- CPU 1 reads the lock word: 0, that is, free.
- Before CPU 1 writes, CPU 2 reads too: again 0.
- CPU 1 writes 1 to the word; CPU 2 writes 1 too.
- Both think “the lock is mine” and mutual exclusion is broken.
Disabling interrupts does not help either. Disabling interrupts protects only the CPU that executes the instruction; the other CPUs keep accessing memory. The fix is in the hardware: TSL locks the bus for the duration of the read and the write. During this time no other CPU can access memory. On today's x86 processors, the LOCK prefix mostly locks not the whole bus but only the cache line concerned. The line is held in state M for the duration of the operation and the requests of other cores are held off. ARM does the same job in two ways: the LDXR/STXR instruction pair (if someone else wrote in the meantime, the write fails and the loop repeats) or single-instruction atomic operations such as CAS in the LSE extension.
12.4.2The ticket lock
A correctly working TSL lock still has two shortcomings. First, it is not fair: when the lock becomes free, which of the waiters takes it is a matter of chance, and one can keep losing and starve. Second, every attempt does a write and generates cache traffic. The ticket lock solves the first problem completely and the second to a large extent.
The idea is the take-a-number machine at a bank. There are two counters: next hands out the next ticket, and serving shows whose turn it is. A thread that wants the lock atomically increments next and takes the old value as its own ticket. Then it waits until serving equals its ticket. The thread that releases the lock increments serving by one. The Java program in the slides shows two threads protecting a shared counter with this lock:
import java.util.concurrent.atomic.*; public class Ticket { static AtomicInteger next = new AtomicInteger(); static volatile int serving = 0; static int counter = 0; static void lock() { int my = next.getAndIncrement(); while (serving != my) Thread.onSpinWait(); } static void unlock() { serving++; } public static void main(String[] a) throws Exception { Runnable job = () -> { for (int i = 0; i < 100_000; i++) { lock(); counter++; unlock(); } }; Thread t0 = new Thread(job); Thread t1 = new Thread(job); t0.start(); t1.start(); t0.join(); t1.join(); System.out.println("counter = " + counter); } }
The key lines of the code are these. next is an AtomicInteger; getAndIncrement() increments the counter indivisibly and returns the old value. On x86 this is a single LOCK XADD instruction. Even if two threads call it at the same time, they get different tickets. serving is volatile. Every read sees the real value. The write in unlock() also makes the writes in the critical section visible to everyone. Thread.onSpinWait() gives the processor the hint “I am spinning”; on x86 it becomes the PAUSE instruction and reduces power consumption. The serving++ in unlock() need not be atomic, because only the lock's owner writes to serving.
T0 and T1 call lock() in turn; T0 releases when it finishes the critical section. How do the counters and the state of the threads change?
| Step | Event | next | serving | T0.my | T1.my | State |
|---|---|---|---|---|---|---|
| 0 | start | 0 | 0 | — | — | lock free |
| 1 | T0 takes a ticket | 1 | 0 | 0 | — | serving == 0: T0 enters, counter++ |
| 2 | T1 takes a ticket | 2 | 0 | 0 | 1 | serving ≠ 1: T1 spins |
| 3 | T1 spins | 2 | 0 | 0 | 1 | reads serving from the S copy in its own cache |
| 4 | T0 releases | 2 | 1 | — | 1 | the write invalidates T1's copy |
| 5 | T1 reads again | 2 | 1 | — | 1 | 1 == my: T1 enters |
At the end of 2 × 100,000 increments, the program prints counter = 200000. The program was run five times with JDK 21 and printed 200000 each time. When the lock calls were removed and only counter++ was left, six runs gave values between 118,108 and 151,847: the increments overwrote one another.
The ticket lock is fair: threads enter the lock in ticket order, that is, in arrival order (FIFO). No thread starves. The waiters only read: they read serving from the S copy in their own caches and do not occupy the bus. When the lock is released, a single coherence message invalidates all the copies. It still has one weakness. After the release, all waiters read the line again, but only one can enter. With many waiters, this wave of reads is expensive.
12.4.3Spinlocks and cache traffic
Locks that spin in a loop while waiting for the lock are called spinlocks. On a multiprocessor, the cost of a spinlock is the cache traffic it generates while waiting. Figure 12.23 compares three designs.
(a) A pure TSL loop. The waiting CPU executes TSL nonstop. Every TSL is a write: it pulls the line in state M and invalidates the other copies. The lock line is moved constantly among the waiters. When the lock's owner wants to access this line, it too gets in the queue. As a result the waiters slow down the lock's owner, and the release of the lock is delayed too.
(b) Read first, then TSL. This method is called TTAS (test-and-test-and-set). The waiting CPU first tries the lock with an ordinary read. If the lock is held, the read is served from the copy in its own cache and nothing goes out on the bus. When the lock looks free, it tries TSL. In addition, exponential backoff can be used: after a failed TSL, the CPU waits a while and doubles this time at each failure. This reduces the waiters rushing in at the same moment.
(c) The MCS lock. In the lock proposed by Mellor-Crummey and Scott in 1991, the waiters form a linked list. Each waiter spins on a flag in its own node, and each node is in a separate cache line. The lock is managed with a single tail pointer that points to the end of the list. The releaser writes to the flag of the next in the list. This is a single remote write and wakes only the next CPU. MCS is both fair and generates constant traffic independent of the number of waiters. Linux's current qspinlock is based on this idea.
None of these designs is made to prevent data inconsistency; the pure TSL lock works correctly too. The aim is to reduce coherence traffic, that is, lines being moved needlessly between caches.
12.4.4Code trace: the TTAS lock
The implementation of the TTAS lock in C is short. The call tsl(k) stands for the hardware instruction that indivisibly writes 1 to *k and returns the old value.
void lock(int *k) { for (;;) { while (*k == 1) /* spin locally */ ; if (tsl(k) == 0) /* looked free */ return; /* acquired */ } } void unlock(int *k) { *k = 0; }
lock() is an endless loop. The inner while spins as long as the lock is 1; this is a read, and if the copy is in the cache it does not go out on the bus. When the lock looks 0, tsl() is tried. If the old value is 0, the lock has been acquired and the function returns. If another CPU slipped in and took the lock first, the old value is 1; the loop goes back to the local read. unlock() writes 0 to the lock word.
CPU 0 holds the lock (k = 1, the line is in CPU 0's cache in state M). CPU 1 and CPU 2 call lock(). CPU 0 releases the lock and the two waiters race. How many bus operations occur?
| Step | Event | CPU 0 | CPU 1 | CPU 2 | Bus operation (total) |
|---|---|---|---|---|---|
| 0 | start | M, k=1, lock held | I | I | 0 |
| 1 | CPU 1 reads *k (miss) | S | S, k=1 | I | 1 |
| 2 | CPU 2 reads (miss) | S | S | S, k=1 | 2 |
| 3 | both spin locally | S | S | S | 2 |
| 4 | CPU 0 unlock(): k = 0 | M, k=0 | I | I | 3 |
| 5 | CPU 1 reads (miss), sees k = 0 | S | S | I | 4 |
| 6 | CPU 2 reads (miss), sees k = 0 | S | S | S | 5 |
| 7 | CPU 1 tsl: old value 0, lock acquired | I | M, k=1 | I | 6 |
| 8 | CPU 2 tsl: old value 1, fails | I | I | M, k=1 | 7 |
| 9 | CPU 2 spins locally | I | I | M | 7 |
Seven bus operations occur in total. No matter how long the spinning in step 3 lasts, this number does not grow; in a pure TSL loop, every attempt would generate one more operation. (The states were verified with the same MESI simulation.)
There is an interesting detail in step 8. CPU 2's failed TSL is also a write. The lock does not change (1 is written over 1), but the line moves from CPU 1 to CPU 2. When CPU 1 leaves the critical section and calls unlock(), it has to pull the line back. The price of the race is these extra operations. As the number of waiters grows, on every release all the waiters read and try TSL; this is why the MCS lock scales better.
Thinking the inner read loop in TTAS suffices and removing the TSL. Between the read and the write another CPU can take the lock; at steps 5 and 6 both CPUs saw k = 0. The atomic TSL ensures the lock's correctness; the inner read only reduces traffic.
12.4.5Spin or switch?
When a thread cannot get a lock, it can do one of two things. It can spin: it keeps polling the lock without giving up the CPU. The CPU is wasted in the meantime, but the thread continues as soon as the lock is free. Or it can switch (block): it sleeps and the CPU is given to another thread. The price of this is two context switches: one when it goes to sleep and one when it wakes. The awakened thread also meets a cold cache.
Figure 12.25 compares the two options on a timeline. The lock becomes free at t = 3 µs, and a context switch takes C = 5 µs. The spinning thread waits 3 µs and enters the critical section. The switching thread leaves at 5 µs and the CPU moves to other work. The thread comes back at 5 µs and enters the critical section only at the 15th microsecond.
The decision rule follows from this. If the expected wait is shorter than the cost of switching, that is, 2C, spinning is cheaper; otherwise sleeping is. For short critical sections spinning is right, and for regions that involve disk I/O or last long, sleeping is.
The problem is that the wait time is not known in advance. For this there is a well-known compromise: spin first for as long as the cost of switching, that is, for 2C, and if the lock still cannot be acquired, sleep. In the worst case the cost of this strategy does not exceed twice the cost of an ideal algorithm that knows the wait time in advance. An online strategy with such a guarantee is called a competitive strategy.
C = 5 µs, so the cost of switching is 2C = 10 µs. The thread first spins for 10 µs and then sleeps. How does the cost of this strategy compare with the ideal one when the wait is t = 3, 10.1, and 50 µs?
- t = 3. It spins for 3 µs and the lock is acquired; the cost is 3 µs. The ideal cost is also min(3, 10) = 3 µs; the ratio is 1.
- t = 10.1. It spins for 10 µs and then sleeps: 10 + 10 = 20 µs. The ideal is to sleep from the start: 10 µs. The ratio is 2; this is the worst case.
- t = 50. Again 10 + 10 = 20 µs is spent; the ideal is 10 µs. The ratio is 2.
Had the threshold been chosen as C, then when t slightly exceeded C the cost would be C + 2C = 3C and the ideal about C; the ratio would rise to 3. (The ratios were verified by computing them in Python for thousands of values of t.)
Real systems apply this idea with adaptive locks. Linux's futex-based mutex spins briefly if the lock's owner is running on another CPU, and sleeps immediately if the owner is asleep. On Windows, a spin count can be set for CRITICAL_SECTION. The Java virtual machine also keeps uncontended locks cheap and converts them into an operating system lock when contention rises; this is called lock inflation.
Inside the kernel one more rule applies: one cannot sleep in a region where interrupts are disabled, because the interrupt that would wake the sleeping code cannot arrive. In such regions only a spinlock can be used.
Spinning on a spinlock in a single-CPU system. If the lock's owner is waiting in the ready queue on the same CPU, the owner can never make progress unless the spinning thread gives up the CPU. Spinning makes sense only when the lock's owner is running on another CPU.
12.5Multiprocessor scheduling
On a single processor, the scheduler answers just one question: which thread is next? On a multiprocessor a second question is added: on which CPU will this thread run? If the threads are independent of one another, the second question is easy. If the threads of the same application communicate with one another, the two questions must be answered together. This section describes three approaches: time sharing, space sharing, and gang scheduling.
12.5.1Time sharing: a shared ready queue
For mutually independent processes, the simplest approach is for all CPUs to take work from a single common ready queue (Figure 12.26). The queue is organized by priority levels, as in single-processor systems. When a CPU becomes free, it locks the queue, removes the highest-priority thread, releases the lock, and runs that thread. In the figure, 14 of the 16 CPUs are running; CPU 3 and CPU 7 are idle. Whichever of the idle CPUs locks the queue first will take A, at the head of the priority 7 queue.
The biggest advantage of this approach is that load is balanced automatically. While one CPU waits for work, work does not pile up on another CPU. It has three drawbacks:
- The single lock is a bottleneck. As the number of CPUs grows, contention for the queue's lock grows too. In a system with hundreds of CPUs, the CPUs wait for one another to take the next job.
- The cache stays cold. If a thread has been running on CPU 4 for a while, its cache and TLB are full of its data. When it comes out of the queue again it may land on any idle CPU, for example CPU 12. There the cache is empty, and the thread spends its first milliseconds on misses. To prevent this, the scheduler tries to run a thread, if possible, on the CPU where it last ran. This tendency is called processor affinity.
- Preemption while holding a lock. If a thread's time slice ends while it holds a spinlock, it is preempted. The other CPUs that want the lock spin in vain until the owner runs again.
For the last problem, the idea of smart scheduling described by Tanenbaum can be used. A thread that acquires a spinlock sets a flag visible process-wide and clears the flag when it releases the lock. The scheduler does not preempt a thread with the flag set. It gives it a little extra time to finish its critical section. A similar mechanism is used in virtual machines today: the problem of a virtual CPU that holds a lock being preempted while the other virtual CPUs spin in vain is called “lock holder preemption”.
Today's operating systems do not use a single common queue. Linux and Windows keep a separate ready queue for each CPU. Lock contention goes away and a thread automatically stays on the same CPU. Imbalance between the queues is corrected by a separate load-balancing mechanism. A CPU with little load pulls work from another CPU's queue, or the load balancer occasionally pushes jobs from loaded CPUs to idle ones. Linux does this balancing with a hierarchy called “scheduling domains”. It balances first among the SMT siblings of the same physical core, then among cores that share the same L3, and last among NUMA nodes.
12.5.2Space sharing
For threads that communicate tightly with one another, another approach is more suitable: running all the threads of the same application at the same time, on separate CPUs. This is called space sharing. When a job starts, the number of CPUs it asks for is allotted to it. It holds these CPUs until the job ends. There is no multiprogramming per CPU, and so no context switching. If there are not enough free CPUs, the job waits until enough CPUs become free. The simplest ordering is first-come, first-served (FCFS).
In the example of Figure 12.27, 32 CPUs are distributed among four jobs: 4 + 6 + 8 + 12 = 30 CPUs are in use, 2 are idle. If the next job in the queue wants 3 CPUs, it waits until one of these jobs ends. In the meantime two CPUs stay idle. This is the main drawback of space sharing. When a thread blocks for I/O, its CPU is not given to another job and sits idle. Today the job schedulers in HPC clusters (Slurm, PBS) partition nodes in exactly this way: a job gets the nodes it asks for and keeps them until it finishes.
12.5.3Gang scheduling
An example shows why communicating threads slow down under time sharing (Figure 12.28). There are two CPUs, the time slice is 100 ms, and two jobs run with time sharing. The two threads of job A, A0 and A1, send messages to each other. On CPU 0 the order is A0, B0, A0, B0…; on CPU 1 it is B1, A1, B1, A1…. A0 sends a request to A1 at t = 0. A1 is not running at that moment and sees the request only at t = 100. It sends the reply at once, but this time A0 is not running. A0 receives the reply at t = 200. A single request-reply has taken 200 ms.
Gang scheduling is running all the members of a group (a gang) of interdependent threads together in the same time slice, on different CPUs. All the CPUs start their slices at the same time and end them at the same time.
Gang scheduling combines time sharing and space sharing. It has three parts. Interdependent threads are grouped as a gang. All members of a gang run at the same time, on different CPUs. All gang members begin their slices together and end them together. This way a message sent by one member is seen at once by its receiver, and the reply comes back in the same slice.
In a system with 6 CPUs there are five jobs: A has 6 threads, B 3, C 3, D 5, and E 7. How are they placed into slices with gang scheduling?
- Slice 0. A's 6 threads fill the 6 CPUs.
- Slice 1. B (3) and C (3) together fill the 6 CPUs.
- Slice 2. D's 5 threads and E0. E's 7 threads do not fit in a single slice; its first member runs here.
- Slice 3. E's remaining 6 threads (E1–E6).
- Cycle. After four slices the order repeats from the start.
In total 6 + 3 + 3 + 5 + 7 = 24 threads fit exactly into 4 slices × 6 CPUs = 24 slots; utilization is 100%. In Tanenbaum's example, E is a large gang and has been split across two slices. Under a stricter definition no member of a gang runs apart from the others; then this arrangement could not be made, because E does not fit in one slice.
The two conditions of gang scheduling can be summarized briefly: the gang members start at the same time and are all on different CPUs. This idea appears today in virtual machines as well. The vCPUs of a virtual machine with many virtual CPUs wait for one another through locks. If the hypervisor schedules them together (co-scheduling), a vCPU is prevented from spinning in vain while waiting for a preempted sibling.
Keeping in mind only the “at the same time” condition of gang scheduling. If the members ran at the same time but in turn on the same CPU, they would still wait for one another. Both conditions are needed together: the same slice and different CPUs.
12.6Multicomputers
Shared-memory multiprocessors cannot be scaled beyond a few hundred CPUs, and scaling them is expensive. Larger systems are built from computers that do not share memory. This section describes the hardware of multicomputers, how messages are carried across the network, and the programming and load-distribution methods used in these systems.
12.6.1Nodes and network interfaces
A multicomputer is a system in which nodes, each consisting of a CPU, RAM, and a network interface, are joined by a fast interconnect. Memory is not shared; each node runs its own copy of the operating system, and the nodes communicate only by messages.
Multicomputers are also called clusters. A node is often an ordinary server; what makes it special is the network interface and the interconnect. Large-scale simulations, high-performance computing, and AI training run on these systems. The systems on the TOP500 list, which ranks the world's fastest computers, are multicomputers with tens of thousands of nodes.
In a multicomputer, the biggest obstacle to performance is the copying of messages (Figure 12.30). In the worst case a message is copied five times:
- from the sending process's user buffer to a kernel buffer,
- from the kernel buffer to the memory of the network interface card (NIC),
- from the NIC over the wire to the receiving NIC,
- from the receiving NIC's memory to the receiver's kernel buffer,
- from the kernel buffer to the receiving process's user buffer.
Each copy takes microseconds, and the network itself can be faster than that. The ways to reduce copies are these. The NIC memory can be mapped directly into user space; the process writes the message there itself. The NIC can read and write main memory directly with DMA. The most advanced solution is RDMA (remote direct memory access). On InfiniBand and RoCE networks, the NIC writes to the memory of a process on the remote machine without the kernel being involved at all. A message thus reaches the other side in under a microsecond instead of a few microseconds.
12.6.2Interconnection topologies
How the nodes are connected to one another is called the topology. There are two basic measures for evaluating a topology. The diameter is the number of hops on the shortest path between the two farthest nodes; it determines the worst-case latency. The number of links, on the other hand, determines the cost. Figure 12.31 shows six common topologies.
- Single switch (star): every node is attached to the switch in the center. The diameter is 2, but the switch is a single point of failure and cannot be scaled up.
- Ring: each node has two neighbors. In a bidirectional ring of n nodes the diameter is n / 2.
- Grid: nodes are laid out in a square arrangement. In a k × k grid there are 2(k − 1) hops between the two farthest corners.
- Torus: the edges of the grid are wrapped around to the opposite edge. In a k × k torus the diameter is 2 · ⌊k / 2⌋.
- Hypercube: a d-dimensional hypercube has 2d nodes and each node is attached to d neighbors. The diameter is d = log₂n.
For a system of 1,024 nodes, what are the diameter and the number of links of a ring, a 32 × 32 grid, a 32 × 32 torus, and a 10-dimensional hypercube?
- Ring. Diameter 1024 / 2 = 512, links 1024.
- Grid. Diameter (32 − 1) + (32 − 1) = 62. There are 31 horizontal links in each row and 31 vertical links in each column: 2 × 32 × 31 = 1984.
- Torus. With the wraparound links, at most 16 hops are needed in each dimension: diameter 32. 4 links leave each node and each link is shared by two nodes: 1024 × 4 / 2 = 2048.
- Hypercube. Diameter log₂1024 = 10. Each node has 10 links: 1024 × 10 / 2 = 5120.
The values are collected in Table 12.4. The diameters of the small 16-node topologies were also computed with a breadth-first search and compared with the values in the figure.
| n = 1,024 | Ring | Grid 32 × 32 | Torus 32 × 32 | Hypercube (10D) |
|---|---|---|---|---|
| Diameter | 512 | 62 | 32 | 10 |
| Links | 1.024 | 1.984 | 2.048 | 5.120 |
The table shows a tradeoff. The hypercube has the smallest diameter, but also the largest number of links. Moreover, in a hypercube the number of links per node grows with the dimension; when the number of nodes doubles, one more link must be added to every node. Today's supercomputers mostly use fat-tree and dragonfly topologies. Japan's Fugaku supercomputer, on the other hand, uses a six-dimensional torus network (Tofu).
12.6.3Routing in a hypercube
In a hypercube the nodes carry d-bit numbers, and two nodes are neighbors only if they differ in a single bit. A 4-dimensional hypercube has 16 nodes; each node has 4 neighbors. For example, the neighbors of 0000 are 1000, 0100, 0010, and 0001. This structure makes routing very easy. The length of the shortest path between two nodes equals the number of bits in which their numbers differ, that is, the Hamming distance. At each step the message advances by correcting one of the differing bits.
E-cube routing corrects these bits always in the same order, from left to right. For a message going from 0000 to 1011, source ⊕ destination = 1011; three bits differ. The first differing bit on the left is corrected: 1000. This step moves the message from the lower 3-dimensional cube to the upper one. Then it comes to 1010, and finally to 1011 (Figure 12.32). The number of hops is 3; in a 4-dimensional hypercube the worst case is log₂16 = 4 hops.
An important property of the rule is that it is local. Each node decides which neighbor to send the message to by looking only at its own number and the destination's number. No routing table is needed. Because the bits are always corrected in the same order, the path never loops either.
12.6.4Code trace: e-cube routing
E-cube routing is a few lines in C. src is the source and dst the destination node, and d is the dimension of the hypercube; the function prints each node passed.
void route(int src, int dst, int d) { int u = src; for (int b = d - 1; b >= 0; b--) { int m = 1 << b; if ((u ^ dst) & m) { /* bit differs */ u ^= m; /* go to neighbor */ printf("%d ", u); } } }
u is the node where the message currently is. The loop starts at the leftmost bit (b = d − 1) and moves to the right. m = 1 << b is the mask with only bit b set to 1. If (u ^ dst) & m is nonzero, u and the destination differ in this bit. u ^= m flips that bit; this means the message moves to the neighbor in that dimension. The loop runs d times; the number of hops equals the number of differing bits.
How does the call route(6, 13, 4), that is, the message going from 0110 to 1101, proceed step by step?
| b | m | u (before) | u ^ dst | Bit differs? | u (after) | Output |
|---|---|---|---|---|---|---|
| — | — | 0110 | 1011 | — | 0110 | — |
| 3 | 1000 | 0110 | 1011 | yes | 1110 | 14 |
| 2 | 0100 | 1110 | 0011 | no | 1110 | — |
| 1 | 0010 | 1110 | 0011 | yes | 1100 | 12 |
| 0 | 0001 | 1100 | 0001 | yes | 1101 | 13 |
The output is 14 12 13. The message follows the path 0110 → 1110 → 1100 → 1101 in 3 hops. The initial u ⊕ dst = 1011 said from the start that three bits differ. (The loop was transcribed one-to-one into Python and run.)
Computing the number of hops from the difference of the node numbers. The difference between 6 and 13 is 7, but the number of hops is the number of differing bits: 0110 ⊕ 1101 = 1011, that is, 3. Adjacency is not numerical closeness but a single-bit difference.
12.6.5Store-and-forward or cut-through
A packet travels from source to destination through several switches. How the switches forward the packet changes the total latency considerably. As an example, consider a 4 KiB packet and 10 Gb/s links. It takes 4096 × 8 bits / 1010 bit/s ≈ 3.28 µs for the packet to cross one link.
In store-and-forward, each switch takes the whole packet into its buffer, checks it, and only then sends it on to the next link. A packet going from A to B through two switches crosses three links. On each link the whole packet is waited for: 3 × 3.28 = 9.83 µs. Latency grows linearly with the number of hops.
In cut-through, a switch sets up the path as soon as it has read the packet's header and starts forwarding without waiting for the rest of the packet. The packet flows like a pipe; its front part arrives at the destination while its back part is still leaving the source. Wormhole routing is the form of this idea used with packets divided into small pieces (flits). The total latency is about one packet time plus the small header delays of the switches. If each switch processes the header in 0.05 µs, the total is 3.28 + 2 × 0.05 ≈ 3.38 µs (Figure 12.34).
The gap widens as the number of hops grows. The latency of store-and-forward is proportional to the number of hops; in cut-through each hop adds only a small header delay. That is why high-performance computing networks and data-center switches use cut-through or wormhole routing.
12.6.6Blocking and nonblocking send
In a multicomputer, processes communicate with send and receive calls. The most important design question for these calls is whether the sender waits for the message to be delivered.
In blocking or synchronous send, the send call does not return until the message has been delivered (Figure 12.35 (a)). The process traps into the kernel, the message is copied and sent; only after that does the process continue. This method is simple and safe: when send returns, the buffer can be reused. The price is that the CPU waits idle for the whole transmission.
In nonblocking or asynchronous send, send returns immediately and the process keeps running (b). Computation and communication proceed in parallel. But a new problem arises: if the sender modifies m in the buffer before the transmission ends, what data goes to the other side? Tanenbaum lists four answers to this problem (Table 12.5).
| Option | Cost |
|---|---|
| Blocking send | CPU idle during transmission |
| Nonblocking + copy to the kernel | CPU time for the extra copy |
| Nonblocking + interrupt on completion | hard to program (race conditions) |
| Copy on write (CoW) | an extra copy again if the buffer is written |
In the second option, the kernel copies the message into its own buffer and the process continues at once; the buffer is now free. In the third, when the transmission is finished an interrupt or signal reaches the sender; the process must not touch the buffer until then. In the fourth, the page of the buffer is marked read-only; a copy of the page is made only if the process tries to write to the buffer.
There are similar options on the receiver side. A blocking receive waits until a message arrives. With polling, the process looks now and then to see whether a message has come. A third way is to start a new thread when the message arrives, or to run the code inside the message directly (an active message). The present-day counterparts of these concepts are familiar too. In the MPI library, MPI_Send/MPI_Recv are blocking calls, and MPI_Isend/MPI_Irecv with MPI_Wait are nonblocking ones. On Linux, io_uring and zero-copy MSG_ZEROCOPY are modern answers to the same problem.
12.6.7Remote procedure call
send and receive are an I/O model; they force the programmer to build the messages. In 1984 Birrell and Nelson proposed a more familiar model: calling a procedure on another machine as if it were a local procedure.
A remote procedure call (RPC) is a program on one machine calling a procedure on another machine with the syntax of an ordinary local call. The construction and sending of messages are hidden from the programmer.
The hiding is done by small procedures called stubs. When the client writes result = add(3, 4), it is really calling the client stub. A call goes through these steps (Figure 12.36):
- The client calls the client stub like a local procedure. The parameters are pushed on the stack as usual.
- The stub packs the parameters into a message and makes a system call to the kernel. The packing is called marshalling.
- The kernel sends the message across the network to the server machine.
- The server's kernel hands the message to the server stub.
- The server stub unpacks the parameters and calls the server procedure locally.
The reply follows the same path in reverse: server → stub → kernel → network → client kernel → client stub → client. From the client's point of view, add is an ordinary procedure; it is only a little slow.
This apparent simplicity hides several difficulties:
- Pointers. An address on the client is meaningless in the server's address space. An array parameter is copied by value and sent, and the changes the server makes are copied back on return. This method is called copy-restore. Structures built with pointers, such as linked lists, cannot easily be sent this way.
- Arrays of unknown length. In C the length of an array is not stored in the array itself. The stub cannot know how many bytes to send; the length must be given as a separate parameter.
- Global variables. The server cannot see the client's global variables.
- Partial failures. In a local call, caller and callee crash together. In an RPC, the server or the network can crash alone. If the client, receiving no reply, repeats the call, the procedure may run twice. For this reason it must be stated whether an RPC system provides “at least once” or “at most once” semantics.
- Data representation. The two machines may differ in byte order or integer size; the stub converts the data to a common format.
Stubs are not written by hand; they are generated automatically from an interface definition. The most common examples today are gRPC and its interface language Protocol Buffers, Apache Thrift, and Java RMI.
Thinking of the stub as a network driver or a mechanism that runs remote code locally. The stub is just an ordinary procedure that packs the parameters into a message, sends it to the kernel, and unpacks the reply. The remote procedure runs on the server.
12.6.8Distributed shared memory
RPC hides message passing behind a procedure call. A more ambitious idea is to create the illusion of shared memory on machines that do not share memory. This idea is called distributed shared memory (DSM). The layer that provides the illusion can be in hardware (NUMA), in the operating system, or in a user library. Page-based DSM, defined by Li and Hudak in 1989, uses the operating system's virtual memory mechanism.
All machines share the same virtual address space, but each page is physically in the memory of a single machine (Figure 12.37). When a CPU accesses a page that is not in its memory, the MMU raises a page fault. The operating system finds out, for example through a directory, which machine the page is on, and requests it. The page is moved over the network to this CPU, the page table is updated, and the instruction that caused the fault is executed again. From the process's point of view this is no different from an ordinary page fault served from disk; only the page comes not from disk but from another machine.
Constantly moving frequently read pages is expensive. So a read-only page is replicated: page 10 in the figure has a copy at both CPU 0 and CPU 1, and both CPUs read locally. If a CPU wants to write to a replicated page, the other copies are invalidated. This is the page-sized counterpart of MESI. For the same reason, false sharing also appears at page size. If two independent variables used on different machines are on the same page, the page goes back and forth between the two machines.
Page-based DSM is not common today. Moving a 4 KiB page over the network is expensive, and a page is a coarse unit for sharing. High-performance computing turned to message passing (MPI) and PGAS languages (partitioned global address space). The present-day counterpart of the idea is in hardware: the CXL standard allows multiple machines to use a common memory pool.
12.6.9Graph-theoretic deterministic allocation
In a multicomputer, which node the processes run on also matters. If two processes that communicate a lot are put on separate nodes, every message of theirs crosses the network. If they are put on the same node, their messages stay local. If the traffic between processes is known in advance, the assignment can be solved as a graph problem. The processes are the vertices and the traffic between them the edge weights. The aim is to partition the vertices into equal-sized sets while minimizing the total weight of the edges that remain between the sets.
Nine processes A–I are to be assigned to 3 machines, three each. The traffic between processes is the edge weights in Figure 12.38; the total traffic is 39. What is the network traffic of the alphabetical assignment and of the best assignment?
- Alphabetical assignment. {A, B, C}, {D, E, F}, {G, H, I}. Within machines only the edges A–B (3), B–C (2), E–F (5), G–H (3), and H–I (2) remain: a total of 15. The network traffic is 39 − 15 = 24.
- A better assignment. {A, B, C}, {D, G, H}, {E, F, I}. Within machines A–B (3), B–C (2), D–G (4), D–H (2), G–H (3), E–F (5), E–I (1), F–I (4) remain: a total of 24. The network traffic is 39 − 24 = 15.
- Is it the best? Nine processes can be divided into three groups of three in 9! / (3!3 · 3!) = 280 different ways. When all are tried, the smallest network traffic is 15, and only the assignment above gives this value.
(All 280 partitions were enumerated in Python and their cut weights computed.)
When the processes that communicate a lot are gathered on the same machine, the network traffic drops by more than a third. But this method has two limits. First, the traffic must be known in advance. Second, the problem is NP-hard in general: as the number of processes grows, the number of possible partitions explodes and they cannot all be tried. In practice, heuristic methods are used.
12.6.10Distributed heuristic load balancing
If the traffic is not known, or if jobs are constantly coming and going, load is distributed with simple rules that the nodes run among themselves. There are two basic algorithms.
In the sender-initiated algorithm, a node that creates a new job looks at its own load. If its load exceeds a threshold, it asks another randomly chosen node “what is your load?” (Figure 12.39). Probing is limited, for example to at most N = 3 nodes. If a node below the threshold is found, the job is sent to it; if none is found, it runs locally. Eager and coauthors studied this algorithm in 1986. In the example in the figure the threshold is 7, and the node with load 9 probes two nodes with loads 3 and 1. It sends the job to the least loaded one, the node with load 1.
The drawback of this algorithm appears when the whole system is loaded. Every node tries to send out jobs, and every probe is wasted. The probes themselves also put extra load on the network and the nodes. As load grows, the system spends more of its time probing.
The receiver-initiated algorithm approaches the problem from the opposite direction. A node that has finished its work and become idle looks for work itself. It probes random nodes and, if it finds a loaded one, takes a job from it (Figure 12.40). The cost of probing falls on the node that is idle anyway. When the system is loaded, there are few idle nodes and so few probes. This is why the receiver-initiated algorithm works well under high load, and the sender-initiated one under low load. There are also algorithms that combine the two.
The present-day counterpart of receiver-initiated balancing is work stealing. Each worker thread has its own work queue. A worker whose queue is empty steals work from the other end of another worker's queue. Cilk, Java's ForkJoinPool, and the runtimes of Go and Rust's Tokio use this method.
12.7Virtualization
Most servers in a data center are lightly loaded most of the time. Allocating a separate physical machine to each service wastes hardware, energy, and space. Virtualization solves this by running several virtual machines on a single physical machine. Each virtual machine runs its own operating system and is isolated from the others. This section describes the software that runs virtual machines, how the processor and memory are virtualized, and containers.
12.7.1Hypervisors: type 1 and type 2
A hypervisor or virtual machine monitor (VMM) is the software layer that creates and runs virtual machines. It presents each virtual machine with an environment that imitates the hardware of a real computer. The operating system running in a virtual machine is called the guest.
Hypervisors divide in two according to where they run (Figure 12.41). A type 1 hypervisor runs directly on the hardware; there is no other operating system beneath it. It is also called a bare-metal hypervisor. VMware ESXi, Xen (today XCP-ng), and Microsoft Hyper-V are of this kind. Linux's KVM module turns the Linux kernel itself into a type 1 hypervisor. Most clouds use KVM or its derivatives; AWS's Nitro system and Google's cloud are examples. When Hyper-V is enabled on Windows, Windows too begins to run on top of the hypervisor, in a privileged “root partition”.
A type 2 hypervisor runs like an ordinary application on a host operating system. VirtualBox, VMware Workstation and Fusion, Parallels, and UTM are of this kind. It leaves device access to the host operating system; so the overhead in I/O is greater. A pure type 2 hypervisor interprets the guest's instructions or converts them by binary translation; QEMU without KVM works this way. Type 2 hypervisors in practice, however, load a kernel module and use the processor's virtualization support. What determines a hypervisor's type is not whether it uses hardware support but where it runs.
Popek and Goldberg set out in 1974 the condition required for a machine to be virtualized efficiently. Let us divide instructions into two groups. Sensitive instructions are those that affect the state of the machine, for example the page table or I/O, or behave differently depending on it. Privileged instructions are those that trap when an attempt is made to execute them in user mode.
If all the sensitive instructions of a machine are privileged, that is, they trap in user mode, an efficient hypervisor can be built for that machine.
The meaning of the condition is this. The guest operating system is run in user mode. Its ordinary instructions are executed directly on the hardware. When it tries to execute a sensitive instruction, it traps and control passes to the hypervisor. The hypervisor emulates the effect of the instruction for the virtual machine. Classic x86 did not satisfy this condition. For example, the POPF instruction also changes the interrupt flag; but in user mode it silently ignores this change without trapping. The guest operating system thinks it has disabled interrupts, and the hypervisor has no idea. This problem was solved first by binary translation and then by hardware support.
The reasons for using virtualization are well known today. Many servers are consolidated onto one machine. A running virtual machine can be moved to another physical machine without interruption; this is called live migration. A snapshot of a virtual machine can be taken and it can be rolled back to it when needed. This is also the foundation of cloud computing.
12.7.2Trap and emulate: VT-x and AMD-V
Intel added hardware virtualization support to x86 with VT-x in 2005, and AMD with AMD-V in 2006. This support gives the processor a new operating mode. The hypervisor runs in root mode and the guest in non-root mode. The guest operating system runs in the kernel mode of non-root mode and believes it is truly in kernel mode. But the real control is with the hypervisor.
When the guest kernel wants to execute a sensitive instruction, this happens (Figure 12.42):
- The guest kernel executes a sensitive instruction:
mov cr3, which changes the page table base,out, which writes to an I/O port, orhlt, which halts the processor. - The hardware does not execute the instruction. Instead it hands control to the hypervisor with a VM exit. The guest's state and the reason for the exit are written to a memory structure called the VMCS.
- The hypervisor emulates the effect of the instruction. For example, it updates the shadow table or the EPT, or changes the state of a virtual device.
- The hypervisor returns to the guest with a VM entry; the guest continues from the next instruction.
Only the guest's sensitive instructions trap; the rest of its instructions run directly on the hardware, at full speed. Even so, a VM exit takes about a microsecond. A workload that exits often therefore slows down. Before hardware support, VMware (1999) solved this problem with binary translation. The code of the guest kernel is scanned before it runs, and sensitive instructions are replaced with safe code fragments that call the hypervisor. The translated code is cached and used again and again.
12.7.3Paravirtualization
There is one more way to avoid the cost of trap and emulate: modify the guest operating system.
In paravirtualization, the guest operating system knows it is running on a hypervisor. Instead of sensitive instructions, it makes direct calls to the hypervisor; these calls are called hypercalls.
A hypercall is the analog of a system call one layer down. Just as an application requests service from the operating system, the guest operating system requests it from the hypervisor. Because there is no trap-and-emulate cost, the method is faster. The price is that it requires changes in the guest operating system's source code. Xen (2003) is the hypervisor that first popularized this approach; a modified version of Linux ran on Xen at nearly native speed (Figure 12.43).
It was a problem that every hypervisor had its own hypercall interface: separate versions of a kernel were needed. So that a single kernel could run both on bare metal and on different hypervisors, a common interface called VMI (Virtual Machine Interface) was proposed. When hardware support became widespread it was no longer needed, and VMI was removed from Linux in 2011. Today paravirtualization lives on mostly in drivers. virtio disk and network drivers, paravirtual clocks, and Hyper-V's “enlightenments” are examples. In today's clouds, CPU and memory are fully virtualized with hardware support. I/O is done either with paravirtual drivers such as virtio or by assigning a piece of a device directly to the virtual machine with SR-IOV.
12.7.4Memory virtualization: shadow tables and EPT
Address translation in a virtual machine has two layers (Figure 12.44). A process in the guest produces a guest virtual address (GVA). The guest operating system's page tables translate it to a guest physical address (GPA). But the guest's “physical” memory is really just a piece of memory that the hypervisor has allocated. The hypervisor must translate the GPA to a real host physical address (HPA).
The solution before hardware support was shadow page tables. For each guest process the hypervisor keeps a table that maps the GVA directly to the HPA, and gives the MMU this table. It makes the guest's own tables read-only. When the guest tries to change a table entry, it traps; the hypervisor reflects the change in the shadow table too. Translation is fast, but every table change by the guest means a VM exit. Workloads that create processes or take many page faults therefore slow down a lot.
Intel's EPT (Extended Page Tables, 2008) and AMD's NPT (Nested Page Tables) give this job to the hardware. The MMU walks the two tables together. The guest changes its own table without trapping; the hypervisor manages only the GPA → HPA table. The cost is in the TLB miss. Each entry of the guest table is a GPA; to be read, it must first go through the EPT.
The guest and the host use 4-level page tables. On a TLB miss, with no table entry in the cache, how many memory accesses are needed in the worst case (excluding the final data access)?
- One level of the guest table. The address of the entry is a GPA. It is first translated to an HPA by walking 4 EPT levels (4 accesses), then the entry itself is read (1 access): 5 accesses.
- Four levels. 4 × 5 = 20 accesses. At the end the GPA of the data is obtained.
- The final translation. The GPA of the data must go through the EPT as well: 4 more accesses. Total 20 + 4 = 24.
The general formula is (n + 1)(m + 1) − 1, where n is the number of guest levels and m the number of EPT levels. For n = m = 4 it comes to (4 + 1)² − 1 = 24 accesses. If both sides have 5 levels, (5 + 1)² − 1 = 35 accesses are needed. Without virtualization, the same miss would need only 4 accesses.
There are two ways to reduce the impact of this long walk. Large pages (2 MiB or 1 GiB) reduce both the number of table levels and the TLB misses. Tagging TLB entries with the virtual machine's identifier (VPID on Intel, ASID on AMD), in turn, makes it unnecessary to flush the TLB when switching between virtual machines.
Hypervisors can also hand out more memory to guests than there is physical memory (overcommitment). Two mechanisms support this. The balloon driver is a driver running inside the guest. When the hypervisor wants memory, it allocates memory in the guest and gives these pages back to the hypervisor; the guest decides for itself what goes to disk through its own page replacement policy. Linux's KSM (Kernel Same-page Merging) mechanism finds pages with identical contents in different virtual machines and merges them into a single copy. If someone writes to the page, a separate copy is made by copy-on-write.
12.7.5Containers and virtual machines
Each virtual machine runs its own kernel; it takes seconds to start and holds gigabytes of memory. For many applications this is excessive. Isolating applications from one another is often enough; a separate kernel is not needed.
A container is a group of processes that shares the host's single kernel and is isolated from other processes with the help of namespaces and cgroups.
Linux containers rest on three kernel mechanisms. Namespaces show a group of processes their own process numbers, file system tree, network interfaces, and host name; the group cannot see other processes. Control groups (cgroups) limit the amount of CPU, memory, and I/O the group can use. seccomp, for its part, restricts the system calls the group can make. A container holds the libraries and tools of a distribution, but the kernel is the host's (Figure 12.45).
| Virtual machine | Container | |
|---|---|---|
| Isolation boundary | hardware level, separate kernel | same kernel: namespace, cgroup, seccomp |
| Startup / overhead | seconds, GB of memory | milliseconds, MB of memory |
| Different operating system | yes (Windows on Linux) | no (same kernel family) |
| Examples | KVM, Hyper-V, ESXi | Docker, Podman, Kubernetes pods |
A container's isolation is weaker than a virtual machine's. Because all containers share the same kernel, a vulnerability in the kernel affects all of them. Solutions in between are therefore spreading. Firecracker, used by AWS Lambda, creates small virtual machines (micro-VMs) that start within milliseconds. gVisor serves a container's system calls in a kernel in user space. Kata Containers runs each container in a lightweight virtual machine. WSL 2 on Windows also runs a real Linux kernel in a lightweight Hyper-V virtual machine; Linux containers on Windows run in this virtual machine.
Thinking a container has its own kernel. On a server running Linux 6.8, in a container based on Ubuntu 20.04, uname -r still shows 6.8; only the user space in the container is Ubuntu 20.04. A virtual machine on the same server, by contrast, boots its own guest kernel and shows its version.
12.8Distributed systems
The nodes of a multicomputer are in the same room, under the management of the same organization, and connected by a private network. In a distributed system all of these assumptions are relaxed. This section describes distributed systems, the network that holds them together, and the four main kinds of middleware.
12.8.1Distributed systems and middleware
A distributed system consists of autonomous computers that communicate over a network. Each computer manages its own operating system, memory, and resources. The system nonetheless tries to look to the user like a single, consistent system. The nodes may run different hardware and different operating systems, may belong to different organizations, and may be spread around the world.
Middleware is a software layer in a distributed system that sits between the operating systems and the applications and offers applications a model that is the same on all nodes.
Different operating systems can speak a common language only thanks to middleware (Figure 12.46). Middleware is based on one of four basic paradigms. In document-based middleware everything is a document; the Web is the example. In file-based middleware everything is a file; NFS and SMB are like this. In object-based middleware everything is an object; CORBA, Java RMI, and gRPC are of this kind. In coordination-based middleware, processes communicate through a shared space or a broker; Linda and publish-subscribe systems are of this kind.
True distributed operating systems that manage all the nodes like a single operating system were also tried. Amoeba and Plan 9 are the best known. These remained research systems. Today each node runs its own operating system; distribution is handled by middleware and cluster managers such as Kubernetes.
12.8.2Comparing the three kinds of systems
This chapter has covered three parallel organizations: the multiprocessor, the multicomputer, and the distributed system. Table 12.7 puts them side by side following Tanenbaum's comparison.
| Property | Multiprocessor | Multicomputer | Distributed system |
|---|---|---|---|
| Node structure | CPU | CPU, RAM, network interface | complete computer |
| Peripherals | all shared | shared (except perhaps disk) | full set at each node |
| Location | same rack | same room | possibly worldwide |
| Communication between nodes | shared RAM | dedicated interconnect | traditional network |
| Operating system | one, shared | many, the same | many, possibly different |
| File system | one, shared | one, shared | each node's own |
| Administration | one organization | one organization | many organizations |
12.8.3Network hardware and encapsulation
A network binds the nodes of a distributed system. The most common kind of local network is Ethernet (Figure 12.48). In the classic Ethernet of 1976, all computers shared a single cable. A computer listened to the cable before sending and sent if it was idle. If two computers sent at the same time, a collision occurred, and both backed off for a random time and tried again. This method is called CSMA/CD. Today each computer is connected to a switch by its own cable. The links work at speeds between 1 and 400 Gb/s and in full duplex; there are no collisions.
Local networks are joined to one another with routers. Organizations' networks connect to Internet service providers, and they connect to the Internet backbone. The backbone consists of high-speed fiber links and exchange points where networks join one another.
Network software is organized in layers. When application data is sent, each layer adds its own header. The transport layer adds the TCP header, the network layer the IP header, and the link layer the Ethernet header and the trailing checksum (FCS). This is called encapsulation. On the receiving side the headers are stripped in reverse order and each layer interprets its own header.
12.8.4Network protocols and service types
Network services are classified from two angles. In a connection-oriented service, a connection is first established, then data is sent, and finally the connection is terminated; it is like a telephone call. In a connectionless service there is no setup cost; each packet is sent independently, like mail. A reliable service guarantees that the data is delivered and in order; the receiver acknowledges each packet with an acknowledgment (ACK). An unreliable service does not give this guarantee. Table 12.8 summarizes the Internet's basic protocols.
| Protocol | Layer | Service | Note |
|---|---|---|---|
| IP (v4/v6) | network | connectionless, unreliable | addressing and routing |
| TCP | transport | connection-oriented, reliable byte stream | acknowledgments, retransmission, flow and congestion control |
| UDP | transport | connectionless, unreliable datagram | has a checksum, no retransmission; DNS, games, audio |
| QUIC | transport (over UDP) | connection-oriented, reliable, encrypted | used by HTTP/3 (2022) |
| DNS | application | name → IP address | hierarchical, distributed, cached |
| HTTP/HTTPS | application | Web documents | HTTPS = HTTP + TLS, port 443 |
| SMTP | application | email transfer | between servers; reading is by IMAP |
| FTP → SFTP | application | file transfer | FTP is unencrypted; SFTP/HTTPS has replaced it |
| SNMP | application | network device monitoring | v3 adds authentication and encryption |
UDP's checksum detects a corrupted packet, but does not correct it or resend it; the corrupted packet is simply dropped. Resending lost or corrupted packets is the job of TCP or the application.
12.8.5Document-based middleware: the Web
On the Web everything is a document. Documents are linked to one another by links and form a giant directed graph. When the user types the address www.example.org/index.html into the browser, this happens (Figure 12.49):
- The browser asks DNS, through the operating system's resolver, for the IP address of
www.example.org. - The reply arrives: 203.0.113.10. The reply is kept in a cache for a while.
- The browser opens a TCP connection to the server's port 443 and performs the TLS handshake. In HTTP/3 these two steps are merged into one by QUIC.
- The browser sends the
GET /index.htmlrequest. - The server returns the HTML file and the browser begins to display the text.
- The images, CSS, and scripts that the HTML refers to are fetched over the same connection; HTTP/2 and HTTP/3 carry them in parallel streams. The connection stays open for a while.
logo.png, style.css, and app.js arrive over the same connection in parallel streams.In old textbooks, connections are made to port 80 and a new TCP connection is opened and closed for every object. This belongs to the HTTP/1.0 era. Today the default is HTTPS (port 443); connections are persistent, and HTTP/2–3 use multiplexing.
12.8.6File-system-based middleware
File-based middleware makes the distributed system look like a file system. The first design question is how the file will be accessed (Figure 12.50). In the upload/download model, the client copies the whole file to itself, reads and writes it locally, and when finished uploads the new version back to the server. This model is simple, but moving an entire large file to read a few bytes of it is expensive. FTP and the old AFS use this model. In the remote access model the file stays on the server. The client sends read and write requests over the network, and only the blocks it wants are moved. NFS and SMB use this model.
The second question is naming. In the simplest solution the file name includes the machine name: machine:/path. This name is not location transparent; if the file is moved to another machine, its name changes. A better solution is to mount the remote file system on a directory of the local tree. If all clients mount the servers at the same place, everyone sees a single, common name space. If clients mount different things, each sees a different view (Figure 12.51). The same path can point to different files on different clients. The most powerful solution is a single name space that is the same on all machines and contains no location of the file at all. This is called location independence. Present-day examples are NFSv4, SMB 3, and object storage systems such as Amazon S3.
/s1, while /s2/D is the same file on both clients.12.8.7The semantics of file sharing
When several clients share the same file, it must be defined when a write becomes visible to others. On a single machine the answer is clear. If process A appends “c” to a file and then B reads, B sees “abc”. Every read sees the most recent write. This is called UNIX semantics, or sequential consistency (Figure 12.52, top).
In a distributed system, clients cache files for performance. Client 1 modifies the file in its cache, but the server does not yet know. Client 2 reads from the server and sees the stale “ab”. The only way to preserve UNIX semantics is not to use a cache and to send every operation to the server; this is very slow. Distributed systems therefore use looser semantics (Table 12.9).
| Approach | Rule | Examples |
|---|---|---|
| UNIX semantics | every write is visible to everyone at once | single machine; remote access without a cache |
| Session semantics | changes become visible when the file is closed | AFS; NFS's close-to-open consistency |
| Immutable files | a file cannot be written, a new one is created | object storage, Git objects |
| Transactions | all or nothing, serializable | databases |
In session semantics, a client's changes are visible only to itself until it closes the file. After the file is closed, clients that open it see the new version. With immutable files the problem never arises, because a file is never modified; a change produces a new file. In transactions, a series of operations is done either entirely or not at all, and concurrent transactions give results as if they had been done in sequence. Each solution sits at a different point between consistency and performance.
12.8.8Object-based middleware: CORBA
In object-based middleware, the distributed system is a collection of objects. A client calls a method of an object on another machine as if it were a local object's. The most comprehensive example of this approach is CORBA, defined by the OMG in 1991 (Figure 12.53).
- IDL (Interface Definition Language): the interfaces of objects are defined in a language independent of the programming language. The IDL compiler generates from this definition the client stub and the skeleton on the server side.
- ORB (Object Request Broker): it finds the object's location, packs the call, and carries it to the other side with the IIOP protocol. The client does not know which machine the object is on; this is called network transparency.
- Static invocation (SII): the client uses stubs generated from IDL at compile time. It is fast, and types are checked at compile time.
- Dynamic invocation (DII): the client discovers the interface it will call from an interface repository at run time and builds the call itself.
SII and DII are two separate mechanisms; SII is not a compiled version of DII. CORBA lives on today mostly in legacy systems. In new systems gRPC with Protocol Buffers, REST, and Java RMI are preferred. But ideas such as generating stubs from IDL, an ORB-like broker, and location-independent object references have passed into these systems.
12.8.9Coordination-based middleware: Linda
In coordination-based middleware, processes do not know one another. Instead of communicating directly, they put data into a common environment and take data from it. The classic example of this approach is Linda, introduced by Gelernter in 1985.
The tuple space is, in Linda, a persistent set of tuples shared by all processes. A tuple is a record made of fields of various types: for example ("abc", 2, 9).
Linda has four basic operations (Figure 12.54):
outputs a tuple into the space and does not block.insearches for a tuple that matches a template, removes it from the space, and assigns its fields to variables. If there is no matching tuple, the caller blocks and waits until a suitable tuple is put in.rdworks likein, but does not remove the tuple from the space; it only reads it.evalstarts a new process; when the process finishes, its result is put into the space as a tuple.
in("abc", 2, ? i); the matching tuple ("abc", 2, 5) was taken from the space and i became 5.Three conditions are required for a template to match a tuple. The numbers of fields must be the same. Corresponding fields must be of the same type. The constant fields in the template must also equal those in the tuple. Fields of the form ? i are formal parameters: they match any value of the right type, and that value is assigned to i. If more than one tuple matches, Linda does not define which will be chosen.
With these simple operations, synchronization comes for free. For example, a semaphore can be implemented with identical tuples put into the space: out("sem") is the V operation and in("sem") the P operation. A work pool is built in a similar way: a manager puts jobs in with out, and workers take them with in.
12.8.10Code trace: Linda in()
The function below is the search part of in() in a simple Linda implementation that keeps the tuple space as a linked list. s is the template; n holds the number of fields, type[k] the type of the k-th field, and fixed[k] whether that field is a constant.
Tuple *in_find(Template *s) {
for (Tuple *d = space; d; d = d->next) {
if (d->n != s->n) continue;
int ok = 1;
for (int k = 0; ok && k < s->n; k++)
if (d->type[k] != s->type[k] ||
(s->fixed[k] && !equal(d, s, k)))
ok = 0; /* field mismatch */
if (ok) { remove(d); return d; }
}
return NULL; /* block */
}The outer loop walks over the tuples in the space in turn. If the number of fields differs, the tuple is skipped at once (continue). Otherwise the inner loop compares the fields one by one. If the type differs, or the field is a constant and its value differs, ok becomes 0 and the inner loop stops. If all fields match, the tuple is removed from the space and returned. If no tuple matches, the function returns NULL; the calling process blocks.
The space holds, in order, d1 = ("abc", 2), d2 = ("xyz", 2, 7), d3 = ("abc", 1, 4), d4 = ("abc", 2, 5), and d5 = ("abc", 2, 9). A process calls in("abc", 2, ? int i) three times.
| Call | Tuple | Check | Result |
|---|---|---|---|
| 1 | d1 | 2 fields ≠ 3 fields | continue |
| 1 | d2 | field 0: "xyz" ≠ "abc" | ok = 0 |
| 1 | d3 | field 0 matches; field 1: 1 ≠ 2 | ok = 0 |
| 1 | d4 | constants equal, field 2 is an integer | d4 is removed, i = 5 |
| 2 | d1, d2, d3 | as above | skipped |
| 2 | d5 | constants equal, field 2 is an integer | d5 is removed, i = 9 |
| 3 | d1, d2, d3 | as above | NULL: the process blocks |
On the first call d5 would have matched too, but d4 comes first in the list, so it was taken. The third call proceeds only when someone puts a matching tuple with out. (The search loop was transcribed one-to-one into Python and run on the same space.)
Looking only at values when matching. The template in("abc", ? int x, 5) does not match the tuple ("abc", 2.0, 5): the type of the second field is floating-point, not integer. The type check comes before the value check.
12.8.11Publish-subscribe and Jini
The most common form of coordination today is the publish-subscribe model (Figure 12.56). A publisher publishes a message to a topic. A subscriber subscribes to the topics it is interested in. The broker in between delivers each message to all subscribers of that topic. The publisher and the subscriber do not know each other's identity; nor do they need to be running at the same time. These two properties are called decoupling in space and in time.
Subscribers and topics can be added and removed at run time; the system is therefore flexible and scalable. The delivery guarantee depends on the broker's configuration: at most once, at least once, or storing messages in a persistent queue. Present-day examples are MQTT for the Internet of Things, Apache Kafka, RabbitMQ, and the queue services of cloud providers.
Jini is a coordination system introduced by Sun in 1998. Java devices that join the network find a lookup service without prior configuration and register the services they offer with it. A client finds a suitable service from the lookup service and uses it through Java RMI. Registrations are made with a lease period. If the lease is not renewed, the registration lapses by itself; this way crashed devices are cleaned out of the service list. Jini was continued under the name Apache River but is not active today. Its ideas live on in service discovery: mDNS/DNS-SD, Consul, and Kubernetes services.
12.8.12The cloud and clusters
A cluster is a set of servers connected by a fast network and under single management; high-performance computing clusters and data centers are examples. The cloud is the offering of these resources over the network, on demand and pay-as-you-go. AWS, Azure, and Google Cloud are the largest cloud providers.
Cloud services are distinguished by how many of the layers the provider manages (Figure 12.57). In an on-premises system, the user manages every layer. In IaaS (Infrastructure as a Service), the provider manages the servers, storage, network, and virtualization; the user manages everything from the operating system up in a virtual machine. In PaaS (Platform as a Service), the user brings only the application and its data. In FaaS (Function as a Service), the user writes only individual functions; the provider runs them on every request. In SaaS (Software as a Service), the user uses a ready-made application and manages no layer.
The infrastructure of the cloud is the topics of this chapter coming together. The physical servers are multicore NUMA machines. On them hypervisors such as KVM or Nitro run virtual machines. On top of the virtual machines or the servers, containers run. Kubernetes schedules these containers (pods) onto nodes, restarts those that crash, and distributes the load; in a sense it is the present-day counterpart of the distributed operating system. The nodes are connected by RDMA-capable networks, workloads are distributed with load balancers, and services communicate through publish-subscribe queues.
12.9Summary
- Parallel systems are built in three organizations: the shared-memory multiprocessor, the message-passing multicomputer, and the wide-area distributed system. Since clock speed has stood still since 2005, the transistor budget goes into the number of cores. According to Amdahl's law, the speedup is 1 / ((1 − p) + p / n) and cannot exceed 1 / (1 − p).
- In UMA machines every memory word is reached in the same time. A single bus saturates with a few CPUs. A crossbar is nonblocking but needs n² crosspoints. An omega network is built from (n/2)·log₂n switches, routes by the bits of the destination address, and is blocking.
- In NUMA, remote access is slower than local; the average access is f · tlocal + (1 − f) · tremote. The operating system keeps data next to the work with first touch, affinity, and automatic NUMA balancing. In CC-NUMA, coherence is maintained with a directory; messages go only to the nodes concerned.
- Cache coherence means writes to the same address are seen in the same order by everyone. In MESI, writing a line in E is silent, writing a line in S requires invalidation, and a line in M is also written to memory when it is given to someone else.
- In false sharing, independent variables sit in the same 64-byte line, so the line bounces between cores. The fix is alignment and padding.
- Multicore chips are made of chiplets, big and little cores, and accelerators. SMT presents one core as several logical CPUs; the gain is 10–30% and it carries a security risk.
- There are three operating system models. A separate operating system per CPU offers no sharing. In master-slave, the master is a bottleneck. In SMP, everyone runs the kernel and shared structures are protected by fine-grained locks.
- On a multiprocessor, TSL must lock the bus or the line for the duration of the read and the write. The ticket lock is fair; TTAS makes waiters spin on a local copy; MCS gives each waiter its own flag. If the expected wait is shorter than 2C, spinning is cheaper, and if longer, sleeping is; spinning for 2C and then sleeping gives twice the cost in the worst case.
- A shared ready queue balances load but suffers from a single lock and cold caches; today's systems use per-CPU queues and load balancing. Space sharing allots CPUs to a job until it finishes. In gang scheduling, interdependent threads run in the same slice on different CPUs.
- In a multicomputer, messages can be copied five times; RDMA removes the copies. The diameters of the topologies are n / 2 for a ring, 2(k − 1) for a k × k grid, and log₂n for a hypercube. E-cube routing corrects the differing bits from left to right. Cut-through removes the latency of store-and-forward, which grows with the number of hops.
- Send can be blocking or nonblocking. RPC makes a remote call look like a local one with stubs; pointers and partial failures cause difficulties. DSM creates the illusion of shared memory with page faults. Process assignment is a graph partitioning problem; distributed load balancing can be sender-initiated or receiver-initiated.
- Hypervisors are divided into type 1 (bare metal) and type 2 (on a host). x86, which did not satisfy the Popek–Goldberg condition, was virtualized first with binary translation and then with VT-x/AMD-V. Paravirtualization uses hypercalls. EPT removes the VM exits of shadow tables, but a TLB miss rises to (n + 1)(m + 1) − 1 accesses. Containers share a single kernel.
- In a distributed system, middleware offers a document (Web), file (NFS, SMB), object (CORBA, gRPC), or coordination (Linda, publish-subscribe) model. In file sharing, UNIX semantics is expensive; session semantics, immutable files, and transactions are tradeoffs. The cloud offers all these layers as a service.
12.10Key terms
- Amdahl's law
- symmetric multiprocessor (SMP)
- uniform / non-uniform memory access (UMA / NUMA)
- crossbar switch
- omega network
- cache coherence
- snooping / directory
- MESI protocol
- false sharing
- multicore
- simultaneous multithreading (SMT)
- master-slave model
- spinlock
- ticket lock
- processor affinity
- load balancing
- space sharing
- gang scheduling
- multicomputer
- hypercube
- message passing
- remote procedure call (RPC)
- distributed shared memory
- hypervisor
- paravirtualization
- virtual machine
- container
- middleware
- tuple space
- publish-subscribe
12.11Test Yourself
90% of a program can be parallelized. What is the speedup on 16 cores, and what is the efficiency per core (speedup / n)? What is the upper limit of the speedup?
Answer
S(16) = 1 / (0.1 + 0.9 / 16) = 1 / (0.1 + 0.05625) = 1 / 0.15625 = 6.4. The efficiency is 6.4 / 16 = 0.4: only 40% of the cores' power is used. The upper limit is 1 / 0.1 = 10.
In an 8 × 8 omega network, CPU 110 accesses memory 001. Through which switches, and by which outputs, does the request pass? If CPU 000 wants to read memory 000 at the same time, is there a conflict?
Answer
110 comes by the shuffle to input 101, that is, to 1C. Since the bits of the destination 001 are 0, 0, 1, the path is 1C (upper) → 2A (upper) → 3A (lower). The request from CPU 000 follows the path 1A (upper) → 2A (upper) → 3A (upper). Both requests use the upper output of 2A; one waits. A conflict has occurred inside the network even though the destination modules are different.
In a NUMA machine, local access takes 90 ns and remote access 150 ns. If 80% of accesses are local, what is the average time? What must the local access ratio be at least so that the average does not exceed 100 ns?
Answer
0.8 · 90 + 0.2 · 150 = 72 + 30 = 102 ns. From the condition 90f + 150(1 − f) ≤ 100 we get 150 − 60f ≤ 100, that is, f ≥ 50 / 60 ≈ 0.833. At least about 83.3% of accesses must be local.
In a directory-based system with 256 nodes, 16 MiB per node, and 64-byte lines, which node's memory holds the line of address 0x5A0003C4? What are the block number and the offset?
Answer
The leftmost 8 bits are 0x5A = 90: the line is at node 90. The remaining 24 bits are 0x0003C4 = 964. Since 964 = 15 · 64 + 4, the block is 15 and the offset is 4. The request goes to node 90, and entry 15 of its directory is consulted.
In a three-core MESI system, x is initially only in memory and is 0. In turn, C0 reads x, C0 writes x = 5, C1 reads, C2 reads, C1 writes x = 6. At the end, what are the states of the line, how many bus operations have occurred, and what value is in memory?
Answer
C0 reads: E (BusRd). C0 writes: E → M, silent. C1 reads: BusRd; C0 supplies the data and writes it to memory, and both are S. C2 reads: BusRd, all three S. C1 writes: BusUpgr; C0 and C2 become I, C1 becomes M. The final states are I, M, I. Four bus operations occur. Memory holds 5; the current value 6 is only in C1.
The context switch cost is C = 2 µs. If the expected wait for a lock is 3 µs, and if it is 6 µs, which is cheaper: spinning or sleeping?
Answer
The cost of switching is 2C = 4 µs. Since 3 µs < 4 µs, spinning is cheaper in the first case. Since 6 µs > 4 µs, sleeping is cheaper in the second. If the wait time is not known, spinning for 4 µs and then sleeping gives, in the worst case, twice the ideal cost.
On a system with 4 CPUs, four jobs are to run with gang scheduling: A has 3 threads, B 2, C 2, and D 1. What is the minimum number of slices in a round, and what is the CPU utilization?
Answer
There are 8 threads in total and 4 CPUs per slice; at least ⌈8 / 4⌉ = 2 slices are needed. Placement: in slice 0 A (3) and D (1), in slice 1 B (2) and C (2). Since every slice is full, utilization is 100%.
Through which nodes does a message going from 0101 to 1010 pass with e-cube routing in a 4-dimensional hypercube? Why is this path the shortest?
Answer
0101 ⊕ 1010 = 1111; all four bits differ. The bits are corrected from left to right: 1101 → 1001 → 1011 → 1010. Each hop corrects a single differing bit and no hop increases the difference; so the number of hops equals the Hamming distance, that is, 4. This is the diameter of the 4-dimensional hypercube.
A 1 KiB packet goes over 4 switches, that is, 5 links. The links are 1 Gb/s and each switch processes the header in 0.1 µs. What are the latencies of store-and-forward and cut-through?
Answer
Crossing one link takes 1024 × 8 / 109 s = 8.192 µs. In store-and-forward the whole packet is waited for on each link: 5 × 8.192 + 4 × 0.1 = 40.96 + 0.4 = 41.36 µs. In cut-through the packet flows once and only the header delays are added: 8.192 + 4 × 0.1 ≈ 8.59 µs.
A 32-bit guest operating system uses 2-level page tables; the host's EPT has 4 levels. On a TLB miss, with no entry in the cache, how many memory accesses are needed in the worst case (excluding the final data access)?
Answer
For each level of the guest table, the GPA of the entry is translated with 4 EPT accesses and the entry is read with 1 access: 2 × 5 = 10. The GPA of the data is also translated with 4 accesses. Total 10 + 4 = 14 = (2 + 1)(4 + 1) − 1.
12.12Further reading
- A. S. Tanenbaum and H. Bos, Modern Operating Systems, Chapter 8 “Multiple Processor Systems” and Chapter 7 “Virtualization and the Cloud”. The book is the original source of the omega network, directory, gang scheduling, and load-balancing examples in these notes.
- R. H. Arpaci-Dusseau and A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, the chapters “Multiprocessor Scheduling”, “Locks”, and “Distributed Systems”: a short and clear treatment of cache affinity, lock implementations, and RPC; the book is free at ostep.org.
- J. L. Hennessy and D. A. Patterson, Computer Architecture: A Quantitative Approach, Chapter 5: examines snooping and directory-based coherence protocols, memory consistency models, and synchronization instructions in detail from the hardware side.
- J. M. Mellor-Crummey and M. L. Scott, “Algorithms for Scalable Synchronization on Shared-Memory Multiprocessors”, ACM TOCS, 1991: the classic paper that compares ticket and MCS locks with measurements.
12.13References
- A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th ed. (2014) / 5th ed. (2023), Pearson — Chapter 8: Multiple Processor Systems; Chapter 7: Virtualization and the Cloud.
- A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018 — Section 5.5 (Multi-Processor Scheduling), Chapter 18 (Virtual Machines), Chapter 19 (Networks and Distributed Systems).
- R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), ostep.org — “Multiprocessor Scheduling”, “Locks”, “Distributed Systems”, “Sun's NFS”, “AFS”, appendix: “Virtual Machine Monitors”.
- J. L. Hennessy, D. A. Patterson, Computer Architecture: A Quantitative Approach, 6th ed., Morgan Kaufmann, 2017 — Chapter 5: Thread-Level Parallelism (coherence, MESI, directory protocols).
- J. M. Mellor-Crummey, M. L. Scott, “Algorithms for Scalable Synchronization on Shared-Memory Multiprocessors”, ACM TOCS, 1991; A. D. Birrell, B. J. Nelson, “Implementing Remote Procedure Calls”, ACM TOCS, 1984; G. J. Popek, R. P. Goldberg, “Formal Requirements for Virtualizable Third Generation Architectures”, CACM, 1974.
- Linux kernel documentation: “CFS/EEVDF Scheduler”, “Scheduler Domains”, “NUMA Memory Policy”, “Core Scheduling”; Intel 64 and IA-32 Architectures Software Developer's Manual, Volume 3 (VMX, EPT).
Related pages: Chapter 12 slides · © Sercan Külcü. All rights reserved.