21. Device models and the bus you will keep

Three buses, one decode Three shelves of a bus museum. Port I/O: in and out instructions to port numbers, which KVM reports as KVM_EXIT_IO on x86. PCI: config space, BARs and an enumeration walk. virtio-mmio: one window of registers from MagicValue at offset 0 to device config at 0x100. All three are a decode of an address to a device model, the box under them. On RISC-V the access arrives as KVM_EXIT_MMIO, an arrow into the lab function mmio_uart. Below, two dashed boxes: wick keeps virtio-mmio (chapter 25); hearth keeps less, with no ACPI, no BIOS and no PIC (Part VII). PIO in / out, port KVM_EXIT_IO PCI config space, BARs enumeration walk virtio-mmio register window 0x000 to 0x100+ a decode: address (or port) to device model KVM_EXIT_MMIO mmio_uart(run): THR, LSR wick keeps virtio-mmio (chapter 25) hearth keeps less: no ACPI, no BIOS, no PIC (Part VII) every bus is an address decode

Why this layer exists

A guest kernel expects a machine, and a machine is more than a hart and RAM. It has a console to print on, a disk to read, a way to find out which of those exist. Chapters 19 and 20 ran a payload that touched memory and made one ecall; nothing in them was a device. The hart has no device in it. Every device a guest sees is something the hypervisor pretends is there, and the pretending is a program: a load or a store arrives at an address, the hypervisor works out which pretend device owns that address, and runs the code that does what the hardware would have done.

This chapter builds the smallest such program and then reads the shelf of buses around it. The program is a 16550 UART with two registers, and the guest that uses it is not new: the payload’s loop is ember’s chapter 2 uart_putc: poll the line-status register until bit 5 says the transmitter can take a byte, then store the byte to the transmit register. On QEMU’s virt board that driver talks to a UART QEMU models. Here the same two accesses go to an address no memory slot backs, and the VMM from chapter 20 answers them. The guest’s driver does not change; the machine under it does. That is the whole job of a device model, and every bus in the museum below (port I/O, PCI, virtio-mmio) turns out to be a different way of telling the guest which addresses to use.

Mechanism

Three terms, defined where this chapter first needs them. A device model is the code that does what a device’s hardware would do in response to accesses: it owns the device’s state, answers reads from that state and acts on writes. mmio_uart below is one; a file under QEMU’s hw/ is one; a Rust struct in Firecracker is one. An MMIO exit is KVM_RUN returning with exit_reason KVM_EXIT_MMIO: the guest executed a load or store to a guest-physical address that no memory slot covers and no device inside the kernel claims, and KVM has stopped the guest with the access described in kvm_run for the VMM to complete. A bus is whatever lets a guest find a device and name a register in it. Every bus in this chapter reduces to the same act, a decode of an address (or, on x86, a port number) to a device model and an offset into it; they differ in who assigns the addresses and how the guest learns them.

The smallest device: two registers of a 16550

The PC’s serial chip is the 16550. Its programming model is a handful of byte-wide registers selected by three address lines; the datasheet’s register-address table (the National Semiconductor PC16550D datasheet as republished by Texas Instruments, Table 2) puts them at offsets 0 to 7. Two are enough to print:

  • Offset 0, written, is the transmit holding register, THR: the byte stored there is sent. The same offset, read, is the receive buffer register, RBR; the datasheet’s table has one row for both, “Receiver Buffer (read), Transmitter Holding Register (write)”, and the direction of the access picks the register. That holds while the divisor-latch access bit (bit 7 of the line control register) is clear, its reset state; with it set, offset 0 is the divisor latch instead. The model never lets the guest set it.
  • Offset 5, read, is the line status register, LSR. Two of its bits matter here, in the datasheet’s words (§8.6.3). Bit 5: “This bit is the Transmitter Holding Register Empty (THRE) indicator. Bit 5 indicates that the UART is ready to accept a new character for transmission.” Bit 6: “This bit is the Transmitter Empty (TEMT) indicator. Bit 6 is set to a logic 1 whenever the Transmitter Holding Register (THR) and the Transmitter Shift Register (TSR) are both empty.”

The datasheet’s reset table (Table 3) gives the line status register’s state after a master reset as 0110 0000, bits 5 and 6 set: 0x60, a transmitter with nothing in it. The model returns exactly that on every read of LSR, and its THR write finishes before the exit returns, so the transmitter really is always empty. The real chip clears THRE while a character is in flight; the model has no flight time. The rest of the chip (the baud-rate divisor latches, the interrupt-enable and FIFO-control registers, the receive path, the modem lines) is not modelled, and the model says so by refusing any other offset.

The exit path, from instruction to run->mmio

The guest’s lbu t2, 5(t0) is a load from 0x10000005. Nothing maps that address in the G-stage, so the load takes a load guest-page fault into HS, the fault class chapter 19 showed and chapter 20 followed to gstage_page_fault: with no memory slot behind the address, a load goes to kvm_riscv_vcpu_mmio_load (and a store to its twin, quoted in chapter 20). The function’s first job is to learn what the guest tried to do. The hardware helps: on a guest-page fault it records a transformed copy of the faulting instruction in htinst, and when the copy is not available KVM reads the instruction out of guest memory at sepc.

// linux v7.2.8, arch/riscv/kvm/vcpu_insn.c:383-390
    /* Determine trapped instruction */
    if (htinst & 0x1) {
        /*
         * Bit[0] == 1 implies trapped instruction value is
         * transformed instruction or custom instruction.
         */
        insn = htinst | INSN_16BIT_MASK;
        insn_len = (htinst & BIT(1)) ? INSN_LEN(insn) : 2;

The second job is the width. Nothing in the fault says how many bytes the guest wanted; the opcode does, and KVM decodes it:

// linux v7.2.8, arch/riscv/kvm/vcpu_insn.c:409-417
    /* Decode length of MMIO and shift */
    if ((insn & INSN_MASK_LW) == INSN_MATCH_LW) {
        len = 4;
        shift = 8 * (sizeof(ulong) - len);
    } else if ((insn & INSN_MASK_LB) == INSN_MATCH_LB) {
        len = 1;
        shift = 8 * (sizeof(ulong) - len);
    } else if ((insn & INSN_MASK_LBU) == INSN_MATCH_LBU) {
        len = 1;

len is therefore the instruction’s width, not a property of the device: a lbu is 1, a lw is 4, an ld is 8. The function then refuses a misaligned access with an error (-EIO, not an exit) and fills in kvm_run:

// linux v7.2.8, arch/riscv/kvm/vcpu_insn.c:452-466
    /* Fault address should be aligned to length of MMIO */
    if (fault_addr & (len - 1))
        return -EIO;

    /* Save instruction decode info */
    vcpu->arch.mmio_decode.insn = insn;
    vcpu->arch.mmio_decode.insn_len = insn_len;
    vcpu->arch.mmio_decode.shift = shift;
    vcpu->arch.mmio_decode.len = len;
    vcpu->arch.mmio_decode.return_handled = 0;

    /* Update MMIO details in kvm_run struct */
    run->mmio.is_write = false;
    run->mmio.phys_addr = fault_addr;
    run->mmio.len = len;

Before the exit, the access is offered to devices that live inside the kernel; this lab registers none, so every access to the UART exits:

// linux v7.2.8, arch/riscv/kvm/vcpu_insn.c:477-481
    /* Exit to userspace for MMIO emulation */
    vcpu->stat.mmio_exit_user++;
    run->exit_reason = KVM_EXIT_MMIO;

    return 0;

KVM_RUN returns and the VMM reads run->mmio. The documentation says what the VMM owes in return, in a sentence (api.rst:6734-6735): the data member “contains the written data if ‘is_write’ is true, and should be filled by application code otherwise”, and, from the paragraph below it (api.rst:6737), “in its first ‘len’ bytes, the value as it would appear if the VCPU performed a load or store of the appropriate width directly to the byte array.” For the UART read the VMM stores 0x60 in data[0] and calls KVM_RUN again. A VMM that forgets to fill data gets no error: the next KVM_RUN consumes whatever bytes are there.

The guest has not moved on yet. The faulting load has neither completed nor been skipped, and KVM_RUN’s first act on the next call is to finish it, before any guest instruction runs:

// linux v7.2.8, arch/riscv/kvm/vcpu.c:872-876
    switch (run->exit_reason) {
    case KVM_EXIT_MMIO:
        /* Process MMIO value returned from user-space */
        ret = kvm_riscv_vcpu_mmio_return(vcpu, vcpu->run);
        break;

kvm_riscv_vcpu_mmio_return does the two things a load would have done. It puts the byte from run->mmio.data into the destination register, and, for stores and loads alike, it steps sepc over the instruction:

// linux v7.2.8, arch/riscv/kvm/vcpu_insn.c:641-652
    if (run->mmio.is_write)
        goto done;

    len = vcpu->arch.mmio_decode.len;
    shift = vcpu->arch.mmio_decode.shift;

    switch (len) {
    case 1:
        data8 = *((u8 *)run->mmio.data);
        SET_RD(insn, &vcpu->arch.guest_context,
            (long)((ulong)data8 << shift) >> shift);
        break;

The shift was set by the decode: lbu leaves it 0, so the byte is zero-extended into the register, while lb sets it to 56 and the arithmetic right shift sign-extends. The UART’s 0x60 reads the same either way.

// linux v7.2.8, arch/riscv/kvm/vcpu_insn.c:672-674
done:
    /* Move to next instruction */
    vcpu->arch.guest_context.sepc += vcpu->arch.mmio_decode.insn_len;

So an MMIO exit is a synchronous call from the guest into the VMM with a small ABI: one instruction in, at most eight bytes either way. The guest sees an ordinary load that took a long time. The VMM sees a switch case. The model’s continue in the exit loop is that second KVM_RUN.

The exit count follows from this. The payload’s instruction fetches and the lbu that reads the string from .rodata touch the memory slot, where a G-stage fault is KVM’s own to resolve and never returns to the VMM (chapter 20); the shutdown ecall returns as a system event, not an MMIO exit. mmio exits counts the accesses the model answered and nothing else.

Port I/O, named

On x86 the PC architecture has a second address space beside memory: 16-bit port numbers reached by the in and out instructions. KVM reports such an access as KVM_EXIT_IO, with a different record:

// linux v7.2.8, Documentation/virt/kvm/api.rst:6695-6704
        /* KVM_EXIT_IO */
        struct {
  #define KVM_EXIT_IO_IN  0
  #define KVM_EXIT_IO_OUT 1
            __u8 direction;
            __u8 size; /* bytes */
            __u16 port;
            __u32 count;
            __u64 data_offset; /* relative to kvm_run start */
        } io;

The documentation recommends both exits, rather than KVM_EXIT_HYPERCALL (a guest’s explicit call to the hypervisor, with a number and six arguments), for the same job (api.rst:6768-6772; “It is strongly recommended that userspace use KVM_EXIT_IO (x86) or KVM_EXIT_MMIO (all except s390) to implement functionality that requires a guest to interact with host userspace”) and adds a note: “.. note:: KVM_EXIT_IO is significantly faster than KVM_EXIT_MMIO.” RISC-V has no port space, so this lab’s only device exit is KVM_EXIT_MMIO, and KVM_EXIT_IO is named here and not used. A model for a port would key on run->io.port where this one keys on run->mmio.phys_addr, and find its data data_offset bytes into the kvm_run page.

PCI: a bus that tells the guest where the devices are

PCI solves discovery. A guest does not need to be told which devices exist or where: each device exposes a small block of configuration registers, addressed by (bus, device, function), whose first fields are a vendor ID and a device ID, and an OS enumerates by walking every address and noting which ones answer. The same block holds the BARs (base address registers), where the OS writes the address at which the device’s own registers should appear. The guest, not the hypervisor, assigns the decode addresses. The cost to the hypervisor is a model of the host bridge, of configuration space for every device, of BAR sizing, and of the interrupt plumbing PCI brings (MSI and MSI-X). Virtio over PCI is §4.1 of the virtio 1.2 specification: “Any PCI device with PCI Vendor ID 0x1AF4, and PCI Device ID 0x1000 through 0x107F inclusive is a virtio device” (§4.1.2). wick would need that transport to boot a guest that expects PCI, and does not build it: it hands its guests virtio-mmio instead.

virtio-mmio: no discovery, one window

The virtio specification introduces the memory-mapped transport as the one for the machines without a PCI bus: “Virtual environments without PCI support (a common situation in embedded devices models) might use simple memory mapped device (“virtio-mmio”) instead of the PCI device.” (§4.2). What it gives up is discovery, and §4.2.1 says so: “Unlike PCI, MMIO provides no generic device discovery mechanism. For each device, the guest OS will need to know the location of the registers and interrupt(s) used.” That is chapter 11’s situation from the guest side: ember probes eight windows at 0x10001000 + n * 0x1000 because QEMU’s virt board put devices there. A VMM that builds the machine chooses the addresses and tells the guest (the specification’s suggested binding is a device-tree node with the window’s base, its length and an interrupt number).

What sits in a window is the register table of §4.2.2 (Table 4.1, fetched 2026-10-01). The registers ember’s chapter 11 reads and writes, with the specification’s direction column:

Offset Name Direction
0x000 MagicValue R
0x004 Version R
0x008 DeviceID R
0x010 DeviceFeatures R
0x014 DeviceFeaturesSel W
0x020 DriverFeatures W
0x024 DriverFeaturesSel W
0x030 QueueSel W
0x034 QueueNumMax R
0x038 QueueNum W
0x044 QueueReady RW
0x050 QueueNotify W
0x060 InterruptStatus R
0x064 InterruptACK W
0x070 Status RW
0x080, 0x084 QueueDescLow, QueueDescHigh W
0x090, 0x094 QueueDriverLow, QueueDriverHigh W
0x0a0, 0x0a4 QueueDeviceLow, QueueDeviceHigh W
0x100+ Config (device-specific) RW

Two lines of §4.2.2.2 change what a model must check. First: “The driver MUST only use 32 bit wide and aligned reads and writes to access the control registers described in table 4.1.” So for the control registers mmio_virtio’s width test is len != 4 (the device-specific config space at 0x100 is accessed at the width of each field), where mmio_uart’s is len != 1; the offset is still phys_addr - base. Second: the driver “MUST NOT write to the read-only registers (direction R) and MUST NOT read from the write-only registers (direction W)”, so the direction column is the list of accesses the model may refuse, the same refusal exercise (c) asks mmio_uart to make for a read of THR. The register that matters for what comes next is QueueNotify: “Writing a value to this register notifies the device that there are new buffers to process in a queue.” One 32-bit store is the doorbell for an arbitrarily large transfer, which the 16550’s one-store-per-byte interface cannot be. Chapter 22 is that device.

What Firecracker deleted, and what a unikernel hypervisor deletes after it

Firecracker’s paper (Agache et al., NSDI 2020) is a list of buses not built. It “does not offer a BIOS, cannot boot arbitrary kernels, does not emulate legacy devices nor PCI, and does not support VM migration” (§1), and the reason is stated: “Lower-level features, such as additional devices (USB, PCI, sound, video, etc), BIOS, and CPU instruction emulation are simply not implemented because they are not needed by typical serverless container and function workloads.” What it keeps is “device emulation for disk, networking and serial console” (§3), and the cost of the part that matters: “The entire virtio block implementation in Firecracker (including MMIO and data structures) is around 1400 lines of Rust” (§3). A device model is cheap and a bus is expensive, and a guest that has no PCI needs no PCI model. That is chapter 23’s subject for wick; this chapter’s point is that each deleted bus is a decode the VMM no longer has to implement correctly.

hearth deletes further, because its guests are not Linux. A guest written against chapter 32’s contract is handed a boot-info block, not a platform description to discover: it does not need a table language (ACPI), a boot firmware to call (BIOS), or the PC’s legacy interrupt controller (the 8259 PIC) to find out what machine it is on. Each is a model the hypervisor does not have to write and a surface a guest cannot attack. That is the shorter shelf in the figure, and Part VII’s argument.

The three budget axes of chapter 14 apply to a device model without change, and exercise (f) places mmio_uart on them.

What this lab does not do

No interrupt reaches the guest: the payload polls LSR and nothing signals it. Interrupt injection is a separate mechanism with its own chapter in hearth (chapter 38) and, on a KVM host, its own ioctl: KVM_INTERRUPT (api.rst §4.16, which lists RISC-V) when KVM has no in-kernel model of the interrupt controller, an irqchip, and KVM_IRQ_LINE when it has one, which arch/riscv/kvm/vm.c implements and refuses without one (line 62) although §4.25 does not list RISC-V; chapter 22’s driver polls too. The model also has no receive path, no FIFO, and no state beyond the counter in the VMM.

Walkthrough

The payload is the driver. t0 holds the UART’s base; a2 walks the string in .rodata; the inner loop is uart_putc’s two steps, LSR read and mask, then the THR store. The end is chapter 19’s shutdown call, the same ecall with a7 = SRST.

# The guest: print "hi from VS\n" through a 16550's two registers, then
# ask for shutdown as chapter 19's payload did. Position independent, no
# stack. Every load and store through t0 is to an address no memory slot
# backs: each one is a VM exit that the VMM turns into a device access.
    .option norelax          # keep auipc+addi: the linker would fold them to an absolute li at address 0
    .section .text
    .globl _start
_start:
    li   t0, 0x10000000      # UART base (guest-physical)
    lla  a2, msg             # PC-relative, no GOT: the payload is loaded at 0x80000000
1:  lbu  a3, 0(a2)           # next byte of the string
    beqz a3, 3f              # NUL: done
2:  lbu  t2, 5(t0)           # LSR
    andi t2, t2, 0x20        # THRE: transmitter holding register empty
    beqz t2, 2b
    sb   a3, 0(t0)           # THR
    addi a2, a2, 1
    j    1b
3:  li   a7, 0x53525354      # SBI SRST, as chapter 19
    li   a6, 0
    li   a0, 0
    li   a1, 0
    ecall
4:  j    4b

    .section .rodata
msg:
    .asciz "hi from VS\n"

The Makefile assembles it with chapter 19’s flags (-march=rv64ima_zicsr -mabi=lp64 -nostdlib -static -Wl,-Ttext=0 -Wl,--build-id=none) and extracts .text and .rodata with objcopy -O binary, so the string follows the code in the file and in the guest’s memory. Two details are the toolchain’s. la a2, msg on this cross toolchain expands to a load from the global offset table, which objcopy -j .text -j .rodata leaves out of the binary the VMM loads. lla is the PC-relative form (auipc and addi), and with -Ttext=0 the linker relaxes that pair into an absolute li a2, 68; .option norelax keeps the pair, and the payload position-independent, which it has to be: it is linked at 0 and loaded at 0x80000000.

The device model is the ch21-uart listing. UART_BASE is the address the payload uses, and the offsets and the two LSR bits are the datasheet’s. mmio_uart returns 0 for the two accesses it understands, -1 for anything else, including a width other than 1.

#define UART_BASE 0x10000000UL
#define UART_THR  0
#define UART_LSR  5
#define LSR_THRE  0x20              /* transmitter holding register empty */
#define LSR_TEMT  0x40              /* transmitter empty */

/* The device model: what the hardware would have done, done by us,
 * after the exit. Reads fill run->mmio.data for the next KVM_RUN. */
static int mmio_uart(struct kvm_run *run)
{
    unsigned long off = run->mmio.phys_addr - UART_BASE;
    if (run->mmio.len != 1) return -1;
    if (run->mmio.is_write && off == UART_THR) {
        putchar(run->mmio.data[0]);
        fflush(stdout);
        return 0;
    }
    if (!run->mmio.is_write && off == UART_LSR) {
        run->mmio.data[0] = LSR_THRE | LSR_TEMT;
        return 0;
    }
    return -1;
}

The exit loop is chapter 20’s with one case changed. An exit inside the window UART_BASE to UART_BASE + 8 goes to the model, and on success the loop counts it and re-enters (continue is the second KVM_RUN of the Mechanism section). An access the model refuses, or any access outside the window, prints the line chapter 20 printed and fails the run.

/* Run until the guest stops. An MMIO exit inside the UART's window goes
 * to the device model and the loop re-enters; any other exit but a
 * shutdown system event is a failure. */
static int vcpu_run_until_exit(int vcpu, struct kvm_run *run)
{
    for (;;) {
        if (ioctl(vcpu, KVM_RUN, 0) < 0) die("KVM_RUN");
        switch (run->exit_reason) {
        case KVM_EXIT_SYSTEM_EVENT:
            printf("vmm: KVM_RUN exit %u (KVM_EXIT_SYSTEM_EVENT) type %u (%s) ndata %u\n",
                   run->exit_reason, run->system_event.type,
                   run->system_event.type == KVM_SYSTEM_EVENT_SHUTDOWN ? "SHUTDOWN" : "other",
                   run->system_event.ndata);
            return run->system_event.type == KVM_SYSTEM_EVENT_SHUTDOWN ? 0 : 1;
        case KVM_EXIT_MMIO:
            if (run->mmio.phys_addr >= UART_BASE && run->mmio.phys_addr < UART_BASE + 8) {
                if (mmio_uart(run) == 0) { mmio_exits++; continue; }
            }
            printf("vmm: KVM_RUN exit %u (KVM_EXIT_MMIO) %s gpa 0x%llx len %u: no device here\n",
                   run->exit_reason, run->mmio.is_write ? "write" : "read",
                   run->mmio.phys_addr, run->mmio.len);
            return 1;
        default:
            printf("vmm: KVM_RUN exit %u: unexpected\n", run->exit_reason);
            return 1;
        }
    }
}

main is chapter 20’s with the data page gone: no a0, no word to read back from the slot. It prints the exit count after the run and the two registers a7 and a6, and its verdict is a shutdown exit with a7 equal to the SRST extension id. The string itself is checked by the capture diff, not by the VMM: a model that dropped the THR writes would pass the verdict and fail the diff.

The lab starts red. With chapter 20’s VMM (which refuses every MMIO exit) and this payload, the guest’s first access is the LSR read:

vmm: KVM_RUN exit 6 (KVM_EXIT_MMIO) read gpa 0x10000005 len 1: no device here

The address is UART_BASE + 5, the length is the lbu’s, and the run fails there: the payload cannot print until the VMM is a bus.

Exercises

Each was run on talos (QEMU 11.1.1, the lab’s kernel and initramfs) in a scratch copy of labs/ch21/, one edit at a time.

(a) Change the model so that the first LSR read after each THR write (and the first read of the run) reports not-empty (0), and later reads report 0x60. What does mmio exits become, and why?

Answer

Observed: vmm: mmio exits 33, with the string and every other line of the capture unchanged. Each byte now costs three exits instead of two: an LSR read that says “busy”, the payload’s beqz back to the poll, a second LSR read that says “empty”, then the THR store. Eleven bytes at three is 33. Polling a register through a device model is paid in VM exits, one per poll; real hardware’s THRE would stay clear for a character time and the guest would spin at memory speed, here each spin is a round trip to the VMM. The model’s always-empty LSR is the cheapest honest answer, and it is also the reason the capture’s 22 is a lower bound for this payload.

(b) Change the payload’s sb a3, 0(t0) to sw a3, 0(t0), a four-byte store to the same address. What fails, and what does len mean?

Answer

Observed:

vmm: KVM_RUN exit 6 (KVM_EXIT_MMIO) write gpa 0x10000000 len 4: no device here
vmm: mmio exits 1
vmm: guest a7=0x0 a6=0x0
vmm: FAIL
vmm rc=1

The count is 1: the first LSR read was served, and the run died at the first store. The address is right, the direction is right and len is 4. len is the width of the instruction, decoded from its opcode in kvm_riscv_vcpu_mmio_store (vcpu_insn.c:539-542: INSN_MATCH_SW sets len = 4, INSN_MATCH_SB sets 1), and it says nothing about what the device accepts; data[0..3] hold the four bytes of the register’s value, as the documentation’s “first ‘len’ bytes” says. mmio_uart’s len != 1 test is a decision that this device is byte-wide. A model that accepted the store would have to choose what a word to a byte register means (take the low byte, or the whole word as four characters); refusing is the choice that cannot print the wrong thing.

(c) Add a lbu t3, 0(t0) before the poll loop: a read of THR’s offset. What does the model do, and what would a real 16550 return?

Answer

Observed: vmm: KVM_RUN exit 6 (KVM_EXIT_MMIO) read gpa 0x10000000 len 1: no device here and vmm: mmio exits 0, then FAIL. The model refuses the read because it implements THR, the write side of offset 0, and not RBR, the read side (offset 0 is those two only while the divisor-latch access bit is clear, which it always is here). The datasheet’s register table has one row for both at offset 0 (Table 2: “Receiver Buffer (read), Transmitter Holding Register (write)”); the chip returns whatever its receive buffer holds, and LSR bit 0 (data ready) says whether that byte is fresh. A model with no receive path could return 0, which would tell the guest a NUL byte arrived. Refusing is safer, and costs nothing for a driver that checks data-ready first: the model’s LSR is 0x60, bit 0 clear, and ember’s uart_getc (uart[LSR] & LSR_DR, chapter 2) never reads RBR in that case.

(d) Move the UART to 0x10001000 in both the payload and UART_BASE. What changes in the capture?

Answer

Nothing: diff against capture.txt reports no difference: string, exit count and all. (The edit is two constants, li t0, 0x10001000 and #define UART_BASE 0x10001000UL.) 0x10001000 is where QEMU’s virt board puts its first virtio-mmio window, the address ember’s chapter 11 probes; in this VM it is an address like any other, with a model where the VMM put one. The guest cannot tell, and neither can the exit: phys_addr is only a key into the VMM’s decode. A bus is that mapping, and who writes it down (a datasheet, a BAR, a device tree node) is the only difference among the shelves of the figure.

(e) Make the payload’s string 1024 bytes of x and run. How many exits does it cost, and what does the virtio ring (chapter 22) exist to replace?

Answer

Observed: vmm: mmio exits 2048, with PASS (the payload is 0x449 bytes: the code, 1024 characters and a NUL). Two exits per byte, 2048 in all, each a trip from the guest through HS and the kernel’s instruction decoder to userspace and back through KVM_RUN. Nothing about the exit count depends on the device being fast; it is set by the interface, a register per byte. A virtqueue replaces the byte-per-store interface with a descriptor in guest memory that names the whole buffer: the memory is a slot the VMM already has mapped (chapter 20), so reading the buffer costs no exit, and the guest signals the device with a single write to QueueNotify (offset 0x50, Table 4.1) for the batch. One doorbell exit, then, where this device pays 2048; chapter 22 builds the backend and counts.

(f) Place mmio_uart on chapter 14’s three axes, as it runs in the VMM process, and say what changes in hearth.

Answer

Shared. The guest and the model share one thing, the register window: the guest-physical addresses UART_BASE to UART_BASE + 7, with nothing behind them except what the VMM chooses to answer. They share no memory beyond chapter 20’s slot, and the model’s state (the mmio_exits counter, stdout) is the VMM process’s own.

TCB. mmio_uart runs in the VMM process, at the privilege of a userspace program under the host kernel, so a bug in it is a bug in a process that the host can confine (chapter 26’s jailer for wick); what the guest reaches in the kernel is the exit path quoted above, and the instruction decoder in it is KVM’s, not the VMM’s. In hearth there is no process to confine: the device model is part of the hypervisor image, so every line of it is in the TCB, which is the argument for the short shelf in the figure.

Copy. At most eight bytes cross per exit, through run->mmio.data; the capture’s 22 exits (talos and straylight) move 11 bytes out and 11 status bytes in. The copy is small and the crossing is the cost, which is the number exercise (e) turns into 2048.

Lab

make lab CH=21
make lab CH=21 IMPL=mine

labs/ch21/Makefile is chapter 20’s with two changes. It calls ../ch20/build.sh overlay out, so the kernel, BusyBox and kernel headers come from the same hp/ch20 cache, and a host that has run chapter 20 builds nothing new here. And it assembles the payload itself from payload.S instead of copying one from ember/. The VMM is labs/ch21/vmm.c, chapter 20’s file with the device model, the exit-loop case and the counter added and the data page removed; the ch21-init script in overlay/init is chapter 20’s.

IMPL=mine replaces the body of mmio_uart with printf("MINE: mmio stub\n"); return -1;. The exit loop then falls through to “no device here” on the first LSR read, and the run diverges there:

 vmm: pc=0x80000000 mode=S
-hi from VS
-vmm: KVM_RUN exit 24 (KVM_EXIT_SYSTEM_EVENT) type 1 (SHUTDOWN) ndata 1
-vmm: mmio exits 22
-vmm: guest a7=0x53525354 a6=0x0
-vmm: PASS
-vmm rc=0
+MINE: mmio stub
+vmm: KVM_RUN exit 6 (KVM_EXIT_MMIO) read gpa 0x10000005 len 1: no device here
+vmm: mmio exits 0
+vmm: guest a7=0x0 a6=0x0
+vmm: FAIL
+vmm rc=1

(the tail of the diff of capture.txt against the run). Writing the two registers is the lab.

With the reference the capture is:

=== lab begin
/dev/kvm
vmm: KVM_GET_API_VERSION 12
vmm: memory slot 0: 0x200000 bytes at gpa 0x80000000
vmm: payload 0x54 bytes at gpa 0x80000000
vmm: pc=0x80000000 mode=S
hi from VS
vmm: KVM_RUN exit 24 (KVM_EXIT_SYSTEM_EVENT) type 1 (SHUTDOWN) ndata 1
vmm: mmio exits 22
vmm: guest a7=0x53525354 a6=0x0
vmm: PASS
vmm rc=0
=== lab end

The 22 was observed before it was explained: the payload prints 11 bytes (hi from VS is ten characters and the newline), and with a model that always reports empty each byte is one LSR read and one THR write, two exits. The ecall is not an MMIO exit: it ends the run as the system event on the line above. The capture pins the exit reasons, the printed string, the exit count and a7 and a6; it does not pin the guest-physical addresses of the exits or their widths (the exercises read those) beyond the payload’s byte count, 0x54, the size of the assembled file. The run on talos and two runs on straylight are byte-identical to capture.txt.

Further reading

results matching ""

    No results matching ""