---
title: "Virtual Machines and Containers"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 14
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/14-virtual-machines-and-containers
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 14 — Virtual Machines and Containers

A data centre rents out machines that do not exist: one physical server runs dozens of operating systems, each convinced that it owns the processor, the memory and the devices. The kernel of the Year 2 volume already gave processes that illusion; this chapter gives it to whole kernels. A monitor written in Python runs a small [guest](#def-b3-virtualisation-vm) kernel on the `rv` machine, intercepts every instruction the [guest](#def-b3-virtualisation-vm) may not run itself, and emulates its devices; the cost of each interception is counted, and the theorem that says when the trick works is stated. Then the hardware’s help is drawn, address translation done twice, and finally [containers](#def-b3-virtualisation-container), which isolate processes without a second kernel, and the price of each kind of isolation.

**You already know.**

[Chapter 10](https://one-course.com/books/computer-science/5/en/chapter/10-the-kernel-and-cpu-scheduling#ch-b3-kernel-and-scheduling) showed how a trap moves the processor from user mode to the kernel at a fixed entry point, saving the interrupted program counter, and how the kernel returns. [Chapter 11](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#ch-b3-virtual-memory) translated virtual addresses through [page tables](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-paging) of several levels, one memory reference per level, and cached the results in a [TLB](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-tlb). In the Year 2 volume a program asks the kernel for a service with a system call, made on RISC-V by the instruction `ecall`.

## 14.1 What a virtual machine is

**Definition 14.1 (System virtual machine, hypervisor, type-1 and type-2 hypervisor, guest, host).**

A *system virtual machine* is an efficient, isolated duplicate of a real machine, on which an unmodified operating system can run. The software that creates it is a *hypervisor*, or virtual machine monitor. A *type-1 hypervisor* runs on the bare hardware; a *type-2 hypervisor* runs as an application of an ordinary operating system, the *host*. The operating system that runs inside a virtual machine is a *guest*.

“Efficient” is part of the definition. Robert Goldberg’s definition, which John Scott Robin and Cynthia Irvine quote, asks that a statistically dominant subset of the virtual processor’s instructions run on the [host](#def-b3-virtualisation-vm) processor directly; a program that interprets every instruction, as the `rv` machine does, is an emulator, not a virtual machine. The same distinction separates the two types: a [type-1 hypervisor](#def-b3-virtualisation-vm) is itself an operating system with the means to virtualise, and a type-2 one relies on a [host](#def-b3-virtualisation-vm) for everything else.

![The two types of hypervisor, as stacks of software. Each layer sees the one below as its machine.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-virtualisation/fig-ddc8150d3176.svg)

*The two types of [hypervisor](#def-b3-virtualisation-vm), as stacks of software. Each layer sees the one below as its machine.*

## 14.2 Trap and emulate

The [guest](#def-b3-virtualisation-vm) kernel believes it runs in supervisor mode. The [hypervisor](#def-b3-virtualisation-vm) runs it in user mode instead, so that the instructions only a kernel may execute leave the [guest](#def-b3-virtualisation-vm) and come to the [hypervisor](#def-b3-virtualisation-vm).

**Definition 14.2 (Sensitive instruction, privileged instruction, trap and emulate).**

A *sensitive instruction* is one whose effect depends on, or changes, the state of the machine that the [hypervisor](#def-b3-virtualisation-vm) must keep for itself: the privilege mode, the translation of addresses, the devices, the clocks. A *privileged instruction* traps when executed outside the most privileged mode. *Trap and emulate* runs the [guest](#def-b3-virtualisation-vm) in a less privileged mode, directly on the processor, lets every privileged instruction trap to the [hypervisor](#def-b3-virtualisation-vm), and has the [hypervisor](#def-b3-virtualisation-vm) perform its effect on the [guest](#def-b3-virtualisation-vm)’s virtual state before resuming the [guest](#def-b3-virtualisation-vm) after it.

**Theorem 14.3 (Popek–Goldberg theorem).**

If every [sensitive instruction](#def-b3-virtualisation-sensitive) of a machine is privileged, a [hypervisor](#def-b3-virtualisation-vm) for that machine can be built by [trap and emulate](#def-b3-virtualisation-sensitive): the [guest](#def-b3-virtualisation-vm) runs directly except for its [sensitive instructions](#def-b3-virtualisation-sensitive), each of which traps and is emulated.

**Proof idea.** Run the [guest](#def-b3-virtualisation-vm) in user mode, and keep for it a virtual copy of every register and device that [sensitive instructions](#def-b3-virtualisation-sensitive) read or write. An instruction that is not sensitive behaves the same whatever that state is, so running it directly gives the same result as on a real machine in the [guest](#def-b3-virtualisation-vm)’s state. A [sensitive instruction](#def-b3-virtualisation-sensitive) is privileged, so it traps; the [hypervisor](#def-b3-virtualisation-vm) applies its effect to the virtual copy, which is what the real machine would have done, and resumes the [guest](#def-b3-virtualisation-vm). By induction on the steps, the [guest](#def-b3-virtualisation-vm)’s state stays what it would be on a real machine of its own. Gerald Popek and Robert Goldberg made this precise in 1974, with a formal model of the machine and its states (exercise [14.10](#exo-b3-virtualisation-10) proves it for a small model). ∎

RISC-V follows the rule for its control and status registers, the CSRs: bits 9 and 8 of a CSR’s number give the lowest privilege level that may access it, and an access without enough privilege raises an illegal-instruction exception. The [guest](#def-b3-virtualisation-vm) of [Listing 14.1](#lst-b3-virtualisation-guest) drives three devices and reads a clock through CSRs numbered from `0x5c0`, in a range the specification reserves for custom supervisor-level registers. The `rv` machine has no CSR instructions at all, so the [guest](#def-b3-virtualisation-vm) writes them as raw words: for `rv`, as for user mode, they are illegal.

```text
# guest.S -- a tiny guest kernel. It drives three devices through control registers (CSRs):
# a console at 0x5c0, a number display at 0x5c3 and a power switch at 0x5c1, and reads a
# clock at 0x5c2. This machine has no CSR instructions, so they are written as raw words.
# capture: exit
        .data
msg:    .asciz "hello from the guest\n"
        .text
main:
        la    t0, msg
print:  lbu   a0, 0(t0)
        beqz  a0, sum
        .word 0x5c051073        # csrw 0x5c0, a0: send one character to the console
        addi  t0, t0, 1
        j     print
sum:    li    a0, 0             # some ordinary work: 1 + 2 + ... + 100
        li    t1, 100
add:    add   a0, a0, t1
        addi  t1, t1, -1
        bnez  t1, add
        .word 0x5c351073        # csrw 0x5c3, a0: show the sum
        .word 0x5c202573        # csrr a0, 0x5c2: read the clock
        .word 0x5c351073        # csrw 0x5c3, a0: show it
        li    a0, 0
        .word 0x5c151073        # csrw 0x5c1, a0: power off, status 0
```

***Listing 14.1.** A [guest](#def-b3-virtualisation-vm) kernel: a message to the console, some work, the clock, then power off. code/bachelor-3/14-virtualisation/listings/guest.S*

```
$ python -m rv run guest.S
rv: line 12: .word 0x5c051073: illegal instruction 0x5c051073
[exit status 1]
```

***Output 14.1.** On the bare machine, the [guest](#def-b3-virtualisation-vm)’s first device access stops it.*

The monitor of [Listing 14.2](#lst-b3-virtualisation-monitor) catches these traps with `rv`’s `on_trap` hook, which is called with the program counter still at the trapping instruction. It decodes the CSR instruction from the [guest](#def-b3-virtualisation-vm)’s memory, emulates it on the virtual devices, and steps over it.

```python
class Monitor:
    def __init__(self, source):
        self.m = Machine(source)
        self.m.on_trap = self.trap  # every illegal word, ecall and ebreak comes here
        self.console = []

    def read_csr(self, csr):
        if csr == CLOCK:
            return self.m.steps  # virtual time: the guest's instructions so far
        if csr in (CONSOLE, POWER, NUMBER):
            return 0
        raise RVFault(f"no device at CSR 0x{csr:03x}")

    def write_csr(self, csr, value):
        if csr == CONSOLE:
            self.console.append(chr(value & 0xFF))
        elif csr == NUMBER:
            self.console.append(f"{value}\n")
        elif csr == POWER:
            self.m.halt(value & 0xFF)
        elif csr != CLOCK:
            raise RVFault(f"no device at CSR 0x{csr:03x}")

    def trap(self, m, cause):
        word = m.load(m.pc, 4)  # the trapping instruction, fetched from the guest
        if cause != "illegal" or word & 0x7F != 0x73:  # not a CSR instruction
            raise RVFault(f"guest {cause} at 0x{m.pc:08x}: not emulated")
        funct3, rd, rs1 = word >> 12 & 7, word >> 7 & 31, word >> 15 & 31
        csr = word >> 20
        old = self.read_csr(csr)
        if funct3 == 1:  # csrrw: write rs1, old value to rd
            self.write_csr(csr, m.x[rs1])
        elif funct3 == 2 and rs1:  # csrrs: set rs1's bits (csrr has rs1 = x0)
            self.write_csr(csr, old | m.x[rs1])
        elif funct3 != 2:
            raise RVFault(f"CSR instruction 0x{word:08x} not emulated")
        if rd:
            m.set_reg(rd, old)
        m.pc += 4  # resume after the emulated instruction
```

***Listing 14.2.** The monitor. The virtual clock counts the [guest](#def-b3-virtualisation-vm)’s instructions; the console collects what the [guest](#def-b3-virtualisation-vm) prints. code/bachelor-3/14-virtualisation/listings/monitor.py*

![One trap. The guest never knows that the console is a Python list.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-virtualisation/fig-fe80a1ae7ef2.svg)

*One trap. The [guest](#def-b3-virtualisation-vm) never knows that the console is a Python list.*

```python
"""run_guest.py -- the guest of guest.S under the monitor: what its devices showed, and
how often it trapped."""
from monitor import Monitor

vm = Monitor(open("guest.S").read())
console, status = vm.run()
print(console, end="")
print(f"powered off with status {status}")
m = vm.m
print(f"{m.steps} guest instructions, {m.traps} traps: one trap every "
      f"{m.steps / m.traps:.1f} instructions")
```

***Listing 14.3.** The [guest](#def-b3-virtualisation-vm) under the monitor. code/bachelor-3/14-virtualisation/listings/run_guest.py*

```
$ python run_guest.py
hello from the guest
5050
413
powered off with status 0
416 guest instructions, 25 traps: one trap every 16.6 instructions
```

***Output 14.2.** The [guest](#def-b3-virtualisation-vm) prints, computes 5,050, reads 413 on its clock and powers off: 25 of its 416 instructions trapped.*

How much does a trap cost? [Listing 14.4](#lst-b3-virtualisation-cost) counts it, using as its clock the number of Python lines that the machine and the monitor execute, which, unlike a time on a busy laptop, does not jitter.

```python
CLOCK_READ = ".word 0x5c2022f3"  # csrr t0, 0x5c2: traps to the monitor
PLAIN = "addi t0, t0, 1"
INSTRUCTIONS = 30_000


def guest(body, first):  # the loop's own add and branch count in its B instructions
    work = ["addi t1, t1, 1"] * (body - 3)
    return "\n".join([f"main: li t2, {INSTRUCTIONS // body}", "loop:", first, *work,
                      "addi t2, t2, -1", "bnez t2, loop", "li a0, 0", "ret"])


def cost(m):  # Python lines executed per guest instruction
    lines = 0

    def tracer(frame, event, arg):
        nonlocal lines
        lines += event == "line"
        return tracer

    sys.settrace(tracer)
    m.run(10 * INSTRUCTIONS)
    sys.settrace(None)
    return lines / m.steps


plain = cost(Machine(guest(3, PLAIN)))
T = cost(Monitor(guest(3, CLOCK_READ)).m) * 3 / plain - 2  # a trap, in plain ones
print(f"a plain instruction: {plain:.1f} lines; a trap: T = {T:.1f} plain instructions")
print("trap fraction f   counted slowdown   1 + f(T - 1)")
for body in (10, 30, 100, 300, 1000):
    slow = cost(Monitor(guest(body, CLOCK_READ)).m) / cost(Machine(guest(body, PLAIN)))
    print(f"{1 / body:>15.4f}   {slow:>16.4f}   {1 + (T - 1) / body:>12.4f}")
```

***Listing 14.4.** The same loop with a trapping clock read, or an ordinary `addi`, once every $B$ instructions. code/bachelor-3/14-virtualisation/listings/trap_cost.py*

```
$ python trap_cost.py
a plain instruction: 64.7 lines; a trap: T = 1.2 plain instructions
trap fraction f   counted slowdown   1 + f(T - 1)
         0.1000             1.0167         1.0155
         0.0333             1.0057         1.0052
         0.0100             1.0017         1.0015
         0.0033             1.0006         1.0005
         0.0010             1.0002         1.0002
```

***Output 14.3.** A trap costs about as much as one instruction here, and the slowdown follows $1 + f(T - 1)$ to within about one part in a thousand.*

A trap replaces one ordinary instruction by one costing $T$, so a fraction $f$ of traps multiplies the time by $1 + f(T - 1)$. Here $T$ is barely more than 1, because `rv` interprets every instruction anyway: an emulator pays its large cost everywhere, and a trap adds little to it. A [hypervisor](#def-b3-virtualisation-vm) on real hardware is the opposite. Its [guest](#def-b3-virtualisation-vm) runs at the processor’s own speed, and only a trap leaves it, through the hardware’s exception entry, the [hypervisor](#def-b3-virtualisation-vm)’s decoding and emulation, and the return: $T$ is then a large number of instructions, and the fraction $f$ decides everything (the weekend problem computes it).

## 14.3 Hardware support

The theorem’s condition is not automatic. Robin and Irvine examined every instruction of the Intel Pentium in 2000 and found seventeen that are sensitive but not privileged, among them `SGDT`, `SIDT`, `SLDT` and `SMSW`, which read registers describing the processor’s own protection tables: run in user mode, they do not trap, and return the [host](#def-b3-virtualisation-vm)’s values to the [guest](#def-b3-virtualisation-vm). By the theorem’s standard the processor was not virtualisable.

Three answers appeared.

**Definition 14.4 (Binary translation, paravirtualisation, nested paging).**

*Binary translation* rewrites the [guest](#def-b3-virtualisation-vm)’s code before it runs, replacing each [sensitive instruction](#def-b3-virtualisation-sensitive) by a call to the [hypervisor](#def-b3-virtualisation-vm) and leaving the others to run directly. *Paravirtualisation* modifies the [guest](#def-b3-virtualisation-vm)’s source so that it calls the [hypervisor](#def-b3-virtualisation-vm) explicitly, with hypercalls, instead of executing [sensitive instructions](#def-b3-virtualisation-sensitive). Hardware virtualisation adds a processor mode for [guests](#def-b3-virtualisation-vm) in which [sensitive instructions](#def-b3-virtualisation-sensitive) trap; *nested paging* adds a second stage of hardware address translation, from the [guest](#def-b3-virtualisation-vm)’s physical addresses to the [host](#def-b3-virtualisation-vm)’s.

RISC-V’s [hypervisor](#def-b3-virtualisation-vm) extension is of the third kind: it [hosts](#def-b3-virtualisation-vm) [guest](#def-b3-virtualisation-vm) operating systems under a type-1 or a [type-2 hypervisor](#def-b3-virtualisation-vm), and translates in two stages, the [guest](#def-b3-virtualisation-vm)’s own tables taking a [virtual address](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space) to a [guest](#def-b3-virtualisation-vm) [physical address](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space), and the [hypervisor](#def-b3-virtualisation-vm)’s tables that address to a real one. Every [guest](#def-b3-virtualisation-vm) [physical address](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space) goes through the second stage, including the addresses of the [guest](#def-b3-virtualisation-vm)’s [page-table entries](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-paging) themselves. A walk therefore nests one walk inside another ([Listing 14.5](#lst-b3-virtualisation-walk)).

```python
    return [f"host L{level}" for level in range(h)]


def two_stage(k, h):
    refs = []
    for level in range(k):  # each guest entry lives at a guest physical address
        refs += host_walk(h) + [f"guest L{level}"]
    return refs + host_walk(h) + ["data"]  # and so does the data

```

***Listing 14.5.** The references of a two-stage walk: before each [guest](#def-b3-virtualisation-vm) level, a whole [host](#def-b3-virtualisation-vm) walk. code/bachelor-3/14-virtualisation/listings/nested_walk.py*

```
$ python nested_walk.py
guest levels k  host levels h  references before the data  k*h + k + h
             1              1                           3            3
             2              2                           8            8
             2              3                          11           11
             3              3                          15           15
             4              4                          24           24
             5              5                          35           35
k = h = 2: host L0, host L1, guest L0, host L0, host L1, guest L1, host L0, host L1, data
```

***Output 14.4.** The memory references before the data can be read. With four levels on each side, 24 instead of 4.*

![A two-stage walk with two levels on each side, as in the last line of . With k levels on both sides it costs (k + 1)2 - 1 references.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-virtualisation/fig-ced3ef979090.svg)

*A two-stage walk with two levels on each side, as in the last line of [Output 14.4](#out-b3-virtualisation-walk). With $k$ levels on both sides it costs $(k + 1)^2 - 1$ references.*

With $k$ [guest](#def-b3-virtualisation-vm) levels and $h$ [host](#def-b3-virtualisation-vm) levels, each of the $k$ [guest](#def-b3-virtualisation-vm) entries costs a [host](#def-b3-virtualisation-vm) walk of $h$ references and its own read, and the data’s address one more [host](#def-b3-virtualisation-vm) walk: $k(h + 1) + h = kh + k + h$, and $(k + 1)^2 - 1$ when $h = k$. A [TLB](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-tlb) hit skips all of it, which is why a miss under virtualisation is so much dearer than without.

## 14.4 Containers

A virtual machine runs a whole kernel per [guest](#def-b3-virtualisation-vm). Often the [guests](#def-b3-virtualisation-vm) would all run the same kernel anyway, and what they need is only to be kept apart.

**Definition 14.5 (Container, kernel namespace, control group, resource limit).**

A *kernel namespace* wraps a global resource of the kernel so that the processes inside it see their own isolated instance of it. A *control group* is a set of processes, arranged in a hierarchy, among which the kernel divides resources such as memory and processor time, within limits set for the group. A *resource limit* caps what one process may use of a resource. A *container* is a group of processes that share the [host](#def-b3-virtualisation-vm)’s kernel but are placed in their own namespaces and control group, so that they see a machine of their own and use a bounded share of it.

Linux has eight kinds of namespace, and each isolates one thing: the mount points, the process IDs, the network devices and ports, the user and group IDs, the [host](#def-b3-virtualisation-vm) name, the inter-process communication objects, the root of the [control groups](#def-b3-virtualisation-container), and the boot and monotonic clocks. Its manual page names [containers](#def-b3-virtualisation-container) as one use of them.

A [control group](#def-b3-virtualisation-container)’s `memory.max` is a hard limit on its memory: when its use reaches it and cannot be reduced, the kernel’s out-of-memory killer acts inside the group. A process can also limit itself: POSIX’s `RLIMIT_AS` caps the total memory of a process, beyond which `malloc` and `mmap` fail with `ENOMEM` ([Listing 14.6](#lst-b3-virtualisation-rlimit)).

```c
int main(void) {
    pid_t pid = fork();
    if (pid == 0) {                                      /* the child */
        struct rlimit cap = {64 * MIB, 64 * MIB};       /* soft and hard limit */
        setrlimit(RLIMIT_AS, &cap);
        int blocks = 0;
        for (;;) {
            char *p = malloc(16 * MIB);
            if (p == NULL) break;                        /* refused: the limit is reached */
            memset(p, 1, 16 * MIB);                      /* really use the memory */
            blocks++;
        }
        printf("child: %d blocks of 16 MiB, then malloc returned NULL\n", blocks);
        exit(blocks > 0 ? 0 : 1);
    }
    int status;
    waitpid(pid, &status, 0);
    printf("parent: the child exited with status %d; the parent is unaffected\n",
           WEXITSTATUS(status));
    char *q = malloc(256 * MIB);                          /* no limit here */
    printf("parent: 256 MiB %s\n", q != NULL ? "allocated" : "refused");
    free(q);
    return 0;
}
```

***Listing 14.6.** A child that limits itself to 64 MiB of [address space](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space). code/bachelor-3/14-virtualisation/listings/rlimit.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o rlimit rlimit.c -lm && ./rlimit
child: 3 blocks of 16 MiB, then malloc returned NULL
parent: the child exited with status 0; the parent is unaffected
parent: 256 MiB allocated
```

***Output 14.5.** Three blocks of 16 MiB fit, not four: the program’s code, libraries and stack already use part of the 64 MiB. The child sees the refusal as a `NULL`, and nobody else is affected.*

The old `chroot` call, which changes the directory a process sees as `/`, is sometimes described as a [container](#def-b3-virtualisation-container). Its manual page says otherwise: it changes one step of resolving a path and does nothing else, and it is not intended for any security purpose.

## 14.5 What each one isolates

**Definition 14.6 (Isolation boundary).**

An *isolation boundary* is the interface through which isolated code can reach what lies outside it; an attacker inside must find a flaw in the code behind that interface to cross it.

| isolation | boundary | shared with the neighbours | cost |
| --- | --- | --- | --- |
| process | system calls, [page tables](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-paging) | the kernel, the file system | almost none |
| [container](#def-b3-virtualisation-container) | system calls, filtered by namespaces and limits | the kernel | almost none; the same kernel for all |
| virtual machine | the trapping instructions and the virtual devices | the [hypervisor](#def-b3-virtualisation-vm), the hardware | a kernel per [guest](#def-b3-virtualisation-vm), traps, two-stage walks |
| language sandbox | the language’s operations and its library | the interpreter’s process | checks on every operation |

***Table 14.1.** Four isolation boundaries. The narrower the interface behind the boundary, the less code an attacker can attack: a [hypervisor](#def-b3-virtualisation-vm)’s interface is a few instructions and devices, a kernel’s hundreds of system calls.*

A [container](#def-b3-virtualisation-container)’s boundary is the whole system-call interface of the shared kernel, so a flaw in the kernel is a flaw in every [container](#def-b3-virtualisation-container); a virtual machine’s boundary is much narrower. A [host](#def-b3-virtualisation-vm) that must run strangers’ code side by side therefore has reason to prefer the narrower boundary, or to narrow a [container](#def-b3-virtualisation-container)’s by filtering the system calls it may make. The table does not rank them: each boundary is chosen for what it isolates and what it costs.

**History — Virtualisation.**

Popek and Goldberg’s *Formal requirements for virtualizable third generation architectures* appeared in the Communications of the ACM in July 1974, and Robin and Irvine’s analysis of the Pentium at the USENIX Security Symposium in August 2000.

## 14.6 Exercises

**Exercise 14.1 ★.**

By the CSR numbering rule, which of these RISC-V instructions trap when a [guest](#def-b3-virtualisation-vm) kernel runs in user mode: a write to `satp` (CSR `0x180`), a read of `time` (`0xC01`), a write to `sstatus` (`0x100`), `add`, a load from the [guest](#def-b3-virtualisation-vm)’s own memory? Which of them are sensitive? Is any sensitive and not privileged?

**Solution of Exercise 14.1.**

`0x180` and `0x100` have bits 9 and 8 equal to 01: supervisor-level, so writing `satp` or `sstatus` from user mode traps. `0xC01` has bits 9 and 8 equal to 00: user-level (and bits 11 and 10 equal to 11, read-only), so reading `time` does not trap by this rule. `add` and a load from the [guest](#def-b3-virtualisation-vm)’s own memory do not trap. The three CSR accesses are sensitive: the translation register, the processor’s status and a clock are state the [hypervisor](#def-b3-virtualisation-vm) must control. Reading `time` is therefore sensitive but, by the numbering rule alone, not privileged: the [guest](#def-b3-virtualisation-vm) would read the real clock.

**Exercise 14.2 ★.**

Which type of [hypervisor](#def-b3-virtualisation-vm) is each: (a) a program a developer starts on a laptop’s usual operating system to try another system in a window; (b) the only software below a server’s [guests](#def-b3-virtualisation-vm), which schedules them and drives the hardware?

**Solution of Exercise 14.2.**

(a) Type 2: it runs as an application of the [host](#def-b3-virtualisation-vm) operating system. (b) Type 1: it runs on the bare hardware and is itself the operating system that schedules the [guests](#def-b3-virtualisation-vm).

**Exercise 14.3 ★.**

How many memory references does a two-stage walk make before the data with two-level tables on both sides? With two-level [guest](#def-b3-virtualisation-vm) tables and four-level [host](#def-b3-virtualisation-vm) tables?

**Solution of Exercise 14.3.**

$kh + k + h$: $2 \times 2 + 2 + 2 = 8$, as in the last line of [Output 14.4](#out-b3-virtualisation-walk); with $k = 2$ and $h = 4$, $8 + 2 + 4 = 14$.

**Exercise 14.4 ★.**

Predict the number of traps in [Output 14.2](#out-b3-virtualisation-run) from [Listing 14.1](#lst-b3-virtualisation-guest), without running it.

**Solution of Exercise 14.4.**

One trap per character of `"hello from the guest\n"`, 21 characters, then four more: show the sum, read the clock, show it, power off. $21 + 4 = 25$ (`test_guest_under_the_monitor_and_exercise_4`).

**Exercise 14.5 ★★.**

`exercises/ex5_stuck.py` emulates each instruction but leaves the [guest](#def-b3-virtualisation-vm)’s `pc` where it was. What does the [guest](#def-b3-virtualisation-vm) do, what does the console contain, and how does the run end? Fix it.

**Solution of Exercise 14.5.**

The [guest](#def-b3-virtualisation-vm) executes its first device write again and again: each time the monitor emulates it, appends `h` to the console, and resumes at the same instruction. The console fills with `h`, one per trap, and the run ends only when the step limit stops it, with `StepLimit` (`test_exercise_5_stuck_monitor_loops`). The fix is the monitor’s last line, `m.pc += 4`: an emulated instruction must be stepped over, as the processor would have done.

**Exercise 14.6 ★★.**

Write a virtual timer for the monitor: the [guest](#def-b3-virtualisation-vm) writes the address of a handler to CSR `0x5c5` and a time to CSR `0x5c4`; when the virtual clock reaches that time, the monitor saves the [guest](#def-b3-virtualisation-vm)’s `pc` in CSR `0x5c6` and jumps to the handler, once. The test runs a [guest](#def-b3-virtualisation-vm) that counts in a loop until the timer stops it.

**Solution of Exercise 14.6.**

`exercises/ex6_timer.py`: the three CSRs are kept in a dictionary that `read_csr` and `write_csr` consult first, and `run` steps the [guest](#def-b3-virtualisation-vm) itself, checking before each step whether the virtual clock has reached the compare value; if so it saves `m.pc` in the third CSR, sets `m.pc` to the handler, and clears the compare value. The test’s [guest](#def-b3-virtualisation-vm) spends 6 instructions setting up (`la` is two), then 2 per round of its loop, so the counter is 22 when the timer fires at instruction 50, and the saved `pc` is inside the loop (`test_exercise_6_timer_fires_once`).

**Exercise 14.7 ★★.**

Prove that a two-stage walk with $k$ [guest](#def-b3-virtualisation-vm) levels and $h$ [host](#def-b3-virtualisation-vm) levels makes $kh + k + h$ references before the data, and that this is $(k + 1)^2 - 1$ when $h = k$.

**Solution of Exercise 14.7.**

Facts used: every [guest](#def-b3-virtualisation-vm) [physical address](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space) must be translated by the [host](#def-b3-virtualisation-vm)’s walk, $h$ references, before it can be read; the [guest](#def-b3-virtualisation-vm)’s walk reads one entry per level, $k$ entries, each at a [guest](#def-b3-virtualisation-vm) [physical address](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space); the data’s address is a [guest](#def-b3-virtualisation-vm) [physical address](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space) too.

For each of the $k$ [guest](#def-b3-virtualisation-vm) levels, $h$ references to find where the entry is and 1 to read it: $k(h + 1)$. Then $h$ references to translate the data’s address: $k(h + 1) + h = kh + k + h$ in all. With $h = k$, $k^2 + 2k = (k + 1)^2 - 1$ (`test_exercise_7_walk_count`).

**Exercise 14.8 ★★.**

A trap costs $T = 2{,}000$ instruction times on some hypothetical server. What slowdown does a [guest](#def-b3-virtualisation-vm) with one trap every 10,000 instructions see? What trap fraction keeps the slowdown under 5 %? The [guest](#def-b3-virtualisation-vm) of [Listing 14.1](#lst-b3-virtualisation-guest) traps once every 16.6 instructions: what would it see?

**Solution of Exercise 14.8.**

$1 + 10^{-4} \times 1{,}999 \approx 1.20$: 20 % slower. Under 5 % needs $f \times 1{,}999 \le 0.05$, $f \le 2.5 \times 10^{-5}$: one trap every 40,000 instructions. The [guest](#def-b3-virtualisation-vm) of the chapter would run $1 + 1{,}999/16.6 \approx 121$ times slower: a [guest](#def-b3-virtualisation-vm) that talks to its devices one character at a time is the worst case.

**Exercise 14.9 ★★.**

Before reading [Output 14.5](#out-b3-virtualisation-rlimit), predict what [Listing 14.6](#lst-b3-virtualisation-rlimit) prints: could the child get four blocks of 16 MiB under a 64 MiB limit? What would change with `RLIMIT_AS` at 1 GiB?

**Solution of Exercise 14.9.**

Four blocks of 16 MiB would need the whole 64 MiB, and the [address space](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space) already holds the program’s code, the C library, the stack and the [allocator](https://one-course.com/books/computer-science/5/en/chapter/9-memory-management-and-garbage-collection#def-b3-garbage-collection-allocator)’s own data. So the fourth `malloc` returns `NULL`: three blocks, as printed. The child returns 0, the parent’s allocation of 256 MiB is not limited, since a [resource limit](#def-b3-virtualisation-container) applies to the process that set it and its future children. With 1 GiB the child would get about 63 blocks, by the same reasoning, if the machine has the memory (the `memset` makes it real).

**Exercise 14.10 ★★★.**

A machine has a mode bit $s$ (supervisor or user), registers, and memory. A user-mode step of a [privileged instruction](#def-b3-virtualisation-sensitive) traps: it saves the pc and jumps to the [hypervisor](#def-b3-virtualisation-vm) in supervisor mode. Model a [guest](#def-b3-virtualisation-vm) state as a pair (virtual mode bit, registers and memory), and assume every [sensitive instruction](#def-b3-virtualisation-sensitive) is privileged. Prove that running the [guest](#def-b3-virtualisation-vm) in user mode, with the [hypervisor](#def-b3-virtualisation-vm) emulating each trapped instruction on the virtual mode bit, produces after every step the state that a real machine in the [guest](#def-b3-virtualisation-vm)’s state would produce.

**Solution of Exercise 14.10.**

Facts used: a non-privileged instruction executed in user mode does what it does in supervisor mode, provided it is not sensitive, since only [sensitive instructions](#def-b3-virtualisation-sensitive) depend on or change the mode, the translation or the devices; every [sensitive instruction](#def-b3-virtualisation-sensitive) is privileged, so it traps in user mode; the [hypervisor](#def-b3-virtualisation-vm)’s emulation of an instruction $i$ applies to (virtual mode, registers, memory) the transition the real machine applies to (mode, registers, memory).

Claim: after each [guest](#def-b3-virtualisation-vm) step, the real registers and memory equal those of a real machine run from the same initial state, and the virtual mode bit equals its mode. Initially true. Step with an instruction $i$. If $i$ is not sensitive, it does not trap, its effect does not depend on the mode, and it does not change it: the real user-mode step gives the same registers and memory as the reference machine, and the virtual bit is unchanged on both sides. If $i$ is sensitive, it is privileged and traps; the [hypervisor](#def-b3-virtualisation-vm) applies $i$’s transition to the virtual state, equal by hypothesis to the reference state, and returns to the [guest](#def-b3-virtualisation-vm) after $i$: both sides take the same transition. By induction the claim holds after every step. If some [sensitive instruction](#def-b3-virtualisation-sensitive) were not privileged, the second case would fail: it would run directly, reading or changing the real mode instead of the virtual one.

**Exercise 14.11 ★★★.**

`exercises/ex11_detect.py` gives a monitor that adds its own work, `charge` instructions per trap, to the [guest](#def-b3-virtualisation-vm)’s clock. Its [guest](#def-b3-virtualisation-vm) reads the clock twice in a row. What does it print for each charge? Can a monitor that charges nothing still be detected by a [guest](#def-b3-virtualisation-vm)? Discuss what a [guest](#def-b3-virtualisation-vm) can measure.

**Solution of Exercise 14.11.**

The first read happens at the [guest](#def-b3-virtualisation-vm)’s first instruction, the second at its second; with `charge` instructions added per trap after the first, the difference is $1 + \mathit{charge}$, and the [guest](#def-b3-virtualisation-vm) prints `charge`: 0, 1 and 50 (`test_exercise_11_timing_detects_the_monitor`). A monitor that charges nothing shows the [guest](#def-b3-virtualisation-vm) a clock that counts only its own instructions: this [guest](#def-b3-virtualisation-vm) cannot tell. But the monitor’s work takes real time, and any clock the [guest](#def-b3-virtualisation-vm) can reach without trapping, a real time register readable in user mode or a device that counts real time, a reply from another machine, reveals it. A [guest](#def-b3-virtualisation-vm) can always measure something; a [hypervisor](#def-b3-virtualisation-vm) can only make every clock it controls consistent, and keep the others out of reach.

**Exercise 14.12 ★★★.**

The monitor runs the [guest](#def-b3-virtualisation-vm) directly, so the [guest](#def-b3-virtualisation-vm) can load and store anywhere in the machine’s memory. Write `checked_step(m, lo, hi)`, which, before each [guest](#def-b3-virtualisation-vm) load or store, computes its address and stops the [guest](#def-b3-virtualisation-vm) if it falls outside $[\mathit{lo}, \mathit{hi})$. Test that a store outside is stopped before it happens. What does this check cost, and what does hardware do instead?

**Solution of Exercise 14.12.**

`exercises/ex12_fence.py` decodes the instruction at `pc` without running it; for a load or a store it computes `x[rs1] + imm` and its size, and raises `RVFault` if the access leaves $[\mathit{lo}, \mathit{hi})$, before calling `m.step()`. The test’s store at `0x10000004` is stopped and the word there stays 0 (`test_exercise_12_fence`). The check costs a decoding and a comparison on every memory instruction, the way [binary translation](#def-b3-virtualisation-techniques) that inserts checks costs. Hardware does the same check for free on every access, as the second stage of address translation: a [guest](#def-b3-virtualisation-vm) [physical address](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space) that the [host](#def-b3-virtualisation-vm)’s tables do not map faults.

## 14.7 Weekend problem

**Problem 14.1.**

Weekend problem — The cost of trapping

A [hypervisor](#def-b3-virtualisation-vm)’s overhead comes from two places: the [guest](#def-b3-virtualisation-vm)’s instructions that trap, and the addresses translated twice. This problem builds a model of each, checks the first against the counts of [Output 14.3](#out-b3-virtualisation-cost), and the second against [Output 14.4](#out-b3-virtualisation-walk).

**Part I — A guest’s instruction mix.**

1. In [Output 14.2](#out-b3-virtualisation-run) , what fraction $f$ of the [guest](#def-b3-virtualisation-vm) ’s instructions trapped? Which instructions were they?
2. How many traps would the [guest](#def-b3-virtualisation-vm) make to print a message of 1,000 characters, and what would $f$ become?
3. A console that takes a whole buffer at once, its address and its length in two CSRs, then a third write to start it: how many traps for the same 1,000 characters?
4. The sum $1 + 2 + \dots + 100$ takes how many instructions in the [guest](#def-b3-virtualisation-vm) ? Why does it never trap?
5. Which kinds of programs have a small $f$ , and which a large one?
6. Why does a [guest](#def-b3-virtualisation-vm) kernel trap more often than the programs that run on it?

**Part II — A model of the cost.**

7. A program runs $N$ instructions, a fraction $f$ of which trap, each trap costing $T$ ordinary instructions’ time. Show that the slowdown is $1 + f(T - 1)$ .
8. What does the slowdown tend to as $f \to 0$ ? And as $T \to 1$ ?
9. With $T = 1{,}000$ , compute the slowdown for $f = 10^{-4}, 10^{-3}, 10^{-2}$ and $10^{-1}$ .
10. For $T = 1{,}000$ , what $f$ keeps the slowdown under 10 %?
11. How does the buffered console of question 3 change the slowdown of the 1,000-character message?
12. An emulator interprets every instruction at a cost of $E$ [host](#def-b3-virtualisation-vm) instructions each. Compare its slowdown with that of [trap and emulate](#def-b3-virtualisation-sensitive) .

**Part III — The counts.**

13. In [Listing 14.4](#lst-b3-virtualisation-cost) , how is $T$ obtained from a loop in which every third instruction traps?
14. Check the first line of the table against the formula: what is the relative difference between the counted slowdown and $1 + f(T - 1)$ ?
15. The formula assumes that every ordinary instruction costs the same. Which instructions of the loop do not, and in which direction does that move the counted slowdown?
16. Why is $T$ about 1 for this monitor, when it does more work per trap than the machine does per instruction?
17. A plain instruction costs 64.7 Python lines. If one Python line took as long as one native instruction, what would $E$ be for the `rv` machine? Compare with [trap and emulate](#def-b3-virtualisation-sensitive) for the [guest](#def-b3-virtualisation-vm) of [Output 14.2](#out-b3-virtualisation-run) and $T = 1{,}000$ .
18. Why did the listing count lines instead of measuring seconds?

**Part IV — Translating twice.**

19. Show that the two-stage walk makes $kh + k + h$ references before the data, and compute it for $k = h = 4$ .
20. Without virtualisation, how many references does a four-level walk make? By what factor does nesting multiply the cost of a [TLB](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-tlb) miss?
21. If a fraction $m$ of the accesses miss the [TLB](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-tlb) , what is the average number of references per access, with and without nesting, for $k = h = 4$ ? Compute it for $m = 0.01$ .
22. The [host](#def-b3-virtualisation-vm) maps the [guest](#def-b3-virtualisation-vm) ’s memory with large pages, using two levels instead of four. What does a walk cost now?
23. Instead of nesting, a [hypervisor](#def-b3-virtualisation-vm) can keep its own table that maps the [guest](#def-b3-virtualisation-vm) ’s virtual addresses directly to real ones. What must it do whenever the [guest](#def-b3-virtualisation-vm) changes one of its [page tables](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-paging) ?
24. Sum up: what makes virtualisation cheap, and what makes it dear?

**Solution of Problem 14.1.**

**1.** $25/416 \approx 0.060$: the 21 console writes, the two writes to the number display, the clock read and the power switch.

**2.** 1,004 traps. The loop takes 5 instructions per character, so the [guest](#def-b3-virtualisation-vm) runs $2 + 5{,}000 + 2 + 2 + 300 + 5 = 5{,}311$ instructions, and $f \approx 0.19$.

**3.** Three: the address, the length and the start.

**4.** 302: two `li` and 100 rounds of 3. None of them is sensitive: arithmetic on the [guest](#def-b3-virtualisation-vm)’s own registers.

**5.** A program that computes in its own memory has a small $f$; one that does input and output, changes its [address space](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-space) or takes many [interrupts](https://one-course.com/books/computer-science/5/en/chapter/10-the-kernel-and-cpu-scheduling#def-b3-kernel-and-scheduling-interrupt), a large one.

**6.** The kernel is the code that manages devices, [page tables](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-paging), [interrupts](https://one-course.com/books/computer-science/5/en/chapter/10-the-kernel-and-cpu-scheduling#def-b3-kernel-and-scheduling-interrupt) and the privilege mode, exactly the sensitive state; the programs above it reach that state only through the kernel.

**7.** $(1 - f)N$ ordinary instructions cost one unit each and $fN$ traps cost $T$ each: $N(1 - f + fT) = N(1 + f(T - 1))$, against $N$ without traps.

**8.** To 1 in both cases: no traps, or traps that cost no more than the instruction they replace.

**9.** About 1.10, 2.0, 11 and 101.

**10.** $999 f \le 0.1$, $f \le 10^{-4}$: one trap every 10,000 instructions.

**11.** One trap per character costs about $1{,}004 \times 999 \approx 10^6$ instruction times; three traps for the whole buffer, about 3,000. Batching work into fewer traps is the main way to make a [guest](#def-b3-virtualisation-vm)’s devices fast.

**12.** An emulator’s slowdown is $E$ for every program; [trap and emulate](#def-b3-virtualisation-sensitive)’s is $1 + f(T - 1)$, close to 1 for most programs. [Trap and emulate](#def-b3-virtualisation-sensitive) loses only if $f(T - 1) > E - 1$.

**13.** The loop runs a trap, an `addi` and a `bnez`: its cost per instruction $c$ is $(T + 2)p/3$, where $p$ is the cost of a plain instruction, so $T = 3c/p - 2$.

**14.** $1.0167$ against $1.0155$: a difference of about 0.1 %.

**15.** The plain cost $p$ was measured on a loop with one branch in three instructions; the long loops are almost all `addi`, cheaper than a branch. Against that cheaper baseline a trap is relatively dearer, so the counted slowdown is slightly above the formula, as printed.

**16.** The machine itself runs about 65 lines for every instruction, to fetch, decode, execute and count it; the monitor’s decoding and emulation is of the same order, and it replaces the instruction’s own execution.

**17.** $E \approx 65$. [Trap and emulate](#def-b3-virtualisation-sensitive) with $T = 1{,}000$ gives $1 + 0.06 \times 999 \approx 61$ for that [guest](#def-b3-virtualisation-vm): about the same. For a [guest](#def-b3-virtualisation-vm) that traps so often, an emulator would do almost as well; for an ordinary one, with $f$ near $10^{-4}$, [trap and emulate](#def-b3-virtualisation-sensitive) is about 60 times faster.

**18.** A count reruns byte for byte; seconds on a laptop shared with other work vary from run to run by more than the effect to be measured. A first version timed the runs, and its slowdowns varied by several per cent between two runs.

**19.** $k$ [host](#def-b3-virtualisation-vm) walks before the [guest](#def-b3-virtualisation-vm)’s $k$ entries, plus one for the data: $kh + k + h = 16 + 4 + 4 = 24$.

**20.** 4. Counting the data access, 25 instead of 5: a [TLB](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-tlb) miss costs five times as much.

**21.** $1 + 4m$ without nesting, $1 + 24m$ with it: 1.04 and 1.24 for $m = 0.01$.

**22.** $4 \times 2 + 4 + 2 = 14$.

**23.** It must notice every change: write-protect the [guest](#def-b3-virtualisation-vm)’s [page tables](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-paging) so that each write traps, and update its own table in the handler. The cost moves from the walks to the traps.

**24.** Virtualisation is cheap when the [guest](#def-b3-virtualisation-vm) runs its own instructions directly and rarely traps, with $f(T - 1)$ small, and when the [TLB](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-tlb) hides the second stage of translation. It is dear when the [guest](#def-b3-virtualisation-vm) talks to its devices often, in small pieces, or misses the [TLB](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#def-b3-virtual-memory-tlb) often: each trap costs $T$, and each miss $(k + 1)^2 - 1$ references instead of $k$.
