Virtual Memory, Paging, and Address Spaces
local graph
Chapter 7 — Virtual Memory, Paging, and Address Spaces
Section titled “Chapter 7 — Virtual Memory, Paging, and Address Spaces”Chapter 7: Virtual Memory, Paging, and Address Spaces
Section titled “Chapter 7: Virtual Memory, Paging, and Address Spaces”Virtual memory is the point where memory management becomes more than a list of physical ranges. A physical frame allocator can tell the kernel which page-sized chunks of RAM are available, but the processor does not simply let the kernel use every physical address as if it were an ordinary pointer. In long mode, x86_64 uses paging. The addresses your Rust code uses are virtual addresses, and the CPU translates them through page tables before it reaches physical memory. That translation step gives the kernel control, but it also creates one of the most common sources of early faults.
Paging is powerful because it separates the address a program uses from the physical location where data is stored. The kernel can map different virtual addresses to different physical frames, mark pages as writable or read-only, prevent execution from data pages, leave guard pages unmapped, isolate future user processes from the kernel, and build dynamic regions such as heaps and stacks. The same mechanism also makes memory bugs easier to detect when it is used carefully. An unmapped guard page can turn a stack overflow into a page fault instead of silent corruption. A read-only mapping can catch accidental writes to kernel text or read-only data. A non-executable mapping can stop code from running where only data should exist.
Paging also raises the cost of incorrect assumptions. If the kernel treats a physical address as a virtual pointer without a valid mapping, it will fault. If it maps a page with the wrong flags, the CPU may reject the access. If it changes a mapping but forgets to flush stale translation state, the processor may continue using an old translation. If it allocates a page table from a frame that overlaps protected memory, later faults may appear unrelated to the allocator. This is why virtual memory must be built on top of the physical memory work already done. Page tables need physical frames, and those frames must come from safe, usable memory.
This stage gives the kernel a controlled way to create and remove mappings. It also introduces the difference between physical frames and virtual pages, the role of multi-level page tables, and the practical tradeoffs between identity mapping, higher-half mapping, and offset mapping. The goal is not only to make mappings work once. The goal is to understand the rules well enough to debug them when they fail. A kernel that can map pages, unmap them, flush translations, and print useful page-fault diagnostics is ready to support heap allocation, dynamic stacks, memory-mapped devices, and later address-space isolation.
7.1: Pages, Frames, Page Tables, and Address Translation
Section titled “7.1: Pages, Frames, Page Tables, and Address Translation”Virtual memory begins with a distinction that must stay clear throughout kernel development: a page is a unit of virtual memory, while a frame is a unit of physical memory. They are often the same size, commonly 4096 bytes in early x86_64 work, but they are not the same thing. A virtual page has a virtual address. A physical frame has a physical address. Page tables connect them by saying that a given virtual page maps to a given physical frame with a set of permissions and attributes.
When Rust code uses a pointer, the CPU treats the pointer value as a virtual address. The processor does not automatically interpret that value as physical RAM. It walks the active page-table hierarchy to translate the virtual address into a physical address. If the translation exists and the flags allow the requested access, the operation proceeds. If the translation is missing or the permissions do not allow the access, the CPU raises a page fault.
This is a major shift from thinking of memory as one flat set of addresses. The physical memory map describes RAM and device regions from the machine’s perspective. The virtual address space describes what the running code can access through its pointer values. The kernel controls the relationship between the two. It may map a physical frame at one virtual address, at multiple virtual addresses, or not at all. It may map device
memory into a virtual range used only by a driver. It may leave an entire range unmapped so that accidental accesses fault immediately.
On x86_64 in the common four-level paging mode, address translation uses a hierarchy of page tables. The top-level table is selected by the cr3 register. A virtual address is divided into indexes that select entries at each level. The processor starts with the level 4 table, reads the entry selected by part of the virtual address, follows it to the next-level table, repeats the process, and eventually reaches an entry that maps the final page to a physical frame. The lowest bits of the virtual address are the offset inside the page. That offset is carried through to the physical frame after translation.
The table hierarchy exists because a full page table for every possible virtual page would be enormous. Multi-level paging allows sparse address spaces. If a large region of virtual memory is unused, the kernel does not need to allocate all lower-level tables for it. It creates tables only for the areas it maps. This is one reason the physical frame allocator is needed before the kernel can create new mappings. When the mapper needs a lower-level table that does not exist, it must allocate a physical frame to store that table.
Each page-table entry contains a physical frame address and flags. The present flag indicates whether the entry is valid. The writable flag controls write access. The user-accessible flag controls whether less privileged code can access the page. The no-execute flag, when supported and enabled, can prevent instruction fetch from that page. Other flags control caching behavior, accessed and dirty state, huge-page mappings, and additional processor-specific behavior. Early kernel code usually focuses on present, writable, user, no-execute, and a few caching-related flags for device memory.
The present bit is the first gate. If a page-table entry is not present, an access through that translation path causes a page fault. The writable bit is another common source of faults. If a page is mapped read-only and the kernel writes to it, the CPU raises a page fault with an error code indicating a protection violation caused by a write. This is a helpful failure when it is intentional. It can protect read-only kernel data or catch accidental writes. It is frustrating only when the mapping flags were set incorrectly.
The user-accessible flag becomes important when the kernel later supports user mode. For now, most kernel pages should not be user-accessible. Early code runs in ring 0, so this flag may not seem urgent, but the habit matters. Kernel mappings should be created with their future privilege policy in mind. When user processes are added, every mapping that accidentally allows user access becomes a potential security problem. A professional kernel design treats page permissions as policy, not decoration.
The no-execute flag helps separate code from data. When a page is marked non-executable, the CPU will fault if it tries to fetch instructions from that page. This can prevent certain classes of memory-corruption bugs from turning data into executable code. Early kernels may not enable or use this flag consistently at first, but the concept should be present in the design. Kernel text can be executable and read-only. Heap and stack pages can be writable and non-executable. Device memory can have carefully chosen caching behavior and should not be treated like ordinary code or data.
Huge pages are another feature worth understanding before using them. x86_64 supports larger mappings, such as 2 MiB pages and, on capable systems, 1 GiB pages. These can reduce page-table overhead and improve translation efficiency. They are useful in mature kernels, especially for direct physical memory mappings or large contiguous regions. Early kernel code should usually begin with 4 KiB pages because they make allocation, testing, and protection easier to reason about. Once the basic mapper works, huge pages can be introduced deliberately.
The active page-table hierarchy is selected by cr3. Reading cr3 tells you the physical frame containing the active top-level table. Writing cr3 switches to another address space and usually flushes a large part of the processor’s cached translations. Switching address spaces is a serious operation because the new tables must map the code, stack, CPU tables, and data needed immediately after the switch. If they do not, the kernel can fault at once.
The processor also caches translations in the Translation Lookaside Buffer. The TLB exists because walking page tables for every memory access would be expensive. When a virtual-to-physical translation is used, the CPU may
cache it. If the kernel changes a page-table entry, the CPU might still have the old translation cached. This is why mapping changes need flushes. After unmapping a page or changing its permissions, the kernel must invalidate the affected translation or reload cr3, depending on the situation and design. Forgetting this can produce bugs where the page table says one thing but the CPU behaves as if the old mapping still exists.
Virtual memory also introduces address-space design. At first, the kernel may use one address space for everything. That is fine. Later, each process can have its own page-table hierarchy, with private user mappings and shared kernel mappings. The kernel can then switch cr3 during context switches so each process sees its own virtual memory. The same virtual address can point to different physical frames in different processes. This is the foundation of process isolation. That advanced use depends on the same basic mechanisms you are setting up now.
Three mapping patterns appear often in early kernels: identity mapping, higher-half mapping, and offset mapping. Identity mapping maps a physical address to the same virtual address. If physical frame 0x1000 is identity-mapped, virtual address 0x1000 refers to that frame. This is easy to understand and useful during early boot, but it can limit design and expose low physical memory at low virtual addresses. Higher-half mapping places the kernel at a high virtual address range. This keeps low addresses unmapped or available for user processes later, and it follows a design used by many kernels. Offset mapping maps physical memory into a virtual range at a fixed offset, so a physical address can be accessed by adding that offset. This is especially useful for page-table manipulation because the kernel can access physical frames through predictable virtual addresses.
None of these patterns is universally best. Identity mapping is simple. Higher-half mapping is cleaner for long-term kernel layout. Offset mapping is practical for accessing physical memory from the kernel. Many kernels use more than one pattern. For example, the kernel may be higher-half mapped while physical memory is also available through an offset mapping. The important point is to know which mappings exist before writing code that depends on them. A pointer value is meaningful only if the current address space maps it as expected.
Virtual memory makes the kernel more capable, but it also makes correctness more formal. A function that maps a page should know which virtual page it is mapping, which physical frame backs it, which flags are used, whether a lower-level page table must be created, and whether the TLB must be flushed. A function that unmaps a page should know what happens to the physical frame afterward. Does the frame return to the allocator? Is it page-table memory? Is it device memory that should never be freed? These policies must be explicit.
The most important discipline in this stage is to avoid mixing address types. A virtual address is not a physical address. A pointer is not automatically safe because it has a numeric value. A physical frame address should not be dereferenced unless the kernel has a virtual mapping for it. A page-table entry contains a physical address, but editing the page table requires accessing the table through a virtual address. Many paging bugs come from confusing these categories. Strong Rust types can help if you use them consistently. Separate types for virtual addresses, physical addresses, pages, and frames are not verbosity. They are protection against wrong assumptions.
7.2: Mapping and Unmapping Virtual Pages
Section titled “7.2: Mapping and Unmapping Virtual Pages”Mapping a virtual page means creating page-table entries that translate that page to a physical frame. Unmapping means removing that translation. These operations are central to almost every memory feature that follows. The heap needs mapped pages. Kernel stacks need mapped pages. Device buffers may need mappings. Page-table memory itself must be allocated from physical frames and then accessed through virtual mappings. A correct mapper gives the kernel a controlled way to shape its address space.
The simplest useful mapping function receives a virtual page address, a physical frame address, flags, and a frame allocator. The frame allocator is needed because the page-table hierarchy may not already contain all intermediate tables for the virtual page. If a lower-level table is missing, the mapper must allocate a frame for it, clear it, and link it into the hierarchy.
This is why paging depends on the physical frame allocator from the previous stage.
In practical Rust kernel code, it is common to use architecture support types for pages, frames, page-table flags, and mapping operations. These types reduce bit-level mistakes and keep address categories clear. The following example shows the shape of a mapping function using a mapper and frame allocator abstraction.
Rust
use x86_64::{ PhysAddr, VirtAddr, structures::paging::{ FrameAllocator, Mapper, Page, PageTableFlags, PhysFrame, Size4KiB, },};
pub unsafe fn map_page_to_frame<M, A>( mapper: &mut M, frame_allocator: &mut A, virtual_address: VirtAddr, physical_address: PhysAddr,) where M: Mapper<Size4KiB>, A: FrameAllocator<Size4KiB>,{ let page = Page::containing_address(virtual_address); let frame = PhysFrame::containing_address(physical_address);
let flags = PageTableFlags::PRESENT | PageTableFlags::WRITABLE;
let flush = unsafe { mapper .map_to(page, frame, flags, frame_allocator) .expect("failed to map page") };
flush.flush();}This function maps the page containing virtual_address to the frame containing physical_address. It uses present and writable flags. The call to map_to is unsafe because the mapper cannot verify all memory-management invariants on its own. You must ensure that the frame is safe to use for the intended purpose, that the mapping does not violate ownership rules, and that aliasing is acceptable. If two virtual pages map to the same physical frame with writable access, then writes through one alias affect the other. That may be intentional in some designs, but it must not happen accidentally.
The returned flush value represents a required TLB invalidation for that page. Calling flush.flush() ensures the processor does not continue using stale translation information. In some cases, a newly mapped page may not have been cached before, but flushing is still the correct pattern supplied by the mapper operation. When changing mappings, be disciplined about invalidation. TLB bugs can be confusing because the page tables in memory may look correct while the CPU still uses an older cached translation.
The previous function panics if mapping fails. That is acceptable for some early initialization paths, but a more controlled function should return a result. Mapping can fail because a page is already mapped, because the frame allocator is out of frames for intermediate tables, or because the mapper encounters an invalid state. Returning a result lets the caller decide whether to panic, report the error, or recover.
Rust
use x86_64::{ PhysAddr, VirtAddr, structures::paging::{ FrameAllocator, MapToError, Mapper, Page, PageTableFlags, PhysFrame, Size4KiB, },};pub unsafe fn try_map_page_to_frame<M, A>( mapper: &mut M, frame_allocator: &mut A, virtual_address: VirtAddr, physical_address: PhysAddr, flags: PageTableFlags,) -> Result<(), MapToError<Size4KiB>>where M: Mapper<Size4KiB>, A: FrameAllocator<Size4KiB>,{ let page = Page::containing_address(virtual_address); let frame = PhysFrame::containing_address(physical_address); let flags = flags | PageTableFlags::PRESENT;
let flush = unsafe { mapper.map_to(page, frame, flags, frame_allocator)? };
flush.flush();
Ok(())}This version accepts flags from the caller and returns an error instead of panicking. It still ensures the present flag is set because a mapping without the present flag is not usable as an ordinary translation. The caller can choose read-only, writable, executable, non-executable, or device-specific caching flags where appropriate. This is a better shape for a memory subsystem because mapping policy belongs to the caller’s purpose, not inside one hard-coded helper.
Mapping a range is usually more useful than mapping a single page. Heap setup, stacks, and buffers often need multiple consecutive virtual pages. A range mapper can walk page by page and map each virtual page to consecutive physical frames, or allocate frames one by one if the physical backing does not need to be contiguous. For heap allocation, physical contiguity is usually not required. Each virtual page can be backed by any available frame. The virtual range appears contiguous to the kernel even if the physical frames are scattered.
Rust
use x86_64::{ VirtAddr, structures::paging::{ FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB, }, };
pub unsafe fn map_allocated_range<M, A>(
mapper: &mut M,
frame_allocator: &mut A,
start: VirtAddr,
size_in_bytes: u64,
flags: PageTableFlags,
) -> Result<(), &‘static str>
where
M: Mapper
for page in page_range { let frame = frame_allocator .allocate_frame() .ok_or("frame allocation failed while mapping range")?;
let flush = unsafe { mapper .map_to(page, frame, flags | PageTableFlags::PRESENT, frame_allocator) .map_err(|_| "page mapping failed")? };
flush.flush();}
Ok(())}
This function maps a virtual range using newly allocated physical frames. It is useful for future heap setup because the heap needs a virtual range backed by physical memory. It assumes size_in_bytes is not zero. A more
defensive version should handle zero-length ranges explicitly and avoid subtracting one from zero.
Rust
use x86_64::{ VirtAddr, structures::paging::{ FrameAllocator, Mapper, Page, PageTableFlags, Size4KiB, },};
unsafe fn try_map_allocated_range<M, A>( mapper: &mut M, frame_allocator: &mut A, start: VirtAddr, size_in_bytes: u64, flags: PageTableFlags,) -> Result<(), &'static str>where M: Mapper<Size4KiB>, A: FrameAllocator<Size4KiB>,{ if size_in_bytes == 0 { return Ok(()); }
let start_page = Page::containing_address(start); let end_address = start + size_in_bytes - 1u64; let end_page = Page::containing_address(end_address); let page_range = Page::range_inclusive(start_page, end_page);
for page in page_range { let frame = frame_allocator .allocate_frame() .ok_or("frame allocation failed while mapping range")?;
let mapping_flags = flags | PageTableFlags::PRESENT;
let flush = unsafe { mapper .map_to(page, frame, mapping_flags, frame_allocator) .map_err(|_| "page mapping failed")? };};
flush.flush();
}
Ok(())}This version behaves more predictably for zero-length input. The difference is small, but it matters because memory code should not rely on friendly inputs. A mapping function may later be called by heap setup, stack setup, test code, or device code. If an empty range is valid input, it should do nothing and succeed. If it is invalid for a particular caller, that caller can reject it before calling the mapper.
Unmapping a page removes its translation from the active address space. This is more dangerous than it may first appear. If the kernel unmaps a page that contains code currently executing, the active stack, the IDT, the GDT, the TSS, page tables, or output device mappings, the next access can fault. Unmapping should therefore be done only with pages whose ownership and purpose are known.
use x86_64::{ VirtAddr, structures::paging::{ Mapper, Page, Size4KiB, mapper::UnmapError, },};
pub fn unmap_page<M>( mapper: &mut M, virtual_address: VirtAddr,) -> Result<(), UnmapError>where M: Mapper<Size4KiB>,{ let page = Page::containing_address(virtual_address); let (_frame, flush) = mapper.unmap(page)?;flush.flush();
Ok(())
}
This function unmaps the page containing the virtual address and flushes the translation. The mapper returns the physical frame that was previously mapped. The example ignores it, but real code must decide what to do with that frame. If the frame belongs to ordinary allocated memory, it may be returned to the frame allocator once a freeing allocator exists. If it belongs to device memory, kernel image memory, or a shared mapping, it must not be freed. Unmapping and freeing are separate decisions.
a more explicit function returns the frame to the caller so ownership can be handled outside the unmap operation.
Rust
use x86_64::{ PhysAddr, VirtAddr, structures::paging::{ Mapper, Page, Size4KiB, mapper::UnmapError, }, };
pub fn unmap_page_and_return_frame
flush.flush();
Ok(frame.start_address())}
This shape makes the physical frame visible to the caller. That caller can log it, inspect it, or later return it to a frame allocator that supports freeing. Until frame freeing is implemented, it is reasonable to leak the frame intentionally rather than risk returning it incorrectly. A one-way allocator is wasteful but safe during early initialization. Incorrect freeing is dangerous.
Mapping code also needs a way to create a mapper for the active page table. On x86_64, the active top-level page-table frame is stored in cr3. To edit page tables, the kernel must access the memory containing those tables through a virtual address. One common strategy is offset mapping, where all physical memory is mapped at a fixed virtual offset. If physical memory is available at such an offset, the kernel can convert the physical address from cr3 into a virtual address by adding the offset.
Rust
use x86_64::{ PhysAddr, VirtAddr, registers::control::Cr3, structures::paging::{OffsetPageTable, PageTable},};
pub unsafe fn active_level_4_table( physical_memory_offset: VirtAddr,) -> &'static mut PageTable { let (level_4_frame, _) = Cr3::read(); let physical = level_4_frame.start_address(); let virtual_address = physical_memory_offset + physical.as_u64(); let page_table_ptr: *mut PageTable = virtual_address.as_mut_ptr();
unsafe { &mut *page_table_ptr }}
pub unsafe fn init_mapper( physical_memory_offset: VirtAddr,) -> OffsetPageTable<'static> { let level_4_table = unsafe { active_level_4_table(physical_memory_offset) };}unsafe { OffsetPageTable::new(level_4_table, physical_memory_offset)}This code is unsafe for a serious reason. It assumes that physical memory is mapped at the provided virtual offset and that the active level 4 page table can be accessed through that mapping. If the offset is wrong, the pointer will be invalid. If the page table memory is not mapped, dereferencing the pointer will fault. If another part of the kernel also holds a mutable reference to the same page table, Rust’s aliasing rules are violated. The safety of this function depends on global paging invariants.
Mapping and unmapping are not isolated tricks. They require correct physical frame allocation, correct page-table access, correct flags, correct TLB flushing, and clear ownership policy. When these functions are shaped carefully, later memory features become much easier. When they are casual, the kernel can corrupt itself in ways that are extremely hard to diagnose.
7.3: Higher-Half Kernels, Offset Mapping, and Identity Mapping
Section titled “7.3: Higher-Half Kernels, Offset Mapping, and Identity Mapping”The layout of virtual memory is a design decision. The kernel can choose where its code appears in the virtual address space, where physical memory is accessible, where the heap will live, where stacks will grow, and which areas remain unmapped. Early in boot, the bootloader may already have chosen some mappings so the kernel can start. As the kernel matures, it should understand those mappings and eventually control its own layout.
Identity mapping is the simplest mapping pattern. A physical address is mapped to the same virtual address. If physical memory at 0x100000 is identity-mapped, the kernel can access it through virtual address 0x100000. This is easy to reason about during early boot because physical and virtual numbers match. It can also be useful for firmware transitions, low-memory structures, or temporary setup.
The limitation is that identity mapping exposes physical memory at low virtual addresses. In a future system with userspace, low addresses are often reserved for user processes, while the kernel lives in a higher range. Keeping low addresses unmapped can also help catch null pointer bugs. If virtual address zero is not mapped, dereferencing a null pointer produces a page fault instead of reading or writing real memory. Identity mapping everything makes that protection impossible.
A higher-half kernel is mapped into a high virtual address range. The kernel may be loaded at some physical address, but it executes at a high virtual address. This keeps the kernel away from low user-space ranges and gives the address space a clean separation. Many operating systems use a design where the kernel is visible in a high portion of every address space, while user processes occupy lower ranges. When the CPU switches between processes, the kernel mappings remain available so system calls, interrupts, and faults can enter the kernel.
Higher-half design requires the linker, bootloader, and page tables to agree. If the kernel is linked to execute at a high virtual address, the page tables must map that virtual range to the physical frames where the kernel image is loaded. If the bootloader jumps to the wrong address or the mapping is missing, the kernel will not execute correctly. This is why higher-half mapping is a stronger long-term design but more demanding than identity mapping.
Offset mapping is another useful pattern. In an offset mapping, physical memory is mapped into a virtual range by adding a fixed offset. If the physical memory offset is 0xffff_8000_0000_0000, then physical address 0x1000 can be accessed at virtual address 0xffff_8000_0000_1000. This gives the kernel a predictable way to access physical frames through virtual addresses. It is especially useful for page-table management because page-table entries store physical addresses, but the kernel needs virtual addresses to edit the tables.
A helper function can express the conversion from physical address to virtual address when an offset mapping exists.
use x86_64::{PhysAddr, VirtAddr};
#[derive(Debug, Clone, Copy)]pub struct PhysicalMemoryOffset { offset: VirtAddr,}
impl PhysicalMemoryOffset { pub const fn new(offset: VirtAddr) -> Self { Self { offset } }
pub fn physical_to_virtual(&self, physical: PhysAddr) -> VirtAddr { self.offset + physical.as_u64() }}This type is small but useful. It prevents the offset from being passed around as an anonymous integer. The conversion function says what is happening: a physical address is being translated into a virtual address through the direct physical memory mapping. This does not prove the mapping exists. It only performs the arithmetic. The bootloader and page tables must provide the actual mapping.
A reverse conversion may also be useful, but it should be handled carefully. Not every virtual address belongs to the offset mapping. The kernel’s higher-half text address, heap address, or stack address may not be convertible to a physical address by subtracting the offset. The helper should reject virtual addresses outside the direct map range.
use x86_64::{PhysAddr, VirtAddr};
#[derive(Debug, Clone, Copy)]pub struct DirectMap { start: VirtAddr, size: u64,}
impl DirectMap {pub const fn new(start: VirtAddr, size: u64) -> Self { Self { start, size } }
pub fn physical_to_virtual(&self, physical: PhysAddr) -> Option
Some(self.start + physical.as_u64())}
pub fn virtual_to_physical(&self, virtual_address: VirtAddr) -> Option
let address = virtual_address.as_u64();
if address < start || address >= end { return None;}
Some(PhysAddr::new(address - start))}
This version gives the direct map an explicit size. It avoids converting virtual addresses that do not belong to the mapped range. That is safer than subtracting the offset blindly. Address conversion helpers should be strict because wrong conversions lead to wrong frame addresses, and wrong frame addresses corrupt paging structures.
Identity mapping can be implemented by mapping a physical frame to a virtual page with the same numeric address. This is sometimes useful for early tests or device regions where identity access is expected temporarily.
Rust
use x86_64::{ PhysAddr, VirtAddr, structures::paging::{ FrameAllocator, Mapper, }, };
PageTableFlags, Size4KiB, ), };
pub unsafe fn identity_map_frame<M, A>(
mapper: &mut M,
frame_allocator: &mut A,
physical_address: PhysAddr,
flags: PageTableFlags,
) -> Result<(), &‘static str>
where
M: Mapper
unsafe { try_map_page_to_frame( mapper, frame_allocator, virtual_address, physical_address, flags, ) .map_err(|_| "identity mapping failed")}}
This function maps the physical frame at the same numeric virtual address. It should not be used casually to identity-map all memory. Identity mappings should have a clear purpose and a known lifetime. Leaving broad identity mappings in place can weaken the design and hide bugs. For example, code that accidentally treats physical addresses as virtual addresses may appear to work only because identity mapping is present. Later, when the identity mapping is removed, the bug becomes a page fault. It is better to make address conversions explicit.
Mapping a higher-half kernel is usually handled by the bootloader or early assembly setup before Rust code begins. Once the kernel is running, it can inspect or extend the layout, but it should not casually move itself. The linker decides the virtual addresses used by symbols. The bootloader and page tables must make those addresses valid. If the kernel’s code is linked at a high address, function pointers and static references use that high
address. The physical image may be elsewhere. That is normal. The mapping connects the two.
A kernel can define constants for major virtual regions. These constants help keep layout decisions clear.
Rust
use x86_64::VirtAddr;
pub const KERNEL_HEAP_START: VirtAddr = VirtAddr::new(0xffff_9000_0000_0000);pub const KERNEL_HEAP_SIZE: u64 = 1024 * 1024;pub const KERNEL_STACK_GUARD_SIZE: u64 = 4096;These constants do not create mappings. They name planned virtual ranges. Heap setup will later map physical frames into KERNEL_HEAP_START..KERNEL_HEAP_START + KERNEL_HEAP_SIZE. Stack setup can leave guard pages unmapped. Naming layout regions prevents scattering magic addresses throughout the kernel.
A heap mapping function can use the range mapper from the previous section. It maps a virtual heap range to newly allocated physical frames. The heap allocator itself will come later, but the virtual range must be backed first.
Rust
use x86_64::structures::paging::PageTableFlags;
pub unsafe fn map_kernel_heap<M, A>( mapper: &mut M, frame_allocator: &mut A,) -> Result<(), &'static str>where M: x86_64::structures::paging::Mapper<x86_64::structures::paging::Size4KiB>, A: x86_64::structures::paging::FrameAllocator<x86_64::structures::paging::Size4KiB>,{let flags = PageTableFlags::WRITABLE | PageTableFlags::NO_EXECUTE;
unsafe { try_map_allocated_range( mapper, frame_allocator, KERNEL_HEAP_START, KERNEL_HEAP_SIZE, flags, )}This maps the heap as writable and non-executable. The present flag is added by the mapping helper. Marking heap memory non-executable is a good habit because heap pages are for data, not instructions. This assumes no-execute support is enabled in the processor state and respected by the paging abstraction. If it is not available, the flag choice may need adjustment, but the policy remains sound.
Offset mapping is also used to initialize the mapper itself. If the bootloader passes a physical memory offset, the kernel can create an OffsetPageTable for the active page table. The code must be unsafe because it constructs a mutable reference to the active level 4 table through the direct map.
use x86_64::{ VirtAddr, registers::control::Cr3, structures::paging::{OffsetPageTable, PageTable},};
pub unsafe fn create_offset_page_table( physical_memory_offset: VirtAddr,) -> OffsetPageTable<'static> { let (level_4_frame, _) = Cr3::read(); let physical = level_4_frame.start_address(); let virtual_address = physical_memory_offset + physical.as_u64(); let page_table_ptr: *mut PageTable = virtual_address.as_mut_ptr();
let level_4_table = unsafe {&mut *page_table_ptr };
unsafe { OffsetPageTable::new(level_4_table, physical_memory_offset) }
The caller must guarantee that the physical memory offset is correct and that the active page table is accessible through it. This should be called once during memory initialization, not repeatedly from unrelated modules. The returned mapper represents mutable access to the active page tables. Multiple mutable mappers to the same active tables would violate Rust’s aliasing model and could lead to logical races in the kernel’s memory manager.
A clean initialization function can tie these pieces together. It receives the physical memory offset from boot information, creates a mapper, creates or receives a frame allocator, maps the heap range, and prints checkpoints.
use x86_64::VirtAddr;
pub unsafe fn init_virtual_memory<A>( physical_memory_offset: VirtAddr, frame_allocator: &mut A,) where A: x86_64::structures::paging::FrameAllocator<x86_64::structures::paging::Size4KiB>,{ let mut mapper = unsafe { create_offset_page_table(physical_memory_offset) };
serial_println!("active page table mapped through physical memory offset");
unsafe { map_kernel_heap(&mut mapper, frame_allocator) .expect("failed to map kernel heap"); }}
<!-- page: 202 -->
cserial_printfln!("kernel heap virtual range mapped");This function still uses expect because heap mapping failure during early initialization is fatal for this stage. A more complete kernel can return a structured error. The important part is the order and visibility. Create the mapper, report success, map the heap, report success. If a page fault occurs during this sequence, the last printed checkpoint tells you which operation was active.
Identity mapping, higher-half mapping, and offset mapping can coexist, but they must not be confused. Identity mapping is a direct numeric match. Higher-half mapping places the kernel at a high virtual address. Offset mapping gives the kernel a way to access physical memory through a direct virtual window. When writing paging code, say which one you are using. If a function receives a PhysAddr, do not cast it to a pointer unless an identity mapping or direct map makes that pointer valid. If a function receives a VirtAddr, do not treat it as a physical frame unless you can translate it correctly.
A strong virtual memory layout is not built all at once. At this stage, the kernel needs enough structure to access active page tables, create new mappings, avoid accidental address confusion, and prepare a heap range. Later, it can add guard pages, read-only kernel text, non-executable stacks, per-process address spaces, copy-on-write, and memory-mapped files. All of those features depend on the same foundation: pages, frames, flags, page tables, and clear address-space policy.
7.4: Debugging Page Faults, TLB Flushes, and Mapping Errors
Section titled “7.4: Debugging Page Faults, TLB Flushes, and Mapping Errors”Paging bugs are often precise, but they do not always look precise at first. A page fault may appear as a kernel freeze, a panic, a QEMU reset, or a message from the page-fault handler. Once the handler is installed correctly, page faults become one of the best sources of diagnostic information in the kernel. The CPU tells you the accessed address, the type of access, and where execution was interrupted. The kernel’s job is to print
that information clearly and connect it to the mapping logic that produced the failure.
The page-fault handler should read cr2, decode the error code, print the instruction pointer, print the stack pointer, and stop. That gives you the core facts. The accessed address tells you what virtual address failed. The error code tells you whether the page was missing or permissions were wrong. The instruction pointer tells you where the access happened. The stack pointer tells you whether the current stack looked reasonable.
Rust
use x86_64::{ registers::control::Cr2, structures::idt::{InterruptStackFrame, PageFaultErrorCode},};
pub extern "x86-interrupt" fn page_fault_handler( stack_frame: InterruptStackFrame, error_code: PageFaultErrorCode,) { let accessed_address = Cr2::read();
serial_println!("page fault"); serial_println!("accessed address: {:?}", accessed_address); serial_println!("error code: {:?}", error_code); serial_println!("instruction pointer: {:?}", stack_frame.instruction_pointer); serial_println!("stack pointer: {:?}", stack_frame.stack_pointer);
print_page_fault_reason(error_code);
crate::arch::halt_loop();}
fn print_page_fault_reason(error_code: PageFaultErrorCode) { if error_code.contains(PageFaultErrorCode::PROTECTION_VIOLATION) { serial_println!("reason: protection violation"); } else { serial_println!("reason: page not present"); }
if error_code.contains(PageFaultErrorCode::CAUSED_BY_WRITE) { serial_println!("access: write"); }}} else { serial_println!(“access: read or instruction fetch”); }
if error_code.contains(PageFaultErrorCode::USER_MODE) { serial_println!(“origin: user mode”); } else { serial_println!(“origin: kernel mode”); }
if error_code.contains(PageFaultErrorCode::INSTRUCTION_FETCH) { serial_println!(“instruction fetch”); }
This handler is built for clarity. It does not try to fix the fault. Early in the kernel, that is the correct decision. A missing mapping or permission fault usually means the memory manager has a bug. Later, the kernel may intentionally handle some page faults, but doing that too early hides problems. For now, a page fault should produce evidence and halt.
A useful diagnostic helper can inspect whether a virtual page is mapped. If the mapper supports translation, the kernel can ask what physical frame a virtual address resolves to. This can be used before and after mapping operations to verify the result.
use x86_64::{ VirtAddr, structures::paging::{ Mapper, Translate, },};
pub fn print_translation<M>(mapper: &M, virtual_address: VirtAddr)where M: Translate,{ match mapper.translate_addr(virtual_address) { Some(physical_address) => { serial_println!( "translation: {:?} -> {:?}", virtual_address, physical_address, ); } }}virtual_address, physical_address ); } None => { serial_println!( “translation: {:?} is not mapped”, virtual_address ); } }
This function is helpful when testing a new mapping. Before mapping a heap page, it should report that the virtual address is not mapped. After mapping and flushing, it should report the physical address. If it still reports unmapped, the mapping did not reach the active page table or the address checked is not in the same page. If it reports a different physical address than expected, the page was already mapped or the mapper used a different frame than intended.
A mapping test can combine translation checks with a real memory write. The write proves that the CPU can use the translation, not only that the page table contains an entry.
Rust
use x86_64::{ PhysAddr, VirtAddr, structures::paging::{ FrameAllocator, Mapper, PageTableFlags, Size4KiB, Translate, }, };
pub unsafe fn test_single_mapping<M, A>( mapper: &mut M, frame_allocator: &mut A, virtual_address: VirtAddr, physical_address: PhysAddr, ) where
M: Mapper
{ serial_println!(“testing page mapping”); print_translation(mapper, virtual_address);
let flags = PageTableFlags::WRITABLE | PageTableFlags::NO_EXECUTE;
unsafe { try_map_page_to_frame( mapper, frame_allocator, virtual_address, physical_address, flags, ) .expect("test mapping failed");}
print_translation(mapper, virtual_address);
let pointer: *mut u64 = virtual_address.as_mut_ptr();
unsafe { core::ptr::write_volatile(pointer, 0xfeefed_face_cafe_beefu64); let value = core::ptr::read_volatile(pointer); serial_println!("mapped page test value: {:#x}", value);}}
This test maps a virtual page to a chosen physical frame, then writes and reads a value through the virtual address. It uses volatile access so the compiler performs the memory operations. This does not mean the memory is device memory. It means the test wants to force the access for diagnostic purposes. If the mapping is wrong, the write may trigger a page fault. If the flags are wrong, a write may produce a protection violation. If the virtual address was already mapped, the map function should fail rather than silently replacing the mapping.
Mapping errors often come from address alignment. If the code maps the page containing one address but tests a different address outside that page, the test may fault. If the requested physical address is not page-aligned, containing_address will round it down. That may be correct in some
contexts, but it can hide a caller mistake. For mapping physical frames, it is often better to require aligned frame starts.
Rust
use x86_64::{ PhysAddr, VirtAddr, structures::paging::{ FrameAllocator, Mapper, Page, PageTableFlags, PhysFrame, Size4KiB, },};
pub unsafe fn map_aligned_frame<M, A>( mapper: &mut M, frame_allocator: &mut A, virtual_address: VirtAddr, physical_address: PhysAddr, flags: PageTableFlags,) -> Result<(), &'static str>where M: Mapper<Size4KiB>, A: FrameAllocator<Size4KiB>,{ if physical_address.as_u64() % 4096 != 0 { return Err("physical address is not frame aligned"); }
let page = Page::containing_address(virtual_address); let frame = PhysFrame::from_start_address(physical_address) .map_err(|_| "invalid physical frame start")?;
let flush = unsafe { mapper .map_to(page, frame, flags | PageTableFlags::PRESENT, frame_allocator) .map_err(|_| "map_to failed")? };
flush.flush();
Ok(())}This version rejects unaligned physical addresses instead of rounding them silently. The difference is important when the caller believes it is mapping a specific frame. Silent rounding can map a different physical range than intended. Rejection makes the bug visible.
Unmapping errors also need careful diagnosis. If unmapping fails because the page was not mapped, the caller may have the wrong virtual address or may have already unmapped it. If unmapping succeeds but the kernel does not flush the TLB, accesses may still appear to work for a time because the CPU is using a cached translation. This is one of the most confusing paging bugs. The page table says the page is gone, but the CPU still accesses it until the translation is invalidated.
Test for unmapping should unmap, flush, then deliberately access the address only when you expect a page fault. This is a fatal test, so keep it gated or run it in a controlled test kernel.
use x86_64::{ VirtAddr, structures::paging::{ Mapper, Size4KiB, Translate, },};
pub fn test_unmap<M>( mapper: &mut M, virtual_address: VirtAddr,) where M: Mapper<Size4KiB> + Translate,{ serial_println!("testing unmap"); print_translation(mapper, virtual_address);
unmap_page(mapper, virtual_address).expect("unmap failed");
print_translation(mapper, virtual_address);
serial_println!("about to access unmapped page");
let pointer: *const u64 = virtual_address.as_ptr();unsafe { let _ = core::ptr::read_volatile(pointer);}The final access should fault if the unmap and flush worked. If it does not fault, the page may still be mapped, the wrong address may have been unmapped, or stale translation state may remain. This test should not run during ordinary startup because its expected result is a fault.
TLB flushing must match mapping changes. When a single page is mapped, unmapped, or has permissions changed, invalidating that page is usually enough. Reloading cr3 is a broader flush, but it is heavier and affects more translations. Early kernels can use the flush object returned by mapping operations. That keeps the operation local and correct.
pub fn flush_page(address: x86_64::VirtAddr) { x86_64::instructions::tlb::flush(address);}This helper is useful when code changes page-table entries through a lower level path and needs to invalidate one address. If you use mapper operations that return flush values, prefer those because they tie the flush to the mapping operation. Manual flushing should be used when you clearly know which virtual address was affected.
Mapping errors can also come from using the wrong address-space model. If the kernel receives a physical address from the bootloader and casts it directly to a pointer, that will work only if the physical address is also mapped at the same virtual address or if the address falls inside another valid mapping. With an offset mapping, you must add the physical memory offset. With a higher-half kernel, symbol addresses may be high virtual addresses while physical memory lies elsewhere. If a page fault shows an accessed address that looks like a raw physical address, check whether you forgot the physical-to-virtual conversion.
use x86_64::{PhysAddr, VirtAddr};
pub unsafe fn read_u64_from_physical( physical_memory_offset: VirtAddr, physical_address: PhysAddr,) -> u64 { let virtual_address = physical_memory_offset + physical_address.as_u64(); let pointer: *const u64 = virtual_address.as_ptr();
unsafe { core::ptr::read_volatile(pointer) }}This function reads through an offset mapping. It is unsafe because the caller must guarantee that the physical memory offset is valid, that the physical address is mapped through it, that reading a u64 at that address is aligned and meaningful, and that the memory is safe to access. This is far better than pretending a physical address is always a pointer. The conversion is visible and tied to the direct map.
Page-table debugging can also print the active cr3 frame. If you suspect the kernel is editing one page table while the CPU is using another, cr3 is the first value to inspect.
use x86_64::registers::control::Cr3;
pub fn print_active_cr3() { let (frame, flags) = Cr3::read();
serial_println!("active cr3 frame: {:?}", frame); serial_println!("cr3 flags: {:?}", flags);}Call this before and after operations that might switch address spaces. In the current kernel, address-space switching may not exist yet, so the value should remain stable. Later, when per-process page tables are introduced, cr3 changes will become part of normal scheduling behavior.
A useful paging debug function can combine several facts: active page table, translation status, and page-fault context. The page-fault handler can call into a small diagnostic routine that prints nearby information without allocating memory.
use x86_64::{ VirtAddr, registers::control::{Cr2, Cr3}, structures::idt::{InterruptStackFrame, PageFaultErrorCode},};
pub fn print_page_fault_diagnostics( stack_frame: InterruptStackFrame, error_code: PageFaultErrorCode,) { let accessed_address = Cr2::read(); let (cr3_frame, cr3_flags) = Cr3::read();
serial_println!("page fault diagnostics"); serial_println!("accessed address: {:?}", accessed_address); serial_println!("error code: {:?}", error_code); serial_println!("instruction pointer: {:?}", stack_frame.instruction_pointer); serial_println!("stack pointer: {:?}", stack_frame.stack_pointer); serial_println!("active cr3 frame: {:?}", cr3_frame); serial_println!("cr3 flags: {:?}", cr3_flags);}This routine keeps page-fault output consistent. It avoids heap allocation and relies only on serial output. If formatting itself becomes risky in a fatal path, the kernel can later add a lower-level emergency serial writer. For now, this level of diagnostic output is a major improvement over a reset or vague panic.
When a page fault occurs after mapping code changes, read the output carefully. If the accessed address is the virtual address you were trying to map, the mapping may not have been installed, the wrong address space may be active, or the page-table walk may be missing a lower-level table. If the error code says protection violation on write, the page may be present but not writable. If the fault is an instruction fetch, the code may have
jumped to a non-executable or unmapped page. If the stack pointer is in an unmapped or suspicious range, the fault may be related to stack setup. If cr3 is not the page table you expected, the kernel may be editing the wrong address space.
Mapping bugs should be fixed at the source, not hidden by broad mappings. If a driver faults while accessing framebuffer memory, do not identity-map all physical memory just to make the fault disappear. Map the framebuffer range with the correct flags and a clear owner. If heap initialization faults, check that the heap range was mapped before the allocator uses it. If pageable editing faults, check that physical memory offset mapping is correct. Broad emergency mappings can hide address confusion and make the design weaker.
The long-term value of this stage is confidence. Once the kernel can map pages, unmap them, flush translations, inspect active mappings, and print useful page-fault reports, memory work becomes much more controlled. Heap allocation will still have its own risks. Device memory will still require careful flags. Future userspace will add privilege and isolation issues. But the foundation is now strong enough to show you what went wrong. In kernel development, that visibility is often the difference between a fixable bug and a silent failure.