19. Nested paging

Two walks, two fault classes Left column, the VS-stage: a guest virtual address passes through vsatp, which is zero (Bare) in chapter 19, and comes out as the guest-physical address. An arrow carries that address to the right column, the G-stage: hgatp with MODE 8 (Sv39x4) selects a 16 KiB root table indexed by 11 bits, then a 4 KiB level indexed by 9 bits, then a 4 KiB level indexed by 9 bits, then a leaf entry that needs U=1, and the walk ends at a supervisor physical address. Below, side by side, the two fault classes: a VS-stage page fault (codes 12, 13, 15) goes to VS if hedeleg says so, the guest's problem; a guest-page fault (codes 20, 21, 23) never goes to VS and reaches HS through medeleg, the hypervisor's problem. VS-stage, vsatp G-stage, hgatp guest virtual address vsatp = 0: Bare guest-physical address hgatp: MODE=8, Sv39x4 root, 16 KiB: VPN[2] 11b L1, 4 KiB: VPN[1] 9b L0, 4 KiB: VPN[0] 9b leaf PTE: needs U=1 supervisor physical address Chapter 19: vsatp = 0, so GVA = GPA and one walk runs. The guest's own tables sit in guest-physical memory: each read of them is G-stage translated too. When a walk fails VS page fault: 12, 13, 15 to VS if hedeleg says so the guest's problem guest-page fault: 20, 21, 23 never VS; HS via medeleg the hypervisor's problem Two walks; a guest page fault is not a hypervisor page fault

Why this layer exists

Chapter 7 put a program under the kernel with one page table and the U bit. Chapter 18 said what a hypervisor needs beyond that: a way to run a kernel at full speed and still own the machine. The part of that problem this chapter solves is memory. A guest kernel builds page tables whose entries it believes name physical memory, and it believes that memory starts where its platform says and is as large as it was told. The hypervisor cannot let that be true of the real memory. The guest’s “physical” pages have to be pages the hypervisor chose, and the guest must not be able to name any other. Before hardware had a second translation stage, the hypervisor got there by trapping every write to the guest’s satp and every edit of its page tables, and keeping a shadow page table of its own that composed the two mappings. Chapter 18 met the hook for that technique, the hstatus bit that makes the guest’s satp accesses trap. The second stage replaces the shadow table with a second hardware walk.

This is hearth chapter zero: the first place in the book where code the reader wrote runs a guest. HS-mode, which is ember after its drop to S on a hart that has the H-extension (chapter 18), builds an identity map for a guest of two pages, executes sret into VS-mode, and reads the guest’s exit out of the trap frame. The guest is eleven instructions; there is no guest kernel, no device and no interrupt. What the lab shows is three things that stay true when the guest is Linux: a page table the guest does not own, a fault class the guest never sees, and a trap entry (chapter 5’s trap_entry, unchanged) that catches the guest’s exit. Chapter 20 gives the same job to KVM and runs the same payload bytes; there a memory slot replaces gmap, and KVM builds the G-stage from it a page at a time, on the guest’s faults.

Mechanism

Section numbers and quotes are from the privileged spec, hypervisor chapter, v20260120 (https://docs.riscv.org/reference/isa/v20260120/priv/hypervisor.html), fetched 2026-10-01T05:26Z, with the machine chapter (…/priv/machine.html) and the supervisor chapter (…/priv/supervisor.html, §11.x) from the same fetch. Quotes are verbatim.

Two stages, three addresses

When V=1 every memory access goes through two translations. The terms below are defined here; chapter 18’s modes and V are used as defined there.

For any virtual memory access, the original virtual address is converted in the first stage by VS-level address translation, as controlled by the vsatp register, into a guest physical address. The guest physical address is then converted in the second stage by guest physical address translation, as controlled by the hgatp register, into a supervisor physical address. The two stages are known also as VS-stage and G-stage translation. (§14.1.5)

So there are three kinds of address. A guest virtual address (GVA) is what a guest instruction names. A guest-physical address (GPA) is what the guest’s own page tables, or no page table at all, turn it into; it is the guest’s idea of physical memory. A supervisor physical address is a real address on the bus. The VS-stage is the walk the guest controls (its vsatp, its tables, which sit in guest-physical memory). The G-stage is the walk the hypervisor controls (hgatp, tables in real memory). The spec adds a sentence that decides this lab’s shape: “Although there is no option to disable two-stage address translation when V=1, either stage of translation can be effectively disabled by zeroing the corresponding vsatp or hgatp register.” The payload has no page tables, so vsatp is zero (MODE 0, Bare, as in satp): its GVAs are GPAs, and one walk, the G-stage, does all the work. The guest’s own tables, when it has them, are read through the G-stage as well: “When V=1, memory accesses that would normally bypass address translation are subject to G-stage address translation alone. This includes memory accesses made in support of VS-stage address translation, such as reads and writes of VS-level page tables.” (§14.1.5). A guest page-table walk of three levels therefore costs three G-stage walks of its own, one per level, plus one for the final address.

The two walks fail in two different ways, and which one failed decides who hears about it. A VS-stage failure is an ordinary page fault (codes 12, 13, 15). It goes to VS if hedeleg says so: Table 2 lists bits 12, 13 and 15 as writable, so the hypervisor may hand it to the guest, which is the guest’s own memory management at work. A G-stage failure is a guest-page fault: code 20 for an instruction fetch, 21 for a load, 23 for a store or atomic. Table 2 lists bits 20 to 23 as read-only zero, and §14.1.5.2 says the same from the other side: “Guest-page-fault traps may be delegated from M-mode to HS-mode under the control of CSR medeleg, but cannot be delegated to other privilege modes.” A guest never sees one. The guest believes it has memory at that address; the hypervisor decides it does not, and only the hypervisor is told. The figure’s lower half is this rule: a guest page fault is not a hypervisor page fault, because the hypervisor’s own page faults are the ordinary kind, from its own satp, and these are neither.

Sv39x4: the G-stage table

hgatp selects the G-stage scheme with its MODE field (Table 5; bits 63:60 on RV64, with the page number in bits 43:0, as the pinned Linux tree’s arch/riscv/include/asm/csr.h:167–170 has them, the tree chapter 15 builds): 0 is Bare (“guest physical addresses are equal to supervisor physical addresses”), 8 is Sv39x4. Sv39x4 is Sv39, the scheme chapter 4 built, with the incoming address widened by two bits:

To accommodate the 2 extra bits, the root page table (only) is expanded by a factor of four to be 16 KiB instead of the usual 4 KiB. Matching its larger size, the root page table also must be aligned to a 16 KiB boundary instead of the usual 4 KiB page boundary. Except as noted, all other aspects of Sv32, Sv39, Sv48, or Sv57 are adopted unchanged for G-stage translation. (§14.1.5.1)

The arithmetic: a guest-physical address is 41 bits (“Address bits 63:41 must all be zeros, or else a guest-page-fault exception occurs”), so the top-level index, VPN[2], is bits 40:30, eleven bits, not nine. 211×8 bytes=163842^{11} \times 8\ \text{bytes} = 16384 is the 16 KiB root; the two lower levels are Sv39’s, 512 entries and 4 KiB each, indexed by bits 29:21 and 20:12, with the low twelve bits the page offset. hgatp holds the root’s physical page number; because the root is 16 KiB aligned, “the lowest two bits of the physical page number (PPN) in hgatp always read as zeros”. A page at guest-physical 0x80401000, as an example, has VPN[2] = 2, VPN[1] = 2, VPN[0] = 1: the same bits Sv39 would index with, except that the top index could now run to 2047. The PTE format is not changed: “G-stage address translation uses the identical format for PTEs as regular address translation, even including the U bit”.

ember’s root is a static array, unsigned long groot[2048] aligned to 16384. The two lower levels come from kalloc_page(), each a zeroed 4 KiB page.

The leaf: U, A and D

A G-stage leaf needs one flag that no chapter-4 leaf needed in this role, and it is the one the first mistake forgets. §14.1.5.1 says G-stage translation is Sv39’s algorithm, except that, among other things, “when checking the U bit, the current privilege mode is always taken to be U-mode”, and, in the next paragraph, “all memory accesses (including those made to access data structures for VS-stage address translation) are considered to be user-level accesses, as though executed in U-mode”. In Sv39 a U-mode access to a page whose U bit is clear is a page fault. In the G-stage every access is a U-mode access, so a leaf without U faults for every guest access, the fetch included, however many of R, W and X it carries. gmap sets PTE_U on every leaf for that reason, and exercise (a) removes it.

Pointer entries (non-leaf) carry V alone, as in Sv39. The A and D bits are set at creation: the supervisor chapter (§11.1.3.1) defines two schemes, “The Svade extension: when a virtual page is accessed and the A bit is clear, or is written and the D bit is clear, a page-fault exception is raised”, and, without Svade, the hardware updates the bits. A G-stage fault of that kind is a guest-page fault. Setting A and D in the entry makes the lab independent of which scheme the hart implements. The G bit has no defined use in G-stage entries, and software is told to leave it clear.

hgatp and the fence

hgatp is written with MODE 8 and the root’s page number. The VMID field, which tags cached translations per guest, is left zero: “The number of VMID bits is UNSPECIFIED and may be zero”, and the lab runs one guest. Then:

Note that writing hgatp does not imply any ordering constraints between page-table updates and subsequent G-stage address translations. If the new virtual machine’s guest physical page tables have been modified, or if a VMID is reused, it may be necessary to execute an HFENCE.GVMA instruction (see 14.1.3.2. Hypervisor Memory-Management Fence Instructions) before or after writing hgatp. (§14.1.2.10)

hfence.gvma zero, zero is the form with both operands x0: no address and no VMID named, so it covers every guest-physical address and every VMID. Here it is required, not optional: §14.1.3.2 says “If hgatp.MODE is changed for a given VMID, an HFENCE.GVMA with rs1=x0 (and rs2 set to either x0 or the VMID) must be executed to order subsequent guest translations with the MODE change—even if the old MODE or new MODE is Bare.” The machine resets with hgatp.MODE zero, Bare, so the lab’s write is a Bare to Sv39x4 change, and the fence also orders the stores that built the table before the first G-stage walk.

Entering the guest

Everything hyp_lab writes before sret is the guest’s initial state. In order:

  • hedeleg = 0 and hideleg = 0: nothing a guest does is handled by the guest; every trap from VS comes to HS. This is the only choice for a payload that has no trap handler, and for the bits that matter here it is not a choice: Table 2 makes hedeleg bits 9 to 11 and 20 to 23 read-only zero (chapter 18).
  • vsatp = 0: the VS-stage is Bare. vsstatus = 0 and vstvec = 0: replicas of sstatus and stvec (chapter 18), zeroed, because the guest never reads or traps through them.
  • hstatus = VSXL | SPV. SPV (bit 7) is the entry switch of chapter 18: sret at V=0 sets V to SPV. VSXL (bits 33:32, csr.h:141–142) selects VSXLEN, the guest’s register width: “VSXL is a WARL field that is encoded the same as the MXL field of misa”, and the machine chapter’s Table 1 encodes 64 bits as 2, so HSTATUS_VSXL64 is 2UL << 32.
  • sstatus.SPP = 1 and sstatus.SPIE = 0. sret in HS-mode reads two bits to choose the mode it enters: “SRET first determines what the new privilege mode will be according to the values in hstatus.SPV and sstatus.SPP, as encoded in Table 10. SRET then sets hstatus.SPV=0, and in sstatus sets SPP=0, SIE=SPIE, and SPIE=1. Lastly, SRET sets the privilege mode as previously determined, and sets pc=sepc.” (§14.1.6.4). Table 10 maps (SPV=1, SPP=1) to VS-mode. SIE=SPIE then loads HS’s own interrupt-enable bit from the cleared one. priv.h names only the mstatus positions, MSTATUS_SPP and MSTATUS_SPIE; the bits sit at the same places in sstatus.
  • sepc = code: the guest-physical address of its first instruction, which is also its physical address because the map is an identity map.
  • hyp_enter(data): the first argument register, a0, carries the data page’s guest-physical address into the guest; sret leaves every other register as it was.

Which side of V the lab starts on. All of this assumes the hart is in HS, V=0, when hyp_lab runs. drop_to_s does not set mstatus.MPV, and the machine chapter does not specify its reset value (chapter 18 says so); the book depends on QEMU’s. The proof is the first write: a hypervisor CSR write from a hart with V=1 would be a virtual instruction exception, and one from a hart without the extension would be an illegal instruction. Neither happens, and csrw hgatp is the line that would show it. (Without the extension the run does not print an error: the illegal write enters trapper, whose first act reads hstatus, which traps again; the image hangs with nothing after the allocator line, exercise (f).) misa would show whether the extension is implemented but is M-only, and the S-mode kernel cannot read it, so the lab does not look.

The interrupt mask. The rule for when an interrupt reaches HS is in §14.1.2.3: “An interrupt i will trap to HS-mode whenever all of the following are true: (a) either the current operating mode is HS-mode and the SIE bit in the sstatus register is set, or the current operating mode has less privilege than HS-mode; (b) bit i is set in both sip and sie, or in both hip and hie; and (c) bit i is not set in hideleg.” With V=1 the mode is VS or VU, less privileged than HS, so clause (a) holds whatever sstatus.SIE says; the gate that is left is clause (b), HS’s own sie. The M shim’s timer (chapter 6) raises a supervisor software interrupt every second; if sie.SSIE were set, the tick would be taken in the middle of the guest, with hstatus.SPV set. hyp_lab therefore clears sie bit 1 before entering. In the committed stage nothing sets that bit, so the clear changes nothing, and the lab ends in microseconds, long before a tick. It is there for the reader’s next stage. Observed on talos in a scratch copy with the payload spinning for a few seconds and timer_on() (chapter 6) called before the guest: without the mask, S: tick 0x1 printed from inside the guest; with it, nothing. The exit is the same in both.

Which traps come to HS

A trap taken while V=1 starts at M and follows chapter 18’s delegation chain (§14.1.6.2): medeleg passes it to HS, then hedeleg to VS. With hedeleg = 0, the question is whether medeleg sends it to HS. trap_init_m delegates bits 2, 3, 8, 12, 13 and 15 (chapter 5), which says nothing about codes 10 or 20 to 23. Without them a VS-mode ecall goes to the M shim: observed on talos, a build with the gated line below made empty stops at M: trap cause 0xa mtval=0x0 and the guest’s exit never reaches hyp_trap. So a VS ecall reaches HS only through medeleg bit 10, and the five bits the chapter adds are 10 (environment call from VS), 20, 21 and 23 (the guest-page faults), and 22 (virtual instruction). Like every medeleg write, this one happens in trap_init_m, from M, before the drop: from S the write is itself illegal (chapter 5).

The exit: an ecall that asks

A guest with no device has no way to say it is done. It cannot write the test finisher at 0x100000; the guest-physical map has two pages and the finisher is not in it, and a store there would be a guest-page fault, which is an error, not an exit. ecall is the one instruction that traps whatever the G-stage holds, and the RISC-V convention for what to ask is already written down. The SBI (chapter 18) fixes the registers: the extension ID goes in a7, the function ID in a6, arguments in a0 onward, then ecall. The System Reset extension has the ID 0x53525354, the ASCII bytes of “SRST”, and function 0, sbi_system_reset(reset_type, reset_reason), with reset_type 0 meaning shutdown (SBI specification v3.0, System Reset Extension). The extension’s text says who answers: “When supervisor software is running inside a virtual machine, the SBI implementation is provided by a hypervisor.” Chapter 18 quoted the same fact from the privileged side (§14.1).

The payload therefore loads a7 = 0x53525354, a6 = 0, a0 = 0 (shutdown), a1 = 0 (reason: none), and executes ecall. From VS that is cause 10. a1 is overwritten by the call’s own argument, so the proof that the guest’s load saw its own store is the other register, t1: the payload loads into t1 before it builds the call, and trap_entry saved t1 in the frame, where hyp_trap reads tf->t1. The trap frame is chapter 5’s. The hardware did not switch register files, so the guest’s registers were the hart’s registers and trap_entry saved them like any other trap’s.

What a guest-page fault reports

scause has the code. stval has “the faulting guest virtual address as usual”, and htval has the faulting guest-physical address, shifted right by two: “When a guest-page-fault trap is taken into HS-mode, htval is written with either zero or the guest physical address that faulted, shifted right by 2 bits” (§14.1.2.8). The “either zero or” is the spec’s licence for an implementation to report nothing; QEMU reports the address. hyp_trap prints (htval << 2) & 0xfff, the offset within the page, not the page: the page is wherever kalloc_page put it, and the capture pins behaviour, not layout. The two address bits shifted out are, by the spec, “ordinarily the same as the least-significant two bits of the faulting virtual address in stval”; the lab’s accesses are 8-byte aligned so they are zero. A fault inside the guest’s own page-table walk would report the address of the table entry that could not be read, not the address the guest asked for (§14.1.2.8); vsatp is Bare here, so that case cannot arise.

The sp the guest chooses

hyp_enter is sret and nothing else, so the guest starts with HS’s sp, gp, tp and every other register as hyp_lab left them, and from the first instruction the registers are the guest’s to change. That matters at the first trap. trap_entry does addi sp, sp, -280 and stores the frame through whatever sp then holds, under HS’s own satp; nothing checks that it is a stack. Whether the guest can reach that page through its G-stage is irrelevant: the store is HS’s, so a guest can aim HS’s frame store anywhere in HS’s address space by setting sp. Observed on talos in a scratch copy: a payload that begins li sp, 0x87ffe0d0 (the data page’s address plus 280 minus 72, in this layout, so that the frame’s a0 slot lands on the first word of the data page) ends with H: guest read back t1=0x600d5eed and H: data page holds 0x0: HS’s own trap entry overwrote the word the guest had stored, with the guest’s a0. The payload never wrote 0x0 there. Chapter 7’s sscratch swap (user_vec opens with csrrw sp, sscratch, sp, so sp becomes a kernel stack the kernel parked) is therefore mandatory for guest entry, not optional, and hearth adopts it in Part VII.

What EPT and NPT change

Nothing structural. Intel’s EPT and AMD’s nested page tables are the same idea under other names: a second table, rooted in a field of the guest’s control structure (the VMCS or VMCB of chapter 18) instead of hgatp, with entries in the format of the first stage, walked on every guest access, with a fault class of its own that goes to the hypervisor and never to the guest (an EPT violation on Intel, a nested page fault on AMD). Where they differ from Sv39x4 is detail: permissions and memory types in the entry, accessed and dirty bits that can be turned off, a different root size. The names of the SDM and APM chapters are in Further reading; nothing else in this book depends on them.

Walkthrough

The payload, with the SBI call from the last section. ember/payload.S is built by its own rule in ember/Makefile: linked at address 0, flattened with objcopy to build/payload.bin, and embedded by payload_blob.S the way user_blob.S embeds a user program.

# The guest. Position-independent, no stack, no devices. It touches one
# data page through the G-stage (a0 is its guest-physical address),
# proves the read-back in t1, and asks the hypervisor to stop through
# the SBI system-reset call — which is an ecall, code 10, from VS.
    .section .text
    .globl _start
_start:
    li   t0, 0x600d5eed
    sd   t0, 0(a0)
    ld   t1, 0(a0)
    li   a7, 0x53525354      # SBI extension SRST ("SRST")
    li   a6, 0               # fid 0: sbi_system_reset
    li   a0, 0               # reset_type: shutdown
    li   a1, 0               # reset_reason: none
    ecall
1:  j    1b

The payload is eleven instructions and 0x2c bytes: each li of a 32-bit constant expands to lui plus addiw, so the two of them are four; li a6, li a0 and li a1 are one each; with sd, ld, ecall and the j that spins, eleven. riscv64-linux-gnu-objdump -d ember/build/payload.elf shows them, and the capture’s payload bytes=0x2c is the same count times four.

gmap maps one page. The three indices are the walk of the Mechanism section; each level without an entry yet gets a fresh zeroed page from kalloc_page, entered as a pointer (V alone); the leaf is the physical page number shifted into the PTE with the caller’s R/W/X and the four flags every leaf carries.

/*
 * Map one 4 KiB guest-physical page to a physical page in the G-stage
 * table. Same PTE format as Sv39 (§14.1.5: "identical format"), one
 * more root bit pair, and every leaf carries U: G-stage accesses are
 * always treated as user-level accesses.
 */
static void gmap(unsigned long gpa, unsigned long pa, unsigned long flags)
{
    unsigned long *t = groot;
    unsigned long i2 = (gpa >> 30) & 0x7ff;     /* 11 bits: Sv39's 9 + 2 */
    unsigned long i1 = (gpa >> 21) & 0x1ff;
    unsigned long i0 = (gpa >> 12) & 0x1ff;
    unsigned long *t1, *t0;

    if (!(t[i2] & PTE_V)) {
        unsigned long p = kalloc_page();
        if (!p) {
            uart_puts("H: gmap: out of pages\r\n");
            halt(1);
        }
        t[i2] = ((p >> 12) << 10) | PTE_V;         /* pointer: V only */
    }
    t1 = (unsigned long *)((t[i2] >> 10) << 12);
    if (!(t1[i1] & PTE_V)) {
        unsigned long p = kalloc_page();
        if (!p) {
            uart_puts("H: gmap: out of pages\r\n");
            halt(1);
        }
        t1[i1] = ((p >> 12) << 10) | PTE_V;
    }
    t0 = (unsigned long *)((t1[i1] >> 10) << 12);
    t0[i0] = ((pa >> 12) << 10) | flags | PTE_U | PTE_A | PTE_D | PTE_V;
}

hyp_enter is the whole of the entry; everything it relies on is set up by hyp_lab (its body is not a listing: it is the sequence the Mechanism section walked, in the same order).

# sret with hstatus.SPV=1 and sstatus.SPP=1 (set by hyp_lab) leaves HS
# for VS at sepc. Every other register is whatever HS left in it. The
# guest's sp is the register trap_entry will store HS's frame through,
# with HS's own satp: a guest can aim that store anywhere in HS's address
# space (chapter 19, "The sp the guest chooses"). Chapter 7's sscratch swap
# is mandatory for guest entry; hearth adopts it.
    .section .text
    .globl hyp_enter
hyp_enter:
    sret

hyp_trap runs at the top of trapper, through the gated branch below, before chapter 5’s illegal-instruction, tick, device and system-call branches (trap.c and main.c also include hyp.h under the same HP_CH >= 19 guard). A trap is the guest’s if hstatus.SPV is set: the hardware sets it on every trap into HS from V=1 (Table 10), and sret cleared it on the way in, and a trap taken from V=0 writes SPV=0 (Table 10), so a trap that HS itself takes, as chapter 5’s illegal-instruction skip does, leaves it clear. hyp_trap owns every synchronous trap with SPV set: the exit, the guest-page faults and the virtual instruction exception have their own lines, and any other cause prints H: guest trap cause=… sepc offset=… and stops. Interrupts (scause bit 63) return 0 and take the branches they always took. The placement matters: an earlier version called hyp_trap after those branches, and a guest whose first word was .word 0xffffffff was caught by chapter 5’s illegal-instruction branch, which skips the instruction and srets back into the guest, so HS silently emulated it as a no-op (exercise (g)).

/* Called first from trapper() when HP_CH >= 19, before every other
 * branch: a trap from VS is one whose hstatus.SPV is set (V was 1 when it
 * was taken), and every synchronous one is this function's. Interrupts
 * (scause bit 63) return 0 and take trapper()'s own paths. */
int hyp_trap(struct trapframe *tf)
{
    unsigned long cause = csr_read(scause);

    if (!(csr_read(hstatus) & HSTATUS_SPV))
        return 0;                          /* not the guest's */
    if (cause & MCAUSE_INT)
        return 0;                          /* an interrupt: trapper's */

    if (cause == CAUSE_ECALL_VS) {
        uart_puts("H: VS ecall ext=");
        uart_puthex(tf->a7);
        uart_puts(" fid=");
        uart_puthex(tf->a6);
        uart_puts(" type=");
        uart_puthex(tf->a0);
        uart_puts("\r\n");
        uart_puts("H: guest read back t1=");
        uart_puthex(tf->t1);
        uart_puts("\r\n");
        uart_puts("H: data page holds ");
        uart_puthex(*(unsigned long *)guest_data);
        uart_puts("\r\n");
        uart_puts("PASS\r\n");
        halt(0);
    }
    if (cause == CAUSE_GPF_INST || cause == CAUSE_GPF_LOAD ||
        cause == CAUSE_GPF_STORE) {
        uart_puts("H: guest-page fault code=");
        uart_puthex(cause);
        uart_puts(" gpa offset=");
        uart_puthex((csr_read(htval) << 2) & 0xfff);
        uart_puts("\r\n");
        halt(1);
    }
    if (cause == CAUSE_VIRT_INST) {
        uart_puts("H: virtual instruction exception\r\n");
        halt(1);
    }
    /* Any other synchronous trap from the guest is not one HS emulates:
     * stop, rather than let a lower branch of trapper() resume it. */
    uart_puts("H: guest trap cause=");
    uart_puthex(cause);
    uart_puts(" sepc offset=");
    uart_puthex(csr_read(sepc) & 0xfff);
    uart_puts("\r\n");
    halt(1);
    return 1;
}

The two gated branches in ember/trap.c, quoted as they stand. The first is the delegation (it sits in trap_init_m, after chapter 5’s medeleg value and before the write); the second is the call into hyp_trap, placed at the top of trapper, before chapter 5’s branches.

#if HP_CH >= 19
    /* VS ecall and the guest-page faults come to HS (chapter 19). */
    medeleg |= (1UL << 10) | (1UL << 20) | (1UL << 21) | (1UL << 22) | (1UL << 23);
#endif
#if HP_CH >= 19
    if (hyp_trap(tf))
        return;
#endif

The chapter’s boot stage in ember/main.c: chapter 13’s prefix up to the allocator, then the hypervisor instead of init. The disk, the console and the file system are not started, so the lab needs no input.txt bytes and no drive.

mem_init();
trap_init();
uart_puts("S: kernel up\r\n");
kalloc_init();
hyp_lab();              /* builds the G-stage, enters VS; never returns */

The Makefile gates the new objects by chapter (hyp.c hyp.S payload_blob.S link only when HP_CH >= 19) so that every earlier capture is unchanged: linking later files into an earlier image moves symbols.

Exercises

Each exercise below was run on talos (QEMU 11.1.1, riscv64-linux-gnu- GCC 16.2.1) in a scratch copy of ember/, one edit at a time, with -cpu rv64,h=true unless it says otherwise. hyp_trap prints codes in hex: 0x14 is 20, 0x15 is 21, 0x17 is 23.

(a) Remove PTE_U from gmap’s leaf and run. Which fault, at what offset, and why with R and X set?

Answer

Observed: H: guest-page fault code=0x14 gpa offset=0x0, code 20, the instruction fetch at the first byte of the code page. R and X do not help: by the U rule of the Mechanism section every G-stage access is a U-mode access. It is the same fault the lab’s IMPL=mine run gets from an empty map, and nothing in the fault tells a missing leaf from a leaf the access may not use: both are code 20 at the same offset.

(b) Map the data page R only. Which fault does the payload take, and at which instruction?

Answer

Observed: H: guest-page fault code=0x17 gpa offset=0x0, code 23, the store/AMO guest-page fault, with the payload’s first access to the data page, its sd, as the instruction that took it (the fetch of the code page succeeded, so the fault is not the code’s). Offset 0 is the data page’s address plus zero: sd t0, 0(a0). The load that would have followed never ran. Permissions are checked in the G-stage the same way as in the VS-stage (§14.1.5.1: “Access type permissions—readable, writable, or executable—are checked during G-stage translation the same as for VS-stage translation”); a store to a read-only guest page is reported to the hypervisor as a guest-page fault, which is the mechanism dirty tracking and copy-on-write for guest memory are built on.

(c) Make the payload load from the page after the data page. What does it do, and what does a load from an address that is certainly unmapped report?

Answer

The first attempt, li t2, 0x1008, add t2, t2, a0, ld t1, 0(t2) (the load offset is too large for the instruction’s 12-bit immediate, hence the add), did not fault: t1 was 0x13b700553023, the payload’s own code word at byte 8. kalloc_init pushes the pages onto the free list from the floor upward, so the list head is the highest page and kalloc_page hands pages out downward: the code page, allocated first, sits directly above the data page, allocated second, and is mapped. The page after the data page is not an unmapped page, and it is the allocator’s layout that decides, not anything in the map. With li t2, 0x2008 and ld t1, 0(t2) instead (a guest-physical address below DRAM that gmap never maps), the payload takes H: guest-page fault code=0x15 gpa offset=0x8: code 21, the load guest-page fault, and an offset of 8, because htval carries the address of the access, not the start of the page. The two low address bits are not in htval; 0x2008’s are zero.

(d) Set hstatus.VTSR (bit 22) before entering and put an sret at the start of the payload. What arrives, and what does hyp_trap print?

Answer

Observed: H: virtual instruction exception. Chapter 18’s table: with VTSR=1 a VS-mode sret raises a virtual instruction exception, code 22 (§14.1.2.1). medeleg bit 22, in the gated branch, is what lets it reach HS; hedeleg bit 22 is read-only zero (Table 2), so it could not have gone anywhere else. With VTSR=0, the same sret would not have trapped at all: it would run on vsstatus and vsepc (chapter 18’s outcome 1) and, with both zero, resume the guest at address 0, in VU-mode (vsstatus.SPP=0 on entry, Table 11, so the sret returns to VU). The payload does not get to find out: observed with VTSR clear, the next event is H: guest-page fault code=0x14 gpa offset=0x0, the fetch at guest-physical 0, which is unmapped.

(e) Replace the three-level map with one 1 GiB leaf at the root covering 0x80000000 to 0xC0000000 (root index 2), pass the address of that entry to the guest in a0, and have the payload read it. What does the guest see, and what does chapter 14’s budget say about the leaf?

Answer

With groot[2] = ((0x80000000 >> 12) << 10) | R | W | X | U | A | D | V and the payload’s sd removed so that t1 is the guest’s read of its own G-stage entry, observed: H: guest read back t1=0x200000df. That is the leaf itself: PPN field 0x80000 shifted to bit 10, flags 0xdf. The guest is reading the hypervisor’s page table, because groot is in the image at 0x80000000-and-up and the leaf maps all of DRAM, the hypervisor’s text, data, stacks and tables included, readable and writable. On the budget: what is shared is everything, the guest’s view of memory is the host’s; who is trusted now includes the guest, which can rewrite groot and so its own map (the W bit on a leaf that covers the table is the whole attack); where the copy is disappears, which is why nothing had to be copied for the guest to read it. A superpage is the cheapest map to build and walk, and it gives the guest the host.

(f) Run make lab CH=19 with -cpu rv64,h=false in extra.mk. What does it print, and how does it end?

Answer

QEMU accepts the flag. Observed on talos: nothing prints after S: kalloc 0x80400000..0x88000000 pages=0x7c00, not even H: payload bytes, and QEMU runs until timeout kills it (exit 124). With -d int -D log the first trap is csrw hgatp (tval 0x68079073: csrw with CSR number 0x680), an illegal instruction in S-mode on a hart without the extension. Then csrrs x15, hstatus, x0 (tval 0x600027f3, CSR 0x600, hstatus) traps, and traps again at the same address, forever. The cause is the placement from the last exercise: every illegal-instruction trap enters trapper, whose first act is hyp_trap’s csr_read(hstatus), itself illegal without H, so the trap re-enters trap_entry 280 bytes lower on the same stack, without end. (Before hyp_trap moved to the top, chapter 5’s handler skipped each H write in silence and the payload ran as plain S code, ending at M: trap cause 0x9.) The lesson: from chapter 19 on every trap path reads hstatus, so the image has no H-less fallback. The evidence that the extension is on is reaching H: payload bytes, and then the three H: result lines.

(g) Put .word 0xffffffff, an illegal instruction, at the start of the payload. What happens, and what did it do before hyp_trap moved to the top of trapper?

Answer

Now: H: guest trap cause=0x2 sepc offset=0x0 and exit 1: cause 2, illegal instruction, taken with hstatus.SPV set, at offset 0 of the code page, is not a trap HS emulates. Before the move (the committed first version, which called hyp_trap after the other branches), the run printed S: trap sepc=0x87fff000 scause=0x2 stval=0xffffffff and then the normal exit lines and PASS: chapter 5’s illegal-instruction branch skipped the guest’s instruction and sreted back into it. HS had silently run the guest’s illegal instruction as a no-op. The lesson is the order of the dispatch: every branch of a handler that predates the guest answers for the guest too, unless the guest’s check comes first.

Lab

make lab CH=19
make lab CH=19 IMPL=mine

ember/ is the reference; labs/ch19/mine/ is a copy of it in which gmap is a stub that prints MINE: gmap stub and maps nothing. labs/ch19/extra.mk passes -cpu rv64,h=true explicitly: this QEMU accepts h=true and h=false, and the lab never relies on the default.

The first thing to observe is the failure. IMPL=mine prints the common prefix, then:

+MINE: gmap stub
+MINE: gmap stub
 H: payload bytes=0x2c entering VS
-H: VS ecall ext=0x53525354 fid=0x0 type=0x0
-H: guest read back t1=0x600d5eed
-H: data page holds 0x600d5eed
-PASS
+H: guest-page fault code=0x14 gpa offset=0x0

(the diff of capture.txt against the run; the stub runs twice, once for each page). The guest’s first fetch finds no G-stage entry: code 0x14, 20, the instruction guest-page fault, at offset 0. Before gmap has a body the guest cannot take a single step, and the fault says why in the spec’s terms, not in ember’s. Writing the three index lines, the table allocations and the leaf is the lab; the failing run is how you know a leaf without U and a missing leaf both look the same from HS (exercise (a)).

With the reference the capture is the common prefix (chapters 2 to 9, through the allocator line), then:

H: payload bytes=0x2c entering VS
H: VS ecall ext=0x53525354 fid=0x0 type=0x0
H: guest read back t1=0x600d5eed
H: data page holds 0x600d5eed
PASS

The capture pins the payload’s size, the registers it sent (a7, a6, a0), the value the guest read back from its own store, and the value HS reads in the same page through its own address, which is the same page. It does not print the address of the guest’s pages or of the page-table pages (they are whatever kalloc_page returned), and on a fault it prints a page offset, not a page. The run is deterministic: two runs on talos are byte-identical to each other and to capture.txt.

Further reading

results matching ""

    No results matching ""