Module 10 · Lesson 45 of 112

A higher-half kernel and MMIO mappings

Relocate a freestanding Sv39 kernel to high virtual addresses, map its device registers and heap, and verify UART output after the paging transition.

  • Beginner to advanced
  • 10 min read
  • 57 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM; the course's freestanding RISC-V Rust kernel, QEMU virt setup, and RISC-V-capable GDB

Your place in the module
By the end you can 4 objectives
  • Distinguish the kernel's physical load address from its high virtual link address.
  • Transfer execution to a high virtual entry and remove temporary identity mappings.
  • Map QEMU virt device ranges and heap pages with appropriate permissions and memory attributes.
  • Verify the high program counter, UART output, and heap backing in QEMU.
Video coming soonA higher-half kernel and MMIO mappings
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from The kernel address-space layout
  • The kernel image has distinct virtual regions for instructions, read-only data, initialized writable data, and zero-initialized data.
  • The heap and stack have their own virtual bounds and use RAM as backing.
  • A direct map uses a constant offset for covered physical ranges, while dedicated MMIO windows give the CPU access to selected device registers.
01

Link high and transfer execution

5 min read

The last lesson drew the layout. Now you relocate the kernel to a high address and map UART, PLIC, CLINT, and virtio into the kernel window with the right attributes.

A write to satp can make the very next instruction inaccessible. The CPU continues from the current program counter, but instruction fetch now goes through the page tables. Linux's RISC-V boot documentation describes an early mapping and a relocation step for this reason. In this lesson the freestanding Rust kernel uses a temporary identity mapping to keep the transition instructions accessible until an explicit jump to the high address. Ubuntu hosts QEMU, and the kernel you change runs inside the RISC-V guest. RISC-V boot requirements

Use 0xffffffff80000000 as the example virtual start of the main kernel image. It is a canonical high address under Sv39, and its VPN[2] is 510, so the root entry for the kernel image is index 510. The physical load address still comes from the course boot setup. A higher-half layout leaves the low virtual range available for user mappings once the temporary boot mappings are gone. Clearing U on the kernel leaves keeps user mode from accessing the high kernel pages.

Distinguish the from the load address, where the image bytes are placed. Keep a small assembly bootstrap linked at the address where the paging-off boot chain enters it. Link the main kernel sections high and assign their load addresses in the physical image using the linker script. Inspect the ELF entry and loadable program headers with readelf -h -l on the kernel ELF. Check that the entry is in the low bootstrap and the main kernel segments have high virtual addresses and the intended physical load addresses. Retain the boot setup's expected image format. If it boots a flat image, also check the offsets in that image and its physical placement.

Build the initial tables while paging is off, using physical addresses for the root and lower-level tables. Map the main kernel's high sections to the frames that contain them. Give text read and execute permission, read-only data read permission, and writable data and BSS read and write permission. Use page-aligned permission boundaries. Ensure BSS is zeroed before Rust code depends on it. Code that runs before the jump must reach its data and tables while paging is off. Keep it in the low bootstrap or give it explicit physical addresses for the objects it needs.

From the low bootstrap to the high kernelBuildinitialtablesmap the lowstub andhigh imageWrite satpprogramcounterstays lowFetchthroughidentitymapfence andswitchstackJump highenter thehighassemblyentryRemove lowmappingsfence afterremoving translationsBuildinitialtablesmap the lowstub andhigh imageWrite satpprogramcounterstays lowFetchthroughidentitymapfence andswitchstackJump highenter thehighassemblyentryRemove lowmappingsfence afterremoving translations
The boot hart uses a temporary identity mapping to reach the explicit jump to the high entry
Step by stepExplore the mechanism
  1. Map the low transition instructions at their current addresses with execute permission. Cover any bootstrap stack or data the transition still touches with the permissions those accesses require. Map the high entry, the stack it will use, and the data it needs before it can run.

  2. In the low assembly stub, prepare the full high entry address and high stack pointer before changing satp. A low-to-high symbol reference can exceed the range of a PC-relative instruction sequence (the linker rejects such a reference with a relocation ... out of range error). One option is to load full-width addresses from a nearby literal table in the low bootstrap. End the transition by jumping through the register holding the entry address.

  3. Keep supervisor interrupts disabled during the transition. Install the Sv39 root in satp using its physical page number, then execute sfence.vma x0, x0 on the boot hart while the low transition instructions are still mapped. Switch to the high stack before calling code that uses it. Enter the high assembly entry without returning to the low caller.

  4. Complete any runtime register setup required by the high code before calling Rust. Set stvec to a valid high trap entry before enabling interrupts or intentionally testing a fault. Synchronous faults can still occur with interrupts disabled.

  5. Once the program counter, stack, trap entry, and remaining pointers use valid high addresses, remove the temporary identity mappings and execute sfence.vma x0, x0 again. Keep a valid virtual mapping of any page-table frames your kernel still needs to edit.

A pointer saved while paging is off can still contain a low address even after the jump. Check the console base, the boot device tree pointer if you still use it, and the pointers used by the page-table editor. Preserve the boot information by copying what you need or by mapping its backing memory at a virtual address the high code can use. Inspect the program counter and stack pointer in GDB at the high entry. A successful satp write by itself tells you neither of those registers has moved high.

02

Map device registers and heap RAM

4 min read

Reserve a range in the kernel window for MMIO, separate from the image and heap. With the course's QEMU virt machine, the 16550 UART starts at physical 0x10000000. Take the UART range and the PLIC, CLINT, and virtio MMIO ranges from the boot map for the machine you launched. Use the device tree's reg entries, applying any bus address translation described by the tree. QEMU configurations can expose different devices or interrupt-controller layouts. Match the course configuration that exposes the expected PLIC and CLINT, and record each virtio MMIO transport range you intend to use.

Round each register range down at its start and up at its exclusive end to page boundaries. Allocate enough high virtual pages to cover the result. Install a leaf for each page, pairing consecutive virtual pages with consecutive physical pages in that range. Keep the device base's offset within its first physical page when computing the driver's virtual base. With the page-aligned UART base, offset zero in the first virtual page translates to 0x10000000. If several register ranges share a physical page, a single mapping can cover that page when the requirements agree. Keep the original register bounds in your device description, since rounding to a page boundary does not grant permission to touch additional registers.

High virtual regions and their physical targetsHigh virtualregionPhysicaltargetImageKernelsectionsLoaded RAMframesHeapConsecutivevirtual pagesReserved RAMframesUARTUART registermapping0x10000000PLIC and CLINTSeparateregistermappingsReportedregisterrangesVirtioTransportregistermappingsReported MMIOranges
The image and heap resolve to RAM frames, while the device mappings resolve to physical register pages

For the lab's writable device ranges, use valid supervisor-only read/write leaves with X and U clear. Set A and D for these eager mappings so first access does not require an accessed or dirty bit fixup. Page permissions and memory type are separate. In base Sv39, the physical memory attributes of the platform determine the behavior of the mapped device addresses. Leave the PTE extension bits clear for that setup. The default CPU of QEMU 8.2 does not list svpbmt in the riscv,isa string of its device tree, so those bits stay reserved there. If Svpbmt is supported and enabled for supervisor use, the IO page-based memory type can explicitly request I/O semantics for a device leaf. The NC type describes non-cacheable ordinary memory and has different ordering semantics. Use the Linux device I/O documentation's distinction between an I/O mapping and ordinary RAM as a reference when deciding which semantics the Rust driver needs. Device I/O access and mapping attributes

Keep register accesses volatile and use the width specified by the device. Volatile accesses make the compiler perform the register access. For sequences that require hardware ordering, such as publishing RAM writes before notifying a device, use the ordering operations required by the driver and architecture. Creating the PTE supplies the translation. The register access happens later through the resulting virtual pointer.

{{< callout type="hardware" >}} An S-mode mapping gives the CPU a translation to the physical range. Firmware restrictions and device privilege rules still apply. Keep using the SBI timer interface from the timer lesson. A CLINT mapping alone gives no reason to probe its registers from S-mode. In a real run on QEMU 8.2.2 with OpenSBI v1.3, the banner listed Domain0 Region00 : 0x0000000002000000-0x000000000200ffff M: (I,R,W) S/U: (), and an S-mode load of mtime at 0x200bff8 through a valid leaf raised scause 5 (load access fault). PLIC and virtio-mmio registers could be read from S-mode. {{< /callout >}}

Switch the existing polled UART driver to its high virtual base before the first high-side print. Apply the same base-address rule to PLIC and virtio pointers. For this lesson you can verify their page-table translations without enabling interrupts, sending device requests, or probing registers that may have side effects. Walk the tables at each mapped base and at the last page of each range. Check the physical address, permissions, and memory type where applicable. A working UART tests the UART mapping and the high print path. The other ranges need their own checks.

Map a small initial heap range using frames reserved for the heap by the physical frame allocator. Install supervisor-only read/write leaves with execution disabled and normal RAM attributes. The heap's virtual pages can be consecutive even if their physical frames are scattered. Feed the high virtual start and mapped length to the existing heap allocator after the pages are ready. For a sanity check, write distinct values into two different heap pages before handing that range to the allocator, then read both values back. This detects a common error in a mapping loop where two virtual pages refer to the same physical frame. A page-table walk can confirm that each page has its intended frame and that the heap range and device window are disjoint.

03

Choose the page size for each region

2 min read
Going deeperExplore the mechanism

Sv39 lets a single leaf PTE describe a 4 KiB, 2 MiB, or 1 GiB region. A 4 KiB mapping terminates the walk at level 0. A leaf at level 1 covers 2 MiB, and a leaf at level 2 covers 1 GiB. For either , both the virtual start and physical start must be aligned to the mapping size. The physical range must be contiguous, and the entire region shares the leaf's permissions and page-based memory type.

Sv39 leaf level and coverageLevel 21 GiBLevel 12 MiBLevel 04 KiBAlign both starts tothe leaf size.
A leaf higher in the Sv39 page-table walk covers a larger aligned range

One 2 MiB leaf can describe the same aligned range as 512 leaves of 4 KiB. That reduces the number of PTEs and can reduce TLB pressure, since the hart can cache a translation covering a larger range. The gain is most relevant when the kernel actually accesses many pages in that range. If you reserve a full large page of RAM for a smaller allocation, the unused space within the reservation is internal fragmentation. If you map a larger device range to obtain the same convenience, the excess coverage can expose unrelated registers or holes and force a single permission and memory-type choice on the entire range.

Use 4 KiB leaves for the first implementation. They allow the boot code to map just the register pages it needs, keep text permissions distinct from writable data, and back the heap with individual RAM frames. A large, aligned range of contiguous RAM with uniform permissions and attributes is a candidate for a superpage. The fact that the kernel starts at a large-page-aligned virtual address tells you only one of the conditions is satisfied. Check the physical start, length, and permission boundaries before choosing the leaf level.

In QEMU, the decisive check is a UART message printed by the high code after removing the temporary identity mappings. Confirm the high program counter and stack pointer in GDB, and confirm the driver uses a high virtual base that resolves to 0x10000000. If execution stops at the instruction after satp, inspect the identity mapping first. If it reaches the high entry but the console stays silent, inspect the UART base, its leaf, and the physical access permissions before changing the UART setup.

Once the stack is accessible at its high address, the next lesson, Guard pages for stacks, shows how leaving a page unmapped can turn stack overflow into a fault before it reaches neighboring memory.

Key takeaways

  • The low bootstrap and high kernel can use the same physical image through different virtual mappings.
  • The instructions immediately after the satp write need a valid translation at the current program counter.
  • MMIO uses supervisor-only, non-executable mappings and platform-appropriate device memory attributes.
  • An Sv39 superpage requires an aligned, physically contiguous range with uniform permissions and attributes.
Reflect
  1. Explain to a colleague, in two sentences: distinguish the kernel's physical load address from its high virtual link address.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close