কম্পিউটার বিজ্ঞান · বই 5 · স্নাতক তৃতীয় বর্ষ

University Computer Science — Year 3

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 3 · স্নাতক তৃতীয় বর্ষ

14Virtual 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 kernel on the rv machine, intercepts every instruction the guest 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, which isolate processes without a second kernel, and the price of each kind of isolation.

You already know

Chapter 10 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 translated virtual addresses through page tables of several levels, one memory reference per level, and cached the results in a 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 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 is itself an operating system with the means to virtualise, and a type-2 one relies on a host for everything else.

The two types of hypervisor, as stacks of software. Each layer sees the one below as its machine.
The two types of hypervisor, as stacks of software. Each layer sees the one below as its machine.

14.2 Trap and emulate

The guest kernel believes it runs in supervisor mode. The hypervisor runs it in user mode instead, so that the instructions only a kernel may execute leave the guest and come to the hypervisor.

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 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 in a less privileged mode, directly on the processor, lets every privileged instruction trap to the hypervisor, and has the hypervisor perform its effect on the guest’s virtual state before resuming the guest after it.

Theorem 14.3 (Popek–Goldberg theorem)

If every sensitive instruction of a machine is privileged, a hypervisor for that machine can be built by trap and emulate: the guest runs directly except for its sensitive instructions, each of which traps and is emulated.

Proof idea. Run the guest in user mode, and keep for it a virtual copy of every register and device that sensitive instructions 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’s state. A sensitive instruction is privileged, so it traps; the hypervisor applies its effect to the virtual copy, which is what the real machine would have done, and resumes the guest. By induction on the steps, the guest’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 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 of Listing 14.1 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 writes them as raw words: for rv, as for user mode, they are illegal.

# 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 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’s first device access stops it.

The monitor of Listing 14.2 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’s memory, emulates it on the virtual devices, and steps over it.

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’s instructions; the console collects what the guest prints. code/bachelor-3/14-virtualisation/listings/monitor.py
One trap. The guest never knows that the console is a Python list.
One trap. The guest never knows that the console is a Python list.
"""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 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 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 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.

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 BB 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)1 + f(T - 1) to within about one part in a thousand.

A trap replaces one ordinary instruction by one costing TT, so a fraction ff of traps multiplies the time by 1+f(T−1)1 + f(T - 1). Here TT 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 on real hardware is the opposite. Its guest runs at the processor’s own speed, and only a trap leaves it, through the hardware’s exception entry, the hypervisor’s decoding and emulation, and the return: TT is then a large number of instructions, and the fraction ff 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’s values to the guest. 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’s code before it runs, replacing each sensitive instruction by a call to the hypervisor and leaving the others to run directly. Paravirtualisation modifies the guest’s source so that it calls the hypervisor explicitly, with hypercalls, instead of executing sensitive instructions. Hardware virtualisation adds a processor mode for guests in which sensitive instructions trap; nested paging adds a second stage of hardware address translation, from the guest’s physical addresses to the host’s.

RISC-V’s hypervisor extension is of the third kind: it hosts guest operating systems under a type-1 or a type-2 hypervisor, and translates in two stages, the guest’s own tables taking a virtual address to a guest physical address, and the hypervisor’s tables that address to a real one. Every guest physical address goes through the second stage, including the addresses of the guest’s page-table entries themselves. A walk therefore nests one walk inside another (Listing 14.5).

    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 level, a whole host 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.
A two-stage walk with two levels on each side, as in the last line of Output 14.4. With kk levels on both sides it costs (k+1)2−1(k + 1)^2 - 1 references.

With kk guest levels and hh host levels, each of the kk guest entries costs a host walk of hh references and its own read, and the data’s address one more host walk: k(h+1)+h=kh+k+hk(h + 1) + h = kh + k + h, and (k+1)2−1(k + 1)^2 - 1 when h=kh = k. A 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. Often the guests 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’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 name, the inter-process communication objects, the root of the control groups, and the boot and monotonic clocks. Its manual page names containers as one use of them.

A control group’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).

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. 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. 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.

isolationboundaryshared with the neighbourscost
processsystem calls, page tablesthe kernel, the file systemalmost none
containersystem calls, filtered by namespaces and limitsthe kernelalmost none; the same kernel for all
virtual machinethe trapping instructions and the virtual devicesthe hypervisor, the hardwarea kernel per guest, traps, two-stage walks
language sandboxthe language’s operations and its librarythe interpreter’s processchecks 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’s interface is a few instructions and devices, a kernel’s hundreds of system calls.

A 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; a virtual machine’s boundary is much narrower. A host that must run strangers’ code side by side therefore has reason to prefer the narrower boundary, or to narrow a 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 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’s own memory? Which of them are sensitive? Is any sensitive and not privileged?

Solution

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’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 must control. Reading time is therefore sensitive but, by the numbering rule alone, not privileged: the guest would read the real clock.

Exercise 14.2 ★

Which type of hypervisor 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, which schedules them and drives the hardware?

Solution

Solution of Exercise 14.2.

(a) Type 2: it runs as an application of the host operating system. (b) Type 1: it runs on the bare hardware and is itself the operating system that schedules the guests.

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 tables and four-level host tables?

Solution

Solution of Exercise 14.3.

kh+k+hkh + k + h: 2×2+2+2=82 \times 2 + 2 + 2 = 8, as in the last line of Output 14.4; with k=2k = 2 and h=4h = 4, 8+2+4=148 + 2 + 4 = 14.

Exercise 14.4 ★

Predict the number of traps in Output 14.2 from Listing 14.1, without running it.

Solution

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=2521 + 4 = 25 (test_guest_under_the_monitor_and_exercise_4).

Exercise 14.5 ★★

exercises/ex5_stuck.py emulates each instruction but leaves the guest’s pc where it was. What does the guest do, what does the console contain, and how does the run end? Fix it.

Solution

Solution of Exercise 14.5.

The guest 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 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’s pc in CSR 0x5c6 and jumps to the handler, once. The test runs a guest that counts in a loop until the timer stops it.

Solution

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 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 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 kk guest levels and hh host levels makes kh+k+hkh + k + h references before the data, and that this is (k+1)2−1(k + 1)^2 - 1 when h=kh = k.

Solution

Solution of Exercise 14.7.

Facts used: every guest physical address must be translated by the host’s walk, hh references, before it can be read; the guest’s walk reads one entry per level, kk entries, each at a guest physical address; the data’s address is a guest physical address too.

For each of the kk guest levels, hh references to find where the entry is and 1 to read it: k(h+1)k(h + 1). Then hh references to translate the data’s address: k(h+1)+h=kh+k+hk(h + 1) + h = kh + k + h in all. With h=kh = k, k2+2k=(k+1)2−1k^2 + 2k = (k + 1)^2 - 1 (test_exercise_7_walk_count).

Exercise 14.8 ★★

A trap costs T=2,000T = 2{,}000 instruction times on some hypothetical server. What slowdown does a guest with one trap every 10,000 instructions see? What trap fraction keeps the slowdown under 5 %? The guest of Listing 14.1 traps once every 16.6 instructions: what would it see?

Solution

Solution of Exercise 14.8.

1+10−4×1,999≈1.201 + 10^{-4} \times 1{,}999 \approx 1.20: 20 % slower. Under 5 % needs f×1,999≤0.05f \times 1{,}999 \le 0.05, f≤2.5×10−5f \le 2.5 \times 10^{-5}: one trap every 40,000 instructions. The guest of the chapter would run 1+1,999/16.6≈1211 + 1{,}999/16.6 \approx 121 times slower: a guest that talks to its devices one character at a time is the worst case.

Exercise 14.9 ★★

Before reading Output 14.5, predict what Listing 14.6 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

Solution of Exercise 14.9.

Four blocks of 16 MiB would need the whole 64 MiB, and the address space already holds the program’s code, the C library, the stack and the 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 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 ss (supervisor or user), registers, and memory. A user-mode step of a privileged instruction traps: it saves the pc and jumps to the hypervisor in supervisor mode. Model a guest state as a pair (virtual mode bit, registers and memory), and assume every sensitive instruction is privileged. Prove that running the guest in user mode, with the hypervisor emulating each trapped instruction on the virtual mode bit, produces after every step the state that a real machine in the guest’s state would produce.

Solution

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 depend on or change the mode, the translation or the devices; every sensitive instruction is privileged, so it traps in user mode; the hypervisor’s emulation of an instruction ii applies to (virtual mode, registers, memory) the transition the real machine applies to (mode, registers, memory).

Claim: after each guest 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 ii. If ii 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 ii is sensitive, it is privileged and traps; the hypervisor applies ii’s transition to the virtual state, equal by hypothesis to the reference state, and returns to the guest after ii: both sides take the same transition. By induction the claim holds after every step. If some sensitive instruction 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’s clock. Its guest 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? Discuss what a guest can measure.

Solution

Solution of Exercise 14.11.

The first read happens at the guest’s first instruction, the second at its second; with charge instructions added per trap after the first, the difference is 1+charge1 + \mathit{charge}, and the guest prints charge: 0, 1 and 50 (test_exercise_11_timing_detects_the_monitor). A monitor that charges nothing shows the guest a clock that counts only its own instructions: this guest cannot tell. But the monitor’s work takes real time, and any clock the guest 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 can always measure something; a hypervisor can only make every clock it controls consistent, and keep the others out of reach.

Exercise 14.12 ★★★

The monitor runs the guest directly, so the guest can load and store anywhere in the machine’s memory. Write checked_step(m, lo, hi), which, before each guest load or store, computes its address and stops the guest if it falls outside [lo,hi)[\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

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 [lo,hi)[\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 that inserts checks costs. Hardware does the same check for free on every access, as the second stage of address translation: a guest physical address that the host’s tables do not map faults.

14.7 Weekend problem

Problem 14.1

Weekend problem — The cost of trapping

A hypervisor’s overhead comes from two places: the guest’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, and the second against Output 14.4.

Part I — A guest’s instruction mix.

  1. In Output 14.2, what fraction ff of the guest’s instructions trapped? Which instructions were they?
  2. How many traps would the guest make to print a message of 1,000 characters, and what would ff 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+⋯+1001 + 2 + \dots + 100 takes how many instructions in the guest? Why does it never trap?
  5. Which kinds of programs have a small ff, and which a large one?
  6. Why does a guest kernel trap more often than the programs that run on it?

Part II — A model of the cost.

  1. A program runs NN instructions, a fraction ff of which trap, each trap costing TT ordinary instructions’ time. Show that the slowdown is 1+f(T−1)1 + f(T - 1).
  2. What does the slowdown tend to as f→0f \to 0? And as T→1T \to 1?
  3. With T=1,000T = 1{,}000, compute the slowdown for f=10−4,10−3,10−2f = 10^{-4}, 10^{-3}, 10^{-2} and 10−110^{-1}.
  4. For T=1,000T = 1{,}000, what ff keeps the slowdown under 10 %?
  5. How does the buffered console of question 3 change the slowdown of the 1,000-character message?
  6. An emulator interprets every instruction at a cost of EE host instructions each. Compare its slowdown with that of trap and emulate.

Part III — The counts.

  1. In Listing 14.4, how is TT obtained from a loop in which every third instruction traps?
  2. Check the first line of the table against the formula: what is the relative difference between the counted slowdown and 1+f(T−1)1 + f(T - 1)?
  3. 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?
  4. Why is TT about 1 for this monitor, when it does more work per trap than the machine does per instruction?
  5. A plain instruction costs 64.7 Python lines. If one Python line took as long as one native instruction, what would EE be for the rv machine? Compare with trap and emulate for the guest of Output 14.2 and T=1,000T = 1{,}000.
  6. Why did the listing count lines instead of measuring seconds?

Part IV — Translating twice.

  1. Show that the two-stage walk makes kh+k+hkh + k + h references before the data, and compute it for k=h=4k = h = 4.
  2. Without virtualisation, how many references does a four-level walk make? By what factor does nesting multiply the cost of a TLB miss?
  3. If a fraction mm of the accesses miss the TLB, what is the average number of references per access, with and without nesting, for k=h=4k = h = 4? Compute it for m=0.01m = 0.01.
  4. The host maps the guest’s memory with large pages, using two levels instead of four. What does a walk cost now?
  5. Instead of nesting, a hypervisor can keep its own table that maps the guest’s virtual addresses directly to real ones. What must it do whenever the guest changes one of its page tables?
  6. Sum up: what makes virtualisation cheap, and what makes it dear?
Solution

Solution of Problem 14.1.

1. 25/416≈0.06025/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 runs 2+5,000+2+2+300+5=5,3112 + 5{,}000 + 2 + 2 + 300 + 5 = 5{,}311 instructions, and f≈0.19f \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’s own registers.

5. A program that computes in its own memory has a small ff; one that does input and output, changes its address space or takes many interrupts, a large one.

6. The kernel is the code that manages devices, page tables, interrupts and the privilege mode, exactly the sensitive state; the programs above it reach that state only through the kernel.

7. (1−f)N(1 - f)N ordinary instructions cost one unit each and fNfN traps cost TT each: N(1−f+fT)=N(1+f(T−1))N(1 - f + fT) = N(1 + f(T - 1)), against NN 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. 999f≤0.1999 f \le 0.1, f≤10−4f \le 10^{-4}: one trap every 10,000 instructions.

11. One trap per character costs about 1,004×999≈1061{,}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’s devices fast.

12. An emulator’s slowdown is EE for every program; trap and emulate’s is 1+f(T−1)1 + f(T - 1), close to 1 for most programs. Trap and emulate loses only if f(T−1)>E−1f(T - 1) > E - 1.

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

14. 1.01671.0167 against 1.01551.0155: a difference of about 0.1 %.

15. The plain cost pp 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≈65E \approx 65. Trap and emulate with T=1,000T = 1{,}000 gives 1+0.06×999≈611 + 0.06 \times 999 \approx 61 for that guest: about the same. For a guest that traps so often, an emulator would do almost as well; for an ordinary one, with ff near 10−410^{-4}, trap and emulate 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. kk host walks before the guest’s kk entries, plus one for the data: kh+k+h=16+4+4=24kh + k + h = 16 + 4 + 4 = 24.

20. 4. Counting the data access, 25 instead of 5: a TLB miss costs five times as much.

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

22. 4×2+4+2=144 \times 2 + 4 + 2 = 14.

23. It must notice every change: write-protect the guest’s page tables 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 runs its own instructions directly and rarely traps, with f(T−1)f(T - 1) small, and when the TLB hides the second stage of translation. It is dear when the guest talks to its devices often, in small pieces, or misses the TLB often: each trap costs TT, and each miss (k+1)2−1(k + 1)^2 - 1 references instead of kk.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো