4. Memory as the CPU sees it

Why this layer exists

Between the address an instruction names and the address the memory system decodes sits a translation, and the hardware performs it on every access using tables the kernel wrote. The part of the hart that does it is the memory-management unit (MMU). It turns a virtual address, the one a load, a store or an instruction fetch names, into a physical address, the one the bus decodes. Whoever writes the tables decides what every access below them can reach. That is how a kernel isolates one process from another from chapter 7 on, and how a hypervisor will isolate a guest: the guest’s own kernel writes tables it believes are final, and the hypervisor owns a second set underneath that the guest never sees. Chapter 19 builds the second set (the G-stage, in the term of the H extension, which chapter 3 names and chapter 18 builds on). wick gets it already built, by KVM, which on an x86 host programs Intel’s EPT or AMD’s NPT, the same second set under other names.

Nested translation is promised here and not built. What is built is one walk, derived from the privileged specification field by field, because the second set is that algorithm with a short list of changes, which the last Mechanism section names. The lab then turns translation on and proves it by executing through a second mapping. The side runs under labs/ch04/ex/ break the hardware’s assumptions one at a time and keep the transcripts.

Mechanism

Two kinds of address, and the register that chooses

A physical address is what the memory system decodes: DRAM at 0x80000000, the UART at 0x10000000, the map chapter 2 drew. A virtual address is what an instruction names. When translation is off the two are equal, which is how chapters 2 and 3 ran. One CSR chooses. satp, the supervisor address translation and protection register, holds three fields on RV64:

bits field meaning
63:60 MODE 0 is Bare (no translation), 8 is Sv39, 9 is Sv48, 10 is Sv57
59:44 ASID address-space identifier, a tag naming which address space a cached translation belongs to; up to 16 bits on Sv39 (the spec’s ASIDMAX) and possibly none
43:0 PPN physical page number of the root table

A page is an aligned 4096-byte unit of address space; the spec says it “settled on a conventional page size of 4 KiB”. A physical page number (PPN) is a physical address with its low 12 bits dropped, so a table at 0x80200000 has PPN 0x80200. Writing satp switches the world: the next instruction is fetched, and every access after it is made, under the new MODE and root.

Four consequences follow before any table exists.

First, translation applies to S-mode and U-mode only. The spec’s wording is that “the satp CSR is considered active when the effective privilege mode is S-mode or U-mode.” M-mode uses physical addresses throughout, which is why the M shim of chapter 3 can print on the UART while S-mode runs translated. (mstatus.MPRV lets M-mode loads and stores borrow another mode’s translation; ember never sets it, and instruction fetches ignore it.)

Second, the hardware reads the tables with physical addresses. The root’s address is satp.PPN times 4096, and every pointer inside a table is a PPN. The kernel that edits those tables is ordinary translated S-mode code, so the table pages must also be mapped, which is one reason ember’s identity map covers the pool they live in.

Third, the instruction after the csrw satp is fetched through the new tables. Its address is unchanged, so the tables must send the address of the code that is running to the code that is running. Exercise (e) removes that mapping and shows what the board does.

Fourth, writing satp swaps a pointer and nothing more. What the hart has cached from the old tables, and whether the stores that built the new ones have reached the point where the hardware can read them, are separate questions, taken up under the translation cache below.

Why a tree, and why 9 + 9 + 9 + 12

The unit of translation is the page, so the low 12 bits of an address (the offset inside a page) pass through unchanged and only the bits above them need translating. Sv39 translates 39-bit virtual addresses. Dropping the offset leaves a 27-bit virtual page number (VPN).

The simplest table is an array indexed by VPN with one entry per virtual page. That is 2272^{27} entries of 8 bytes (why 8 comes below), 2302^{30} bytes, 1 GiB for every address space, almost all of it empty for any real program. A radix tree pays only for the branches in use. Make each node of the tree exactly one page. A page holds 4096/8=512=294096 / 8 = 512 = 2^9 entries, so one node consumes 9 bits of the VPN, and 27 bits take three levels. The spec fixes the same size: “A page table is exactly the size of a page and must always be aligned to a page boundary.”

The three indices are VPN[2] = bits 38:30 of the address (indexing the root table), VPN[1] = bits 29:21 and VPN[0] = bits 20:12. The root is level 2 and the leaf level is 0. Once three levels are chosen, the 9, 9, 9 and 12 follow from the page size and the entry size and nothing else.

Each entry stands for a span that grows by 512 per level. One level-0 entry maps one 4 KiB page. One level-1 entry stands for a whole level-0 table, 512 pages, which is 2 MiB (2212^{21} bytes). One level-2 entry stands for 512 of those, 1 GiB (2302^{30} bytes). The root’s 512 entries span 2392^{39} bytes, 512 GiB. These spans return as superpage sizes below.

The entry is 8 bytes because it must carry a physical page number plus flags. Sv39’s PPN is 44 bits, so a physical address is 44+12=5644 + 12 = 56 bits wide; Sv32’s 4-byte entries carry 22 bits of PPN and could not.

Which 64-bit values are addresses

A register holds 64 bits and Sv39 translates 39. The spec’s rule for the other 25: “Instruction fetch addresses and load and store effective addresses, which are 64 bits, must have bits 63–39 all equal to bit 38, or else a page-fault exception will occur.” That is sign extension, not zero extension, and the spec says why: it “follows an entrenched convention that allows an OS to use one or a few of the most-significant bits of a full-size (64-bit) virtual address to quickly distinguish user and supervisor address regions.”

The consequence is two canonical halves with a hole between them. Bit 38 clear and bits 63:39 clear gives 0 through 0x3fffffffff, 256 GiB. Bit 38 set and bits 63:39 set gives 0xffffffc000000000 through 0xffffffffffffffff. The usual choice puts user programs in the low half and the kernel in the high one, so that the top bits tell the two apart. Everything between is not an address at all. An address that satisfies the Sv39 rule is also legal under Sv48 and Sv57, whose rules are the same with bit 47 and bit 56 in place of bit 38 (the Sv48 text reads “bits 63–48 all equal to bit 47”), so widening the mode never makes an address a program already holds illegal.

The addresses 0x4000000000 and 0xffffffc000000000 have identical VPN[2], VPN[1] and VPN[0] and differ only in bits 63:39, which makes them a clean test of whether the rule is separate from the tables. Exercise (b) runs it.

The page-table entry

An entry is one 8-byte word, laid out as in the figure.

The Sv39 page-table entry A 64-bit PTE: bits 63 to 54 reserved and zero, bits 53 to 10 the physical page number, bits 9 and 8 reserved for software, and the eight flag bits D, A, G, U, X, W, R, V from bit 7 down to bit 0. reserved 63:54, zero PPN 53:10, 44 bits RSW 9:8 7 D 6 A 5 G 4 U 3 X 2 W 1 R 0 V 7:0, the flags: dirty, accessed, global, user, execute, write, read, valid R = W = X = 0 with V = 1: a pointer. Otherwise a leaf.

V, valid, is bit 0. The spec’s rule: “if it is 0, all other bits in the PTE are don’t-cares and may be used freely by software.” A zeroed page is therefore a table with no mappings, and ember relies on that.

R, W, X, bits 1 to 3, are the permissions to read (R), write (W) and execute (X) the page. Eight combinations exist and two are not allowed:

X W R meaning
0 0 0 pointer to the next level of the table
0 0 1 read-only page
0 1 0 reserved
0 1 1 read-write page
1 0 0 execute-only page
1 0 1 read-execute page
1 1 0 reserved
1 1 1 read-write-execute page

The spec’s sentence for the reserved rows is “Writable pages must also be marked readable; the contrary combinations are reserved for future use.” The first row is how a pointer PTE is told from a leaf PTE: a valid entry with R, W and X all zero names the next table, and any other valid entry ends the walk. A leaf is the entry that holds the final translation.

U, bit 4, marks a page that user mode may access; the section on U, SUM and MXR below gives the exact rule. G, bit 5, marks a global mapping, one that exists in every address space; the spec adds that for a non-leaf entry “the global setting implies that all mappings in the subsequent levels of the page table are global”. It only matters once ASIDs do. A and D, bits 6 and 7, record that the page has been accessed and that it has been written; they get their own section. RSW, bits 9:8, is “reserved for use by supervisor software; the implementation shall ignore this field.”

PPN, bits 53:10, is the physical page number the entry points at. The PPN has three parts, PPN[0] in bits 18:10 and PPN[1] in 27:19 (nine bits each) and PPN[2] in 53:28 (the other 26), which matters for superpages in a moment. Bits 63 to 54 are reserved. The spec gives the rule for them: bit 63 belongs to the Svnapot extension, bits 62:61 to Svpbmt, and “if Svnapot is not implemented, bit 63 remains reserved and must be zeroed by software for forward compatibility, or else a page-fault exception is raised.” The same holds for the others in the range. This hart’s extension list, in the device tree QEMU builds (dump it with -machine virt,dumpdtb=virt.dtb and read it with strings), has neither Svnapot nor Svpbmt, so all ten bits must be zero. For pointer entries the spec also says “the D, A, and U bits are reserved for future standard use” and “must be cleared by software”; ember’s pointer entries set V and the PPN and nothing else.

Leaves at every level: superpages

Any level may hold a leaf. The spec: “in addition to 4 KiB pages, Sv39 supports 2 MiB megapages and 1 GiB gigapages, each of which must be virtually and physically aligned to a boundary equal to its size. A page-fault exception is raised if the physical address is insufficiently aligned.”

The spans derived above are exactly these sizes. A leaf at level 1 skips level 0 and maps 2 MiB directly; a leaf at level 2 maps 1 GiB. The alignment rule is the arithmetic of what is left over. A level-1 leaf has no level-0 index, so the low 9 bits of the VPN, which would have selected a page inside a 2 MiB region, are passed straight through into the physical address. The translation takes those bits from the address, so the leaf’s own PPN[0] would be dead bits, and the walk below requires them to be zero: the entry then names the true base of an aligned 2 MiB region. For a level-2 leaf the same check covers PPN[1] and PPN[0] together, one pte.ppn[i-1:0] in the walk’s notation.

The spec’s reason for superpages is reach: “A large page size increases TLB reach”, at the price of internal fragmentation. A superpage also saves a level of reads per walk and a table page. ember maps 4 KiB pages only, so that its walk stays one loop; exercise (c) installs a 2 MiB leaf by hand.

The walk the hardware performs

The spec states the algorithm once for all the paged modes, in “Virtual Address Translation Process” (section 11.1.3.2), and Sv39 plugs in LEVELS = 3 and PTESIZE = 8. Here it is in order, with ii the level being examined, starting at 2. Two names first. A page fault is the exception that says the translation refused the access. An access fault says the physical address itself was refused, by the platform’s memory attributes or by PMP (chapter 3). Which of three page-fault causes is raised follows the original access, covered under faults below.

  1. Let aa be satp.PPN × 4096 and ii = 2. The hart must be in S or U.
  2. Read the 8-byte entry at a+VPN[i]×8a + \mathrm{VPN}[i] \times 8. If reading it violates a memory attribute or a PMP check, raise an access fault. PMP applies to this read like any other, and the spec fixes the privilege it is checked at: “The effective privilege mode for implicit page-table accesses is S.”
  3. If V is 0, or R is 0 and W is 1, or any reserved bit or encoding is set, raise a page fault.
  4. Otherwise the entry is valid. If R or X is 1 it is a leaf, so go to step 5. If not it is a pointer: decrease ii, raise a page fault if that makes it negative, set aa to the entry’s PPN × 4096 and go to step 2.
  5. A leaf. If i>0i > 0 and pte.ppn[i-1:0] is not zero, “this is a misaligned superpage”: page fault.
  6. Check the access against the entry’s U bit, “given the current privilege mode and the value of the SUM and MXR fields of the mstatus register”. If it is not allowed, page fault. The rule is in the next section.
  7. Apply the shadow-stack rules of the Zicfiss extension, which fault with an access fault. This hart’s extension list does not include it, so the step never fires here.
  8. Check the access against R, W and X. If it is not allowed, page fault.
  9. If A is 0, or the access is a store and D is 0: under Svade, page fault. Under Svadu, the hart performs, atomically, a compare of the entry with memory, a set of A (and of D for a store) and a store back, retrying from step 2 if the comparison fails; a store to the entry that would violate PMP is an access fault.
  10. Done. The physical address’s offset is the virtual offset. If i>0i > 0 the low PPN fields come from the virtual address’s low VPN fields, the superpage case. The high PPN fields come from the entry.

The Sv39 walk A 64-bit virtual address splits into bits 63 to 39 that must equal bit 38, three 9-bit indices VPN[2], VPN[1], VPN[0], and a 12-bit offset. The walk starts at the root table named by satp.PPN, indexes it with VPN[2], follows pointer entries down through levels 1 and 0, and ends at a leaf entry whose PPN and the offset form the physical address. 63:39 = bit 38 VPN[2] 38:30 VPN[1] 29:21 VPN[0] 20:12 offset 11:0 level 2: a = satp.PPN × 4096 pte = mem[a + 8 × VPN[2]] R = W = X = 0: a pointer, go down a level level 1: a = pte.PPN × 4096 pte = mem[a + 8 × VPN[1]] R = W = X = 0: a pointer, go down a level level 0: a = pte.PPN × 4096 pte = mem[a + 8 × VPN[0]] R or X set: a leaf, check it and stop PA = pte.PPN × 4096 + offset a leaf at level 2 or 1 ends the walk early: a superpage

Three points the steps carry that are easy to miss. Steps 3 and 5 are where the entry’s reserved and encoding rules bite, before any permission is looked at. Step 6 is not the leaf’s R, W or X: U and SUM have their own check, and MXR changes what the read test accepts for a load. And the walk makes up to three dependent memory reads, one per level, before the access that caused it can start. That cost is why the hart caches the result.

Who may touch the page: U, SUM and MXR

The U bit asks who is accessing. The spec: “U-mode software may only access the page when U=1.” For S-mode it is more guarded: “If the SUM bit in the sstatus register is set, supervisor mode software may also access pages with U=1. However, supervisor code normally operates with the SUM bit clear, in which case, supervisor code will fault on accesses to user-mode pages. Irrespective of SUM, the supervisor may not execute code on pages with U=1.”

sstatus, the S-mode view of mstatus that chapter 3 introduced, holds the two bits this chapter needs: SUM (permit Supervisor User Memory access) is bit 18 and MXR (Make eXecutable Readable) bit 19. SUM exists because a kernel must sometimes read a user’s buffer, but a kernel bug that dereferences a user-supplied pointer by mistake would then succeed silently. With SUM normally clear, the mistake faults, and the handful of places that need user memory raise SUM around the access. ember’s kernel takes another route in chapter 7 and never sets it. The kernel reaches user bytes through the identity map, where the same physical page is U=0, which is possible because it holds the tables and can look the page up.

MXR changes loads: “When MXR=0, only loads from pages marked readable (R=1 …) will succeed. When MXR=1, loads from pages marked either readable or executable (R=1 or X=1) will succeed.” The spec says what it is for: it “allows instruction words to be loaded from pages marked execute-only”, as an M-mode routine emulating a missing instruction must. It changes nothing for stores or fetches.

Neither bit needs a fence when it changes. The spec: “Changes to the sstatus fields SUM and MXR take effect immediately, without the need to execute an SFENCE.VMA instruction.” The runs under “The user map” below show SUM at work and exercise (d) shows MXR.

Accessed and dirty

A page’s A bit records that it has been touched since the OS last cleared it, and D that it has been written. An OS that swaps pages uses them: A to choose a victim, D to know whether the victim has to be written out. The hardware never clears either: “The A and D bits are never cleared by the implementation.”

When the hardware reaches a leaf with A = 0, or a store to a leaf with D = 0, the spec defines two behaviours and a hart does one. Svade: “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”, so software sets the bit and retries. Svadu: the hardware sets the bit itself, atomically, in step 9. On a hart that implements Svadu, which one it does is selected by menvcfg.ADUE, a machine environment configuration bit; without Svadu the bit is read-only zero. The Svadu extension document puts it in bit 61. When ADUE is 0, the hart behaves as though only Svade were implemented.

This board reports Svadu: the extension list in the device tree contains svadu, with no separate svade entry. The ad-svadu run below prints menvcfg at reset (0x2000000000000000, ADUE set) and ad-svade clears the bit before the drop, so the capture shows both behaviours and what this board does is not left to the extension name. ember does not depend on either. Its leaf constructor sets A and D at map time, following the spec’s advice that software which “does not rely on accessed and/or dirty bits … should always set them to 1 in the PTE to improve performance.”

The device tree also reports mmu-type as riscv,sv57. Sv39 is the one taught here because the spec requires it of every hart that has more: “Implementations that support Sv48 must also support Sv39”, and the same sentence holds for Sv57 over Sv48.

The translation cache, and sfence.vma

Three dependent reads per access would make every load four memory accesses, so the hart keeps recent results. The spec’s term is the address-translation cache, which it allows in one form only: “The results of implicit address-translation reads in step 2 may be held in a read-only, incoherent address-translation cache but not shared with other harts.” The usual name for it is the TLB (translation lookaside buffer). An entry records a virtual page, its address space, the physical page it translated to and the permissions it carried.

The word that matters is incoherent. A store to a page table is an ordinary store; it does not reach into the cache and fix it. After the kernel rewrites a leaf, the hart may keep using the translation it cached from the old leaf. The spec states the permission precisely: “an implementation may use any translation for an address that was valid at any time since the most recent SFENCE.VMA that subsumes that address.” That is a permission to be stale, not a promise to be. Correct code cannot depend on either outcome, and the tlb-stale and tlb-print runs below show the board doing each.

sfence.vma, the supervisor memory-management fence, closes the gap. The spec specifies it “as a fence rather than a TLB flush to provide cleaner semantics”, and it does two jobs. It orders: “any previous stores already visible to the current RISC-V hart are ordered before certain implicit references by subsequent instructions in that hart to the memory-management data structures.” And it invalidates the address-translation cache entries that match. Which set it covers depends on its two operands:

sfence.vma rs1, rs2 orders and invalidates
x0, x0 every entry, all address spaces
x0, rs2 entries for the address space whose ASID is in rs2, except global ones
rs1, x0 entries for the leaf mapping the virtual address in rs1, all address spaces
rs1, rs2 entries for the leaf mapping the address in rs1 in the address space in rs2, except global ones

Over-fencing is always legal: “simpler implementations can ignore the virtual address in rs1 and the ASID value in rs2 and always perform a global fence.” The instruction orders only the local hart, “consequently, other harts must be notified separately”, which the spec describes as the RISC-V analogue of a TLB shootdown.

An ASID is what lets entries from several address spaces sit in the cache together, so a context switch can swap satp without flushing; a global (G) mapping is shared by all of them and is kept through an ASID-specific fence. ember uses ASID 0 throughout and has no use for either.

The spec lists when a fence is owed: after modifying a non-leaf entry, sfence.vma with rs1 = x0; after modifying a leaf, rs1 set to a virtual address inside the page; for either, rs2 is the ASID unless any entry on the path is global, in which case x0. Two relaxations exist. Raising the permissions on a leaf, or turning an invalid entry into a valid leaf, may be fenced lazily: “either the new or old permissions will be used”, and a resulting page fault is the signal to fence. The Svvptc extension, which this board lists, goes further for invalid to valid: such a store becomes visible “within a bounded timeframe”, so the fence is redundant. The case needs a rule because the spec “permits the caching of PTEs whose V (Valid) bit is clear”, so a hart may remember that a page was unmapped after software has mapped it, and an unfenced new mapping can still fault.

Why the lab fences after writing satp. Two sentences of the spec bear on it. The spec notes that writing satp “does not imply any ordering constraints between page-table updates and subsequent address translations, nor does it imply any invalidation of address-translation caches.” And for software that uses only ASID 0, as ember does: “after every satp write, software should execute SFENCE.VMA with rs1=x0.” The fence after the write is that prescription. Its guarantee is stated for later instructions: previous stores are “ordered before certain implicit references by subsequent instructions”, so it covers every translation after it. It cannot cover its own fetch. The instruction after the csrw is the sfence.vma itself, fetched through the new tables before the fence has executed, and a strict reading would also want a fence before the write; the spec allows one, since a fence may be needed “after, or in some cases before, writing satp”.

Nothing stale can be cached on this first write. Translation only begins while satp is active, and implementations “must only perform implicit reads of the translation data structures pointed to by the current contents of the satp register”, so a hart that ran Bare before (this board’s reset state for satp, as the S: running line printed before mem_init shows) has left no Sv39 entries behind. The ordering is what remains: the stores that built the tables must reach the walker, whose “implicit references are ordinarily not ordered with respect to explicit loads and stores.” On this board the capture cannot tell these cases apart. The no-fence run below leaves the fence out and the transcript does not change, so the argument is the spec’s sentences and not an observation.

Faults: three causes, two registers

A page fault is reported as one of three exception causes, chosen by the original access:

mcause / scause name raised by
12 instruction page fault an instruction fetch
13 load page fault a load
15 store/AMO page fault a store or an atomic memory operation

Cause 14 is reserved. An atomic operation is a read-modify-write; the spec’s rule is “AMOs never raise load page-fault exceptions”, so an AMO on an unreadable page is a store fault. The access faults of step 2 have their own codes (code 1 for a fetch, 5 for a load, 7 for a store). The cause number follows the access, not the reason: a missing mapping, a cleared V, a reserved bit, a failed U check and a missing X all give the same number. What the cause does not carry is which address, and a second register holds that.

Chapter 3 gave the registers a trap writes: scause, sepc and stval for a trap taken into S-mode, their m twins for M-mode. For a page fault the trap value is the faulting virtual address. The spec: when stval is written with a nonzero value for a page-fault exception on a fetch, a load or a store, “stval will contain the faulting virtual address.” The M-mode register says the same, and adds a rule for access faults: “When page-based virtual memory is enabled, mtval is written with the faulting virtual address, even for physical-memory access-fault exceptions.” The platform may set the value to zero instead; the sentence only fixes what happens if it writes it, and the captures say what this board does.

Which privilege mode takes the trap is chapter 3’s delegation rule: a trap goes to M unless the matching bit of medeleg is set. In this chapter nothing is delegated, and the paging is on in S, so the fault climbs to M. The shim prints mcause and mtval, not stval. Chapter 5 sets medeleg bits 12, 13 and 15 from M before the drop. By the rule above the same faults then arrive in S-mode as scause 12, 13 and 15, with stval holding the virtual address and sepc the instruction.

What ember’s walk is, and what it is not

pt.c’s walk() descends the same three levels with the same index arithmetic as the hardware. It has a different job. The hardware walk translates, and stops with a fault at the first bad entry. walk() builds: it is given a virtual address, and where an entry is invalid it allocates a zeroed table and plants a pointer to it, until it reaches level 0 and hands back the slot for the caller to fill. It checks no permissions, reads no A or D, and refuses (returns 0) to descend through a leaf, a case where the hardware’s step 4 would have stopped and translated. The two share only the index arithmetic. Chapter 19 adds a second hardware walk and a second building walk for it; keep apart which walk is building and which is translating.

The second walk

With the H extension a guest’s own tables (the VS-stage) sit above a second set that the hypervisor owns, the G-stage, which translates guest-physical addresses to the machine’s own physical addresses. The spec defines it as this chapter’s algorithm with a short list of changes: hgatp takes the place of satp; every leaf is checked as though the access came from U-mode; its faults are a distinct kind, guest-page faults; and the guest-physical address is two bits wider than Sv39’s 39, with the bits above it required to be zero, so the root table is four pages (16 KiB) instead of one. The G-stage also applies to every memory access the VS-stage itself makes, including its reads of the guest’s page tables, so one guest access can walk the second set many times. Which privilege level handles a fault depends on the stage as well as on delegation: a VS-stage page fault can be delegated as far as the guest kernel, but the spec says guest-page faults “may be delegated from M-mode to HS-mode under the control of CSR medeleg, but cannot be delegated to other privilege modes” (H 14.1.5.2), so a G-stage fault never reaches the guest. Chapter 19 derives each of these.

Walkthrough

The reference code is ember/pt.h, ember/pt.c and ember/mem.c. Every listing below is shown as compiled at chapter 4; the files carry other chapters’ branches that this one does not.

#define PAGE_SHIFT 12
#define PAGE_SIZE  (1UL << PAGE_SHIFT)
#define PTE_COUNT  512

#define PTE_V (1UL << 0)
#define PTE_R (1UL << 1)
#define PTE_W (1UL << 2)
#define PTE_X (1UL << 3)
#define PTE_U (1UL << 4)
#define PTE_G (1UL << 5)
#define PTE_A (1UL << 6)
#define PTE_D (1UL << 7)

#define SATP_MODE_SV39 (8UL << 60)

The constants are UL so that the masks are 64 bits wide; for SATP_MODE_SV39, 8UL << 60 is bit 63 of a 64-bit register, and 8 << 60 on a 32-bit int would be undefined. PTE_COUNT is the 512 of the derivation. There is no PTE_RSW because the kernel never writes it.

static int pte_valid(unsigned long pte)
{
    return (pte & PTE_V) != 0;
}

int pte_leaf(unsigned long pte)
{
    return pte_valid(pte) && (pte & (PTE_R | PTE_X)) != 0;
}

pte_leaf is the spec’s step 4 as one predicate: valid, and R or X. A W-only entry (reserved) is not a leaf here, so walk() would treat it as a pointer. The hardware would fault it at step 3; ember never builds one, so the difference does not arise.

static unsigned long pte_ppn(unsigned long pte)
{
    return (pte >> 10) & ((1UL << 44) - 1);
}

static unsigned long make_ptr_pte(void *table)
{
    return PTE_V | ((((unsigned long)table) >> PAGE_SHIFT) << 10);
}

static unsigned long make_leaf_pte(unsigned long pa, unsigned long flags)
{
    return flags | PTE_V | PTE_A | PTE_D | ((pa >> PAGE_SHIFT) << 10);
}

pte_ppn extracts bits 53:10 (the mask is 44 ones), and the two constructors are its inverse. make_ptr_pte sets V and the PPN of the next table and nothing else, so R, W, X, U, A and D are all zero, which is what a pointer entry must be. make_leaf_pte takes the caller’s flags (R, W, X, U) and sets V, A and D as well; the shift by PAGE_SHIFT then by 10 is “physical address to PPN, PPN to its place in the entry”. Setting A and D here is what keeps the capture independent of Svade versus Svadu. Nothing masks flags, so a caller that passed a stray high bit would plant a reserved one; every caller in this chapter passes PTE_ constants.

static void zero_page(void *p)
{
    unsigned long *q = p;
    for (int i = 0; i < (int)PTE_COUNT; i++)
        q[i] = 0;
}

static void *alloc_table(void)
{
    char *p = pool;
    if (p + PAGE_SIZE > pt_pool_end)
        halt(1);
    pool += PAGE_SIZE;
    zero_page(p);
    return p;
}

void pt_init(void)
{
    pool = pt_pool_start;
    root = alloc_table();
}

unsigned long pt_root_ppn(void)
{
    return ((unsigned long)root) >> PAGE_SHIFT;
}

Table pages come from a bump allocator over pt_pool_start to pt_pool_end, which link.ld places after stack_top and aligns to a page, since a table must be page-aligned. The pool lies outside .bss, so start.S’s zeroing loop does not touch it. root and pool are file-level statics declared at the top of pt.c: the root table and the next free page. alloc_table zeroes what it hands out, and that is not tidiness. A zeroed page has V = 0 in all 512 entries, which means “no mapping”, and any other contents would be a table full of mappings. When the pool runs out it halts rather than returning a bad pointer. pt_root_ppn is the number satp wants.

unsigned long *walk(unsigned long va)
{
    unsigned long *table = root;
    int level;

    for (level = 2; level >= 0; level--) {
        unsigned vpn = (unsigned)((va >> (PAGE_SHIFT + 9 * level)) & 0x1ff);
        unsigned long *slot = &table[vpn];
        if (level == 0)
            return slot;
        if (!pte_valid(*slot)) {
            void *next = alloc_table();
            *slot = make_ptr_pte(next);
        } else if (pte_leaf(*slot)) {
            return 0;
        }
        table = (unsigned long *)(pte_ppn(*slot) << PAGE_SHIFT);
    }
    return 0;
}

vpn is the derivation as one expression: shift right by 12+9×level12 + 9 \times \mathrm{level} (30, 21 or 12), mask nine bits. slot is the address of entry VPN[i]\mathrm{VPN}[i] in the current table, which is the hardware’s a+VPN[i]×8a + \mathrm{VPN}[i] \times 8 written as C pointer arithmetic on an array of 8-byte words. At level 0 the loop returns the slot itself, because the caller will fill it. Above level 0 there are three cases. An invalid entry means the branch does not exist yet, so allocate a zeroed table and plant a pointer to it. A valid leaf means a superpage covers this address and there is no table to descend into: returning 0 makes map_page halt, where the alternative, treating the leaf’s target page as a table, would write entries into someone’s data. Otherwise it is a pointer, and table becomes the next table. That last line reinterprets a physical address as a C pointer. Before satp is written, that is simply true. After, it is true because the pool is part of the identity map. This is the second consequence from the start of the chapter.

void map_page(unsigned long va, unsigned long pa, unsigned long flags)
{
    unsigned long *slot = walk(va);
    if (!slot)
        halt(1);
    *slot = make_leaf_pte(pa, flags);
}

map_page is walk plus one store. It overwrites whatever is in the slot, without a check, which is how mem_init, below, replaces the identity leaf at 0x81000000 with a user leaf. It does not execute sfence.vma. A mapping changed after translation is on needs the caller to fence, and chapter 9’s kalloc_init does so when it takes the user page back; the translation-cache run below shows why.

static void map_identity_dram(void)
{
    unsigned long pa;
    for (pa = DRAM_BASE; pa < DRAM_BASE + DRAM_SIZE; pa += PAGE_SIZE)
        map_page(pa, pa, PTE_R | PTE_W | PTE_X);
}

static void map_mmio(unsigned long pa)
{
    map_page(pa, pa, PTE_R | PTE_W);
}

static void map_mmio_range(unsigned long pa, unsigned long bytes)
{
    unsigned long end = pa + bytes;
    pa &= ~(PAGE_SIZE - 1);
    for (; pa < end; pa += PAGE_SIZE)
        map_mmio(pa);
}

The identity map: every 4 KiB page of the 128 MiB of DRAM maps to itself with R, W and X all set (32768 map_page calls). The MMIO pages are mapped read and write only; executing a device register is meaningless. map_mmio_range rounds the start down to a page and walks to the end. How many table pages all this allocates is exercise (f).

/*
 * Own page, no calls, no constant pool: RISC-V `call` and `auipc`
 * for a .rodata string both relocate from PC, so a PC at SECOND_VA
 * cannot reach identity-mapped uart_puts or a pool on another page.
 * Immediate stores to the UART only.
 */
__attribute__((noinline, aligned(4096))) static void hi_print(void)
{
    volatile unsigned char *u = (volatile unsigned char *)0x10000000UL;
#define PUT(c)                                                                 \
    do {                                                                       \
        while ((u[5] & 0x20) == 0)                                             \
            ;                                                                  \
        u[0] = (unsigned char)(c);                                             \
    } while (0)
    PUT('S');
    PUT(':');
    PUT(' ');
    PUT('s');
    PUT('e');
    PUT('c');
    PUT('o');
    PUT('n');
    PUT('d');
    PUT(' ');
    PUT('m');
    PUT('a');
    PUT('p');
    PUT('\r');
    PUT('\n');
#undef PUT
}

hi_print is the proof function. It is page-aligned, so the whole function lives in one page and the second mapping can cover exactly that page. Its constraint comes from how RISC-V reaches addresses. A call is auipc plus jalr, and auipc adds an immediate to the program counter, so a call or a .rodata access compiled at one address lands somewhere else when the code runs at another. The function runs at 0x40000000 + offset, where nothing PC-relative from the identity-mapped copy would find its target. So it does not call, and it does not read .rodata: the UART address is built with lui (an absolute constant), each character is an immediate stored to the transmit register after a wait on the line-status ready bit, and the only RAM it touches is the stack, which is identity-mapped. It returns through ra, which holds an identity-mapped address, so the ret jumps back out of the second mapping. PUT is a macro so there is no helper to call. Chapter 2’s UART lesson applies unchanged: poll LSR bit 5, then write THR.

void mem_init(void)
{
    unsigned long fn = (unsigned long)hi_print;
    unsigned long page = fn & ~(PAGE_SIZE - 1);
    unsigned long off = fn & (PAGE_SIZE - 1);
    void (*via_second)(void);

    pt_init();
    map_identity_dram();
    map_mmio(0x00100000UL);
    map_mmio_range(0x02000000UL, 0x10000UL);
    map_mmio_range(0x0c000000UL, 0x400000UL);
    map_mmio(0x10000000UL);
    map_page(SECOND_VA, page, PTE_R | PTE_X);
    map_page(0x81000000UL, 0x81000000UL, PTE_R | PTE_W | PTE_U);

    csr_write(satp, SATP_MODE_SV39 | pt_root_ppn());
    __asm__ volatile("sfence.vma" ::: "memory");

    via_second = (void (*)(void))(SECOND_VA + off);
    via_second();
    *(volatile unsigned long *)BAD_VA = 1UL;
    uart_puts("S: store to unmapped VA survived\r\n");
    halt(1);
}

The lines in order. pt_init takes the root page. map_identity_dram and the four MMIO calls build what S-mode will use after the write: the finisher at 0x00100000 (what halt writes), the CLINT’s 64 KiB at 0x02000000 (the timer block of chapter 6), the first 4 MiB of the PLIC at 0x0c000000 (the interrupt controller of chapter 5) and the UART page. The CLINT and the PLIC are mapped now because chapters 5 and 6 use them with this function unchanged; chapter 5 shows that with only the PLIC’s base page mapped, the first access beyond it (the load of the enable word) is scause 13 (labs/ch05/ex/plic-base-page.txt).

map_page(SECOND_VA, page, PTE_R | PTE_X) maps the physical page containing hi_print at 0x40000000, read and execute, a second mapping: the same physical page under a different VPN. Nothing about 0x40000000 makes it a “high alias” in Sv39; it is a second mapping, a different index into the root. The last mapping, map_page(0x81000000UL, 0x81000000UL, …), replaces the identity leaf for that one page (the loop had just made it read, write, execute) with read and write and PTE_U: a user page, mapped now and unused by this chapter’s image. The side runs use it.

csr_write(satp, SATP_MODE_SV39 | pt_root_ppn()) is the switch: MODE 8 in bits 63:60, ASID 0, and the root’s PPN. The sfence.vma follows because the spec prescribes it after every satp write for ASID-0 software, and it assembles with both operands x0, the first row of the table: every entry, every address space. The "memory" clobber stops the compiler from moving memory operations across it. The call through via_second is the proof of translation: control reaches hi_print through a virtual address whose page-number bits are not the physical page’s. The capture’s S: second map is the string hi_print wrote, and no other path to those instructions exists.

Last, a store to 0x12345000, which chapter 5’s image compiles out. Which table says no? VPN[2] = 0 is the root entry that the MMIO mappings made valid; VPN[1] = 0x12345000 >> 21 & 511 = 145, and no level-1 entry at 145 was ever made, so the entry is invalid and step 3 stops the walk at level 1 with a store page fault. Nothing is delegated, so it climbs to M. The shim prints mcause 15 and mtval, the faulting virtual address. The lab can pin that number because it is the address the program named, not one the linker chose.

S: second map
M: trap cause 0xf (page fault) mtval=0x12345000
PASS

PASS comes from chapter 3’s shim, which at this chapter expects exactly one trap, a store page fault.

The user map

The identity map serves the kernel. A user map is the other half of an operating system’s use of Sv39: pages the kernel marks U=1 for a user program. The main image has one, 0x81000000, mapped read and write with U=1 and unused until chapter 9 takes it back. Three side runs use it, each a patch to mem_init (user-fetch.patch also deletes the line that maps the user page) that applies to a scratch copy and leaves the tree alone: sum-clear.patch, sum-set.patch and user-fetch.patch under labs/ch04/ex/, with the transcripts beside them. make ex CH=04 reruns all of them.

With SUM clear, S-mode loads from the page:

volatile unsigned long *u = (volatile unsigned long *)0x81000000UL;
unsigned long v = *u;
S: SUM clear, load from the U=1 page at 0x81000000
M: trap cause 0xd (page fault) mtval=0x81000000

Cause 13, load page fault, with the virtual address in mtval. The walk reached a valid leaf whose R bit allows the load and stopped at step 6: S-mode, U = 1, SUM clear. With SUM set (csr_set(sstatus, (1UL << 18))), a store and a load on the same page both work:

S: SUM set, store and load on the U=1 page at 0x81000000
S: loaded back 0x600d

Same address, same leaf, same R and W bits; only the privilege rule changed.

The third run isolates the rule that SUM does not touch. The page this time is mapped read, write and execute, with U=0 first. The patch stores a ret instruction (0x00008067) into it and calls it. Then it remaps the page with U=1 added, fences that one address (sfence.vma with rs1 the address), sets SUM and calls it again:

S: U=0, X=1: jumped to the page and returned
S: page now U=1, X=1, and SUM set; jump again
M: trap cause 0xc mtval=0x81000000

The first call returns, so the page is executable. The second differs from the first in one bit of the leaf, U, and in SUM, and it faults with cause 12, an instruction page fault at the page’s own address. That is the spec’s “irrespective of SUM, the supervisor may not execute code on pages with U=1” shown on the board. The shim prints (page fault) only for causes 13 and 15, so cause 12 gets the generic line. (The patch writes code and runs it without fence.i, the instruction that makes stored instructions visible to fetch on a core that needs it. QEMU does not, and the run is about translation, not instruction coherence.)

The translation cache

Four runs use a fresh page, mapped read and write at 0x50020000 (or 0x50000000) to the physical page 0x82000000, which holds 0xaaaa; the page at 0x82001000 holds 0xbbbb. Each loads through the mapping, rewrites the leaf with map_page to point at 0x82001000, and loads again. A small helper, say, prints a label and a value in hex. The central lines of tlb-stale.patch:

say("S: via 0x50020000, mapped to 0x82000000: ", *(volatile unsigned long *)0x50020000UL);
map_page(0x50020000UL, 0x82001000UL, PTE_R | PTE_W);
say("S: via 0x50020000: ", *(volatile unsigned long *)0x50020000UL);
__asm__ volatile("sfence.vma %0, zero" : : "r"(0x50020000UL) : "memory");
say("S: via 0x50020000: ", *(volatile unsigned long *)0x50020000UL);
S: via 0x50020000, mapped to 0x82000000: 0xaaaa
S: leaf PTE now points at 0x82001000, no fence
S: via 0x50020000: 0xaaaa
S: sfence.vma 0x50020000, x0
S: via 0x50020000: 0xbbbb

The second load returned 0xaaaa, the contents of the page the leaf used to name, though the leaf in memory already named the other one. The hart used a cached translation. After sfence.vma with rs1 the page’s address and rs2 zero, the same load returns 0xbbbb.

The same patch with the virtual address 0x50000000 (tlb-print.patch) gives a different transcript:

S: via 0x50000000, mapped to 0x82000000: 0xaaaa
S: leaf PTE now points at 0x82001000, no fence
S: via 0x50000000: 0xbbbb
S: sfence.vma 0x50000000, x0
S: via 0x50000000: 0xbbbb

The second load already returned 0xbbbb, with no fence, and the code differs only in the address. tlb-quiet.patch repeats that address but makes the three loads back to back and prints afterwards, with no UART output between the first load and the second:

S: via 0x50000000, mapped to 0x82000000: 0xaaaa
S: after rewriting the leaf, no fence: 0xaaaa
S: after sfence.vma 0x50000000, x0: 0xbbbb

Now 0x50000000 is stale as well. So the difference between the two runs at that address is the output between the loads, and whether the cached translation survived it depends on the address. The runs do not show which access displaced the entry (that would take QEMU’s source, which this chapter does not read). The spec’s sentence covers all of it: the hart may use “any translation for an address that was valid at any time since the most recent SFENCE.VMA”, and “it is unpredictable which translation will be chosen from that set”. Staleness is not guaranteed and its absence is not evidence that the fence is optional. Code that rewrites a mapping and reads through it needs the fence either way.

tlb-satp.patch replaces the fence with a second csrw satp of the same value, at 0x50020000:

S: via 0x50020000, mapped to 0x82000000: 0xaaaa
S: leaf PTE now points at 0x82001000; rewrite satp, no fence
S: via 0x50020000: 0xaaaa

Rewriting satp with the same value did not drop the stale entry. That is one run of one unchanged write. It agrees with the spec sentence that a satp write implies no invalidation, and says nothing about a write that changes the root or the ASID.

A fifth patch, no-fence.patch, deletes the sfence.vma after the first satp write and otherwise runs the stock lab. Its transcript is identical to labs/ch04/capture.txt. This board shows no difference with or without the fence there.

Accessed and dirty on this board

ad-svadu.patch writes, by hand, a leaf for 0x50020000 with V, R and W set and A and D clear, then loads through it and stores through it. It prints menvcfg from M-mode before the drop. ad-svade.patch is the same mapping and the same load after csr_clear(menvcfg, 1UL << 61) in M-mode, which clears ADUE.

M: menvcfg=0x2000000000000000
S: leaf PTE has V R W, A and D clear; load, then store
S: loaded 0xaaaa
S: PTE after load  0x20800047
S: PTE after store 0x208000c7

The reset value has bit 61 set. The load succeeded and the entry in memory went from 0x07 in its low byte (V, R, W) to 0x47, A set. The store made it 0xc7, D set too. The hardware performed step 9. With ADUE cleared:

M: menvcfg=0x0
S: leaf PTE has V R W, A and D clear; load through it
M: trap cause 0xd (page fault) mtval=0x50020000

A load through a leaf with A clear is a load page fault: Svade. This board does both, and a bit that M-mode can write selects between them.

Exercises

(a) Hand-walk 0x81234567 the way the hardware would. Give the three indices, the offset, and which table each index selects an entry in under ember’s tables.

Answer

By hand: bits 38:30 are 0x81234567 >> 30 = 2, so VPN[2] = 2. Bits 29:21 are (0x81234567 >> 21) & 0x1ff = 0x409 & 0x1ff = 9. Bits 20:12 are (0x81234567 >> 12) & 0x1ff = 0x81234 & 0x1ff = 0x34. The offset is 0x567. The address is below 238 with bits 63:39 zero, so it is canonical. The side run hand-walk performs the walk in software, reading the three tables from the root pt_root_ppn() names:

S: VPN[2] 0x2
S: VPN[1] 0x9
S: VPN[0] 0x34
S: offset 0x567
S: level-2 entry flags 0x1
S: level-1 entry flags 0x1
S: leaf entry 0x2048d0cf
S: PA 0x81234567

The two upper entries have only V set, so they are pointers (R = W = X = 0): root entry 2 leads to the level-1 table for the DRAM gigabyte, its entry 9 to the level-0 table for 0x81200000 to 0x813fffff, and that table’s entry 0x34 is the leaf. The leaf 0x2048d0cf has the PPN 0x81234 in bits 53:10 (0x81234 << 10 is 0x2048d000) and 0xcf in the flags: V, R, W, X, A and D, which is what make_leaf_pte builds for a read-write-execute identity page. The physical address is the PPN times 4096 plus the offset: 0x81234567, the address it started as.

(b) 0xffffffc000000000 and 0x0000004000000000 have the same VPN[2], VPN[1] and VPN[0]. The side run canonical maps the first to the page at 0x82000000 and loads through both. What happens to each, and what does that show about the walk?

Answer

From labs/ch04/ex/canonical.txt:

S: load 0xffffffc000000000: 0xaaaa
S: load 0x0000004000000000 (same VPN[2:0], bits 63:39 clear)
M: trap cause 0xd (page fault) mtval=0x4000000000

Both addresses have VPN[2] = 0x100 and zero below it, so the same entries would answer for both. The first has bits 63:39 equal to bit 38 (all ones) and translates. The second has bit 38 set and bits 63:39 clear, which breaks the rule “bits 63–39 all equal to bit 38”, and takes a load page fault, with the whole 64-bit address in mtval. The canonical rule is a check on the address itself, separate from the tables: no table entry can make the second address valid.

(c) A 2 MiB leaf is installed at virtual address 0x60000000, pointing at the physical page 0x82000000, and another at 0x60200000, pointing at 0x82001000. What does a load through each return, and why does the second fail? Use labs/ch04/ex/superpage.txt.

Answer

The side run stores 0xcafe at physical 0x82001008 and loads through both leaves:

S: 2 MiB leaf at VA 0x60000000 -> PA 0x82000000; load 0x60001008: 0xcafe
S: 2 MiB leaf at VA 0x60200000 -> PA 0x82001000 (not 2 MiB aligned); load
M: trap cause 0xd (page fault) mtval=0x60200008

The first load’s address, 0x60001008, has VPN[2] = 1, VPN[1] = 0x100 (which selected the level-1 leaf), VPN[0] = 1 and offset 0x008; the second leaf sits at VPN[1] = 0x101. The leaf is at level 1, so step 10 takes the physical page number’s low field from VPN[0] instead of from the entry: the physical address is 0x82000000 + 1 × 4096 + 0x008 = 0x82001008, which holds 0xcafe. The second leaf points at 0x82001000, whose PPN is 0x82001; PPN[0] is the low nine bits of that, 1, not zero. Step 5 reads “if i>0 and pte.ppn[i-1:0] ≠ 0, this is a misaligned superpage” and raises a page fault: a leaf that is a 2 MiB region must start on a 2 MiB boundary.

(d) A page is mapped execute-only (X = 1, R = W = 0). What does a load from it do under sstatus.MXR clear, and under MXR set? Use labs/ch04/ex/mxr-clear.txt and mxr-set.txt.

Answer

MXR clear:

S: MXR clear, load from an execute-only page
M: trap cause 0xd (page fault) mtval=0x70000000

MXR set:

S: MXR set, load from an execute-only page
S: loaded 0xaaaa

With MXR clear the load fails the read check on a page whose R is 0. With MXR set the same check accepts X: “loads from pages marked either readable or executable (R=1 or X=1) will succeed.” MXR changes only loads: the spec describes it as modifying “the privilege with which loads access virtual memory”.

(e) Remove map_identity_dram() from mem_init and run. What happens, at what point, and why does the M shim still work?

Answer

From labs/ch04/ex/no-identity.txt, whose patch also makes the shim print the high bits of mtval for cause 12 so the transcript does not pin a link address:

S: running
M: instruction page fault, mtval>>20 = 0x800

The line S: second map never appears. S: running is printed before mem_init; the next output would come after the satp write. The instruction fetch that follows that write is translated through tables that still map 0x81000000 but nothing around the image: root entry 2 exists and points at a level-1 table, whose entry 0 (the one covering 0x80000000 to 0x801fffff) is invalid. The walk stops there at step 3 and raises cause 12. mtval>>20 is 0x800, so the address lies in the first megabyte of DRAM, where the image is. The M shim keeps working because satp is active in S and U only, and the trap runs in M with the physical addresses it always used.

(f) How many page-table pages does mem_init allocate? Account for every one.

Answer

labs/ch04/ex/pool-count.txt prints S: page-table pages allocated 0x4a, which is 74. The count: one root table; three level-1 tables, one for each root entry in use (index 0 for the MMIO below 1 GiB, 1 for the second mapping at 0x40000000, 2 for DRAM); and 70 level-0 tables. The DRAM region needs 64 level-0 tables because 128 MiB is 64 × 2 MiB and each level-0 table maps 2 MiB. The second mapping needs one. The MMIO needs five: 0x00100000 (the finisher), 0x02000000 to 0x0200ffff (the CLINT), 0x0c000000 to 0x0c3fffff (the PLIC, 4 MiB, so two), and 0x10000000 (the UART), each in a different 2 MiB region. The user page at 0x81000000 replaces a leaf in an existing table. 1 + 3 + 64 + 1 + 5 = 74.

(g) A kernel on this board unmaps a page: it clears V in a leaf. May it skip the sfence.vma because the hart lists Svvptc?

Answer

No. Svvptc covers only the other direction. The spec: a store that updates the Valid bit “from 0 to 1” becomes visible “within a bounded timeframe”, but, in its words, “Synchronizing the hart’s address-translation caches with other forms of updates to a memory-resident PTE, including when a PTE is changed from Valid to Invalid, requires the use of suitable memory-management instructions.” Until the fence, the hart may keep using the cached translation (the spec’s permission to use any translation valid since the last fence). The fence is sfence.vma with rs1 an address in the page, and rs2 the ASID or x0 as in the table above.

Lab

make lab CH=04
make lab CH=04 IMPL=mine
make ex CH=04

The capture pins S: second map and mtval=0x12345000. IMPL=mine stubs mem_init, so the capture diff fails on the missing lines until the reader writes it. make ex CH=04 reruns every side run in a scratch copy of ember/ and diffs each transcript against the committed one in labs/ch04/ex/; it is not part of make check. The translation-cache transcripts depend on the state of the board’s cache, which the spec leaves open, so a different QEMU build may print a different one; the committed ones are from QEMU 11.1.1.

Further reading

results matching ""

    No results matching ""