Physical Memory and Boot Memory Maps
local graph
Chapter 6 — Physical Memory and Boot Memory Maps
Section titled “Chapter 6 — Physical Memory and Boot Memory Maps”Chapter 6: Physical Memory and Boot Memory Maps
Section titled “Chapter 6: Physical Memory and Boot Memory Maps”Physical memory management is where the kernel begins taking real ownership of the machine. Until this point, the kernel has depended heavily on the bootloader’s preparation. The bootloader loaded the kernel image, prepared the initial execution state, supplied a stack, and passed startup information. That is enough to begin execution, but it is not enough to manage memory safely. A kernel cannot allocate frames, build page tables, create heap space, or protect device memory until it knows which physical memory regions exist and which ones are safe to use.
The first rule of physical memory is simple: not all memory is available. Some regions contain the kernel image. Some contain boot information. Some are reserved by firmware. Some are used by devices. Some contain framebuffer memory. Some may be usable later but must be handled with special care. If the kernel treats every address as free RAM, it will eventually overwrite something important. That kind of bug can look random because the visible failure may occur long after the original corruption.
The memory map is the first reliable guide. It describes physical address ranges and their intended use. The bootloader normally obtains this information from firmware and passes it to the kernel in a structured form. The kernel then interprets that map and decides which regions can feed the physical frame allocator. From there, the kernel can hand out page-sized physical frames to paging code, heap setup, stacks, and other memory subsystems.
This stage requires conservative design. A frame allocator is powerful because every frame it returns may later become page-table memory, heap backing storage, or kernel data. If the allocator returns a frame that overlaps the kernel image, the kernel may overwrite its own code. If it returns a frame that overlaps the boot information structure, later initialization may read corrupted data. If it returns framebuffer memory, screen output may become unstable or memory writes may damage device state. Good physical
memory management is not about grabbing as much memory as possible. It is about using only memory the kernel can justify.
6.1: Reading the Bootloader Memory Map
Section titled “6.1: Reading the Bootloader Memory Map”The bootloader memory map is the kernel’s first structured description of physical memory. It usually consists of a set of entries, where each entry describes a starting physical address, a length, and a region type. The region type tells the kernel whether the region is available for general use, reserved, used by firmware, used by the bootloader, associated with ACPI data, assigned to a framebuffer, or otherwise unavailable. The exact names and categories depend on the boot protocol, but the principle is consistent: the kernel must not allocate physical memory blindly.
A memory map is not the same thing as a heap. It does not hand out memory. It does not track allocations. It does not automatically protect the kernel from overwriting itself. It is input data. The kernel must parse it, validate it, normalize it where necessary, and feed only safe ranges into an allocator. Treating the memory map as an allocator is a common design mistake. The map describes what exists. The allocator decides what can be used now.
A simple internal representation can begin with a memory-region type and a region structure. Even if the bootloader provides its own structures, the kernel benefits from translating them into internal forms. This prevents bootloader-specific details from spreading through the memory manager.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum MemoryRegionKind { Usable, Reserved, Firmware, Bootloader, Kernel, Framebuffer, Unknown,}#[derive(Debug, Clone, Copy)]pub struct MemoryRegion { pub start: u64, pub length: u64, pub kind: MemoryRegionKind,}
impl MemoryRegion { pub const fn new(start: u64, length: u64, kind: MemoryRegionKind) -> Self { Self { start, length, kind, } }
pub fn end(&self) -> u64 { self.start.saturating_add(self.length) }
pub fn is_empty(&self) -> bool { self.length == 0 }
pub fn is_usable(&self) -> bool { self.kind == MemoryRegionKind::Usable }}This structure gives the kernel a stable internal language for memory regions. The start field is the first physical address in the region. The length field is the number of bytes in the region. The end method returns the first address after the region. That convention is useful because many range calculations become simpler when a region is treated as [start, end), where the start is included and the end is excluded.
The saturating_add call protects the end calculation from wrapping if invalid input produces a region whose start and length exceed the maximum representable value. This does not make a bad memory map safe, but it prevents one arithmetic operation from silently wrapping into a small address. A robust kernel should reject or ignore invalid entries rather than trusting impossible ranges.
The kernel entry point receives boot information from the bootloader. In real code, the boot information type depends on the selected boot strategy. The following example uses a kernel-owned BootInfo shape to show the idea. The important detail is the flow: the entry point receives boot information, passes the memory map to memory initialization, and then the memory module takes responsibility for parsing it.
pub struct BootInfo { pub memory_regions: &'static [MemoryRegion],}
#[unsafe(no_mangle)]pub extern "C" fn kernel_main(boot_info: &'static BootInfo) -> ! { serial::init(); serial_println!("kernel entered");
memory::init_from_map(boot_info.memory_regions); serial_println!("memory map read");
loop { x86_64::instructions::hlt(); }}This code assumes the bootloader has already provided the memory regions in the kernel’s internal format. A real bootloader may provide different names, layouts, or region categories. In that case, the first step is translation. Keep that translation near the boot module. The memory manager should receive a clean internal representation so the rest of the kernel is not tied to one boot protocol.
A translation function can convert raw bootloader region kinds into kernel region kinds. The following example uses placeholder raw types to show the pattern without binding the whole kernel to a specific external API.
#[derive(Debug, Clone, Copy)]pub enum RawRegionKind {Available, Reserved, FirmwareRuntime, BootloaderData, KernelImage, GraphicsFramebuffer, Other,
#[derive(Debug, Clone, Copy)] pub struct RawMemoryRegion { pub start: u64, pub length: u64, pub kind: RawRegionKind, }
pub fn translate_region(raw: RawMemoryRegion) -> MemoryRegion { let kind = match raw.kind { RawRegionKind::Available => MemoryRegionKind::Usable, RawRegionKind::Reserved => MemoryRegionKind::Reserved, RawRegionKind::FirmwareRuntime => MemoryRegionKind::Firmware, RawRegionKind::BootloaderData => MemoryRegionKind::Bootloader, RawRegionKind::KernelImage => MemoryRegionKind::Kernel, RawRegionKind::GraphicsFramebuffer => MemoryRegionKind::Framebuffer, RawRegionKind::Other => MemoryRegionKind::Unknown, };
MemoryRegion::new(raw.start, raw.length, kind)}
This translation is deliberately conservative. If a raw kind is not clearly available, it becomes something other than Usable. That is the safer direction. A memory region should be used by the allocator only when the kernel has a positive reason to treat it as available. Unknown memory is not free memory. Reserved memory is not free memory. Firmware memory is not free memory. Framebuffer memory is not free memory.
Once the map is translated, the kernel should print it early. A memory-map dump is one of the most useful diagnostics you can add before building the allocator. It shows what the bootloader thinks the physical address space looks like. It also helps you catch unexpected region types, zero-length
entries, overlapping entries, strange high addresses, and missing usable ranges.
pub fn print_memory_map(regions: &[MemoryRegion]) { serial_println!("physical memory map");
for region in regions { serial_println!( "start={:#018x}, end={:#018x}, length={:#018x}, kind={:?}", region.start, region.end(), region.length, region.kind ); }}The formatted output uses fixed-width hexadecimal addresses because physical memory addresses are easier to inspect that way. The start and end values show the region boundaries. The length shows how large the range is. The kind shows how the kernel classified it. This printout should be called before the allocator is initialized, while the kernel is still in a diagnostic-friendly phase.
A memory map should also be checked for basic validity. Some boot environments may already provide well-formed entries, but the kernel should still defend its own assumptions. An entry with zero length can be skipped. An entry whose end address wraps should be rejected. An entry whose start is greater than or equal to the end should be rejected. A region that is not page-aligned may still contain usable page-aligned frames inside it, but the allocator must align carefully before using it.
pub fn is_valid_region(region: MemoryRegion) -> bool { if region.length == 0 { return false; }}let end = region.start.saturating_add(region.length);
if end <= region.start { return false; }
true
This check is small, but it sets a good tone. The memory manager should not treat input as perfect. A bootloader-provided map is more trustworthy than guessing, but the kernel still needs to uphold its own invariants. The allocator should consume only regions that pass basic validation and have the correct kind.
A more useful function filters the memory map into usable regions. This still does not allocate frames. It only selects candidate regions for the allocator.
rustpub fn usable_regions<'a>( regions: &'a [MemoryRegion],) -> impl Iterator<Item = MemoryRegion> + 'a { regions .iter() .copied() .filter(|region| is_valid_region(*region)) .filter(|region| region.is_usable())}This function returns only valid regions marked as usable. Later, the frame allocator can walk these regions and split them into page-sized frames. This separation keeps the design clear. The map parser identifies usable regions. The frame allocator decides which page-sized physical frames to return.
There is a subtle issue here. A region marked usable by the bootloader may still overlap something the kernel needs to protect if the bootloader’s region categories are too broad or if the kernel has created additional static objects after the map was formed. For that reason, the allocator should not rely only on the raw usable flag. It should also exclude known protected ranges such as the kernel image, boot information, initial stack, page tables, and framebuffer. In many boot protocols, those areas are already marked
separately, but the allocator should be designed to support explicit exclusions. Conservative exclusion is better than accidental reuse.
Reading the memory map is therefore a multi-stage act. The kernel receives bootloader data, translates it into internal types, validates entries, prints the result, filters candidate usable regions, and prepares additional protection rules before allocation begins. This may sound like a lot of care for one startup structure, but it is justified. Every later memory operation depends on getting this right.
6.2: Identifying Usable, Reserved, Firmware, and Kernel Memory Regions
Section titled “6.2: Identifying Usable, Reserved, Firmware, and Kernel Memory Regions”The memory map is useful only if the kernel interprets region types correctly. A physical address range is not safe simply because it exists. The kernel must understand what a region is for and whether it can be allocated. Misclassifying memory is one of the fastest ways to create corruption that appears much later.
Usable memory is ordinary RAM that the kernel may allocate after applying its own exclusions and alignment rules. It is the source for physical frames. Even then, usable memory should not be consumed as one giant byte pool. The kernel will allocate frames in page-sized units, typically 4096 bytes for early x86_64 work. If a usable region starts or ends at an address that is not page-aligned, only the aligned portion inside that region can be used for frames. The bytes before the first aligned frame and after the last full frame are not useful to a 4 KiB frame allocator.
Reserved memory must not be allocated. It may contain firmware data, device mappings, platform-specific structures, memory holes, or regions that are simply not safe for general RAM use. The kernel does not need to know every reason a reserved region exists before avoiding it. The correct behavior is to leave it alone unless a later subsystem has specific knowledge and a valid reason to access it.
Firmware memory needs careful treatment. Some firmware data may be needed only during boot. Some may be needed later by runtime services or hardware discovery. Some memory may hold ACPI tables that the kernel should read but not overwrite casually. A simple early kernel can classify firmware-related memory as unavailable to the frame allocator. Later, specific firmware table parsers can read selected regions through controlled mappings. Reading is different from allocating. The allocator should not hand firmware memory out as general-purpose frames.
Kernel memory includes the kernel’s code, read-only data, writable data, uninitialized data, static stacks, descriptor tables, and other static structures. The kernel must never allocate frames that overlap its own image or live structures. If it does, it may overwrite the code currently executing, the IDT, the GDT, panic strings, global variables, or early stacks. Such corruption may not fail immediately. The kernel may continue until it calls a function whose code was overwritten or reads a global value that has been damaged.
Bootloader memory and boot information should also be protected during early initialization. The boot information structure may contain the memory map, framebuffer details, physical memory offset, module locations, and other startup data. If the allocator reuses those frames before the kernel has copied or permanently preserved the needed data, later initialization can read garbage. A clean design either keeps boot information memory reserved for the whole early kernel or copies the necessary data into kernel-owned structures before freeing anything. Early on, keeping it protected is simpler and safer.
Framebuffer memory is a common trap. It may look like a physical address range, and it may be writable, but it is not general RAM. It represents device memory used for display output. Writing random allocator data into it can corrupt the screen, and reading it as ordinary memory may have different performance or behavior characteristics. The frame allocator should not return framebuffer frames. The console or graphics subsystem can map and write to framebuffer memory through a dedicated interface.
The kernel can encode these decisions in a function that checks whether a region kind is eligible for general allocation.
Rust
pub fn region_kind_is_allocatable(kind: MemoryRegionKind) -> bool { match kind { MemoryRegionKind::Usable => true, MemoryRegionKind::Reserved => false, MemoryRegionKind::Firmware => false, MemoryRegionKind::Bootloader => false, MemoryRegionKind::Kernel => false, MemoryRegionKind::Framebuffer => false, MemoryRegionKind::Unknown => false, }}This function is intentionally strict. Only Usable returns true. Everything else is excluded. This is the right default for an early kernel. If a future subsystem wants to reclaim certain bootloader memory after initialization, that should be a deliberate design change, not an accident in the first allocator.
Page alignment is the next step. A memory region may begin at any byte address, but physical frame allocation should return page-aligned frame starts. A frame allocator that returns unaligned addresses is broken because page tables map frames at page granularity. The allocator needs to round the start address up to the next page boundary and round the end address down to the previous page boundary.
Rust
pub const PAGE_SIZE: u64 = 4096;
pub fn align_up(address: u64, alignment: u64) -> u64 { let mask = alignment - 1;
if address & mask == 0 { address } else { (address + mask) & !mask }}pub fn align_down(address: u64, alignment: u64) -> u64 { address & !(alignment - 1) }
These helpers assume the alignment is a power of two. Page size is a power of two, so that condition holds for 4 KiB frames. A production-quality helper might assert or check the power-of-two property. In early kernel code, keeping the helper small is acceptable as long as its use is controlled.
A function can then compute the usable frame range inside a memory region. It should return nothing if the aligned range contains no full frames.
#[derive(Debug, Clone, Copy)]pub struct FrameRange { pub start: u64, pub end: u64,}
impl FrameRange { pub fn is_empty(&self) -> bool { self.start >= self.end }}
pub fn frame_range_from_region(region: MemoryRegion) -> Option<FrameRange> { if !region_kind_is_allocatable(region.kind) { return None; }
if !is_valid_region(region) { return None; }
let start = align_up(region.start, PAGE_SIZE); let end = align_down(region.end(), PAGE_SIZE);
let range = FrameRange { start, end };
if range.is_empty() { None } else { Some(range) }}This function converts a usable byte region into a page-aligned frame range. The start is inclusive and the end is exclusive. If the aligned start is greater than or equal to the aligned end, there are no full frames available. This prevents the allocator from returning partial frames at the edges of regions.
To make the memory map easier to inspect, the kernel can print both raw regions and derived frame ranges. This helps confirm that alignment did not remove more memory than expected.
pub fn print_usable_frame_ranges(regions: &[MemoryRegion]) { serial_println!("usable physical frame ranges");
for region in regions.iter().copied() { if let Some(range) = frame_range_from_region(region) { serial_println!( "frames start={:#018x}, end={:#018x}", range.start, range.end ); } }}This diagnostic output gives you an early view of what the allocator will be allowed to consume. If no usable frame ranges appear, the memory map translation is wrong, the bootloader did not provide the expected region types, or the kernel filtered too aggressively. If framebuffer or firmware ranges appear as usable, the classification logic is too permissive.
Overlapping memory regions require careful thought. Some boot maps may be clean and non-overlapping. Others may contain regions where one entry refines another or where firmware data overlaps a broader available range. A simple allocator that only iterates Usable regions may still be unsafe if protected regions overlap those ranges and are not explicitly removed. To be conservative, the allocator can maintain a separate list of protected
ranges and reject frames that overlap them. That is often simpler than trying to normalize the entire memory map during the first implementation.
A range-overlap function is useful for this.
Rust
#[derive(Debug, Clone, Copy)]pub struct PhysicalRange { pub start: u64, pub end: u64,}
impl PhysicalRange { pub const fn new(start: u64, end: u64) -> Self { Self { start, end } }
pub fn overlaps(&self, other: PhysicalRange) -> bool { self.start < other.end && other.start < self.end }}This uses the same [start, end) convention. Two ranges overlap when each starts before the other ends. This handles partial overlap, full containment, and exact interior intersections. If one range ends exactly where another begins, they do not overlap, which is the desired behavior for exclusive end ranges.
The kernel can use protected ranges to reject candidate frames.
Rust
pub fn frame_overlaps_protected_range( frame_start: u64, protected_ranges: &[PhysicalRange],) -> bool { let frame = PhysicalRange::new(frame_start, frame_start + PAGE_SIZE);
protected_ranges .iter() .copied() .any(|range| frame.overlaps(range))}This function checks whether a 4 KiB frame overlaps any protected range. It is a simple but important guard. Even if a frame comes from a region marked usable, it should not be returned if it overlaps the kernel image, boot information, stack, framebuffer, or other reserved kernel-owned areas.
The category decisions should be conservative during early development. Do not reclaim bootloader memory early just because it appears possible. Do not allocate ACPI or firmware regions before you have a clear plan. Do not treat device memory as ordinary RAM. Do not assume an unknown region is harmless. A physical frame allocator is a trust boundary. Once a frame is returned, later code may put anything there. The safest allocator is one that returns fewer frames correctly rather than more frames recklessly.
6.3: Designing a Physical Frame Allocator
Section titled “6.3: Designing a Physical Frame Allocator”A physical frame allocator hands out page-sized chunks of physical memory. Paging code uses these frames to create page tables, back heap pages, allocate stacks, and map memory for kernel structures. The allocator’s job is not to manage virtual addresses and not to provide byte-level heap allocation. It deals in physical frames. That separation matters. A heap allocator may provide small objects. A virtual memory manager may map pages into an address space. A frame allocator provides the physical backing for those operations.
The first frame allocator should be simple, inspectable, and conservative. It should walk through page-aligned usable frame ranges and return the next frame that is not protected. This is often called a bump-style frame allocator because it moves forward and does not free frames. It is not a complete long-term allocator, but it is excellent for early kernel initialization. It can allocate page-table frames and heap backing frames before more complex memory management exists.
A frame can be represented by its starting physical address. Wrapping it in a type prevents confusion between arbitrary addresses and frame-aligned addresses.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct PhysFrame { start: u64,}
impl PhysFrame { pub fn containing_address(address: u64) -> Self { Self { start: align_down(address, PAGE_SIZE), } }
pub fn from_start_address(address: u64) -> Option<Self> { if address % PAGE_SIZE == 0 { Some(Self { start: address }) } else { None } }
pub fn start_address(&self) -> u64 { self.start }}This type distinguishes two operations. containing_address rounds an arbitrary address down to the frame that contains it. from_start_address accepts only an aligned frame start. This distinction helps prevent mistakes. When allocating, you should return frames from aligned starts. When checking whether an address belongs to a frame, rounding down can be appropriate.
A basic allocator can hold the memory regions, protected ranges, and a pointer to the next candidate frame. It scans until it finds a frame from a usable region that does not overlap any protected range.
pub struct BumpFrameAllocator<'a> { regions: &'a [MemoryRegion], protected: &'a [PhysicalRange], region_index: usize, next_frame: u64,}}
impl<‘a> BumpFrameAllocator<‘a> { pub fn new(regions: &‘a [MemoryRegion], protected: &‘a [PhysicalRange]) -> Self { Self { regions, protected, region_index: 0, next_frame: 0, } }
pub fn allocate_frame(&mut self) -> Option<PhysFrame> { loop { let region = *self.regions.get(self.region_index)?;
let Some(range) = frame_range_from_region(region) else { self.region_index += 1; self.next_frame = 0; continue; };
if self.next_frame == 0 || self.next_frame < range.start { self.next_frame = range.start; }
if self.next_frame >= range.end { self.region_index += 1; self.next_frame = 0; continue; }
let candidate = self.next_frame; self.next_frame += PAGE_SIZE;
if frame_overlaps_protected_range(candidate, self.protected) { continue; }
return PhysFrame::from_start_address(candidate); }}}
This allocator is intentionally one-way. It never frees. That is acceptable during early setup. The goal is to get a correct source of frames for page-
table construction and heap initialization. Freeing frames requires additional bookkeeping, and that complexity should not be introduced before the kernel can test and diagnose simpler allocation behavior.
The allocator walks through memory regions by index. For each region, it derives a page-aligned frame range. If the region is not usable, invalid, or too small to contain a frame, it skips it. It then advances next_frame through the range. Each candidate frame is checked against protected ranges. If it overlaps anything protected, it is skipped. Otherwise, the allocator returns it.
The use of Option is important. Physical memory is finite. The allocator can run out of frames. Early kernel code may panic if that happens during essential initialization, but the allocator itself should express failure through its return type. That keeps the design honest. A frame allocation can fail.
The allocator can be tested by printing the first few frames it returns. This is a good early diagnostic before using it to back page tables.
Rust
pub fn print_first_frames(allocator: &mut BumpFrameAllocator, count: usize) { for index in 0..count { match allocator.allocate_frame() { Some(frame) => { serial_println!( "frame {}: {:#018x}", index, frame.start_address() ); } None => { serial_println!("no more frames after {}", index); break; } } }}This output lets you check that the allocator is not returning frames from suspicious low addresses, protected regions, or device memory. If the first returned frame overlaps the kernel image or boot information, stop and fix the protection logic before using the allocator for anything important.
The first version of the allocator borrows slices directly. That is useful during initialization when the boot information is still available. Later, the kernel may want to copy the memory map into kernel-owned storage or create a more permanent memory manager. Early on, borrowing from boot information can be acceptable if the boot information memory remains protected and valid. If you plan to free bootloader memory later, copy what you need before freeing it.
A more controlled allocator can count frames and allocations, which helps debugging.
Rust
pub struct CountingFrameAllocator<'a> { inner: BumpFrameAllocator<'a>, allocated: usize,}
impl<'a> CountingFrameAllocator<'a> { pub fn new(regions: &'a [MemoryRegion], protected: &'a [PhysicalRange]) -> Self { Self { inner: BumpFrameAllocator::new(regions, protected), allocated: 0, } }
pub fn allocate_frame(&mut self) -> Option<PhysFrame> { let frame = self.inner.allocate_frame();
if frame.is_some() { self.allocated += 1; }
frame }
pub fn allocated_count(&self) -> usize { self.allocated }}This wrapper does not change the allocation policy. It adds accounting. When paging and heap setup begin consuming frames, the count can show how much physical memory has already been allocated. This helps detect accidental allocation loops. If one initialization step allocates thousands of frames unexpectedly, the counter will make that visible.
A frame allocator must not be globally mutable in an uncontrolled way. It is tempting to create a static mut FRAME_ALLOCATOR and access it from anywhere. That creates unsafe global state with unclear borrowing rules. A better early design passes the allocator by mutable reference through initialization functions. This keeps ownership clear. Later, a synchronized global memory manager can be introduced if needed.
pub fn init_memory(regions: &[MemoryRegion], protected: &[PhysicalRange]) { let mut allocator = CountingFrameAllocator::new(regions, protected);
print_first_frames(&mut allocator, 5);
serial_println!( "frames allocated during probe: {}", allocator.allocated_count() );}This function creates the allocator locally and uses it for a controlled diagnostic. When the paging system is added, the allocator can be passed into page-table initialization. Keeping it local at first avoids global-state problems before there is a real memory manager.
Eventually, the allocator must become part of kernel state because many subsystems need frames. At that point, use a synchronization primitive and clear initialization rules. The global allocator should start uninitialized, be initialized once, and reject use before initialization. This can be expressed with a lock-protected optional allocator.
use spin::Mutex;
static FRAME_ALLOCATOR:Mutex<Option<CountingFrameAllocator<'static>>> =Mutex::new(None);
pub fn init_global_frame_allocator( regions: &'static [MemoryRegion], protected: &'static [PhysicalRange],) { let mut guard = FRAME_ALLOCATOR.lock();
if guard.is_some() { panic!("frame allocator is already initialized"); }
*guard = Some(CountingFrameAllocator::new(regions, protected));}
pub fn allocate_frame() -> Option<PhysFrame> { let mut guard = FRAME_ALLOCATOR.lock(); let allocator = guard.as_mut()?;
allocator.allocate_frame()}This design is better than a naked mutable static, but it still has limitations. The lifetime requirements mean the memory map and protected ranges must be valid for the required lifetime. The lock can become a problem if used from interrupt context without care. The allocator still cannot free frames. These are acceptable limitations if they are understood. The first global frame allocator exists to support early memory management, not to be the final physical memory subsystem.
A more complete physical memory manager would eventually track free and used frames with a bitmap, buddy allocator, or another structure. It would support freeing frames, merging ranges, reserving frames, handling memory zones, and managing per-CPU or NUMA-aware policies in more advanced systems. That is not necessary at this stage. Building a correct one-way allocator first is the right move because it gives paging and heap initialization a dependable foundation.
The key quality of the allocator is not cleverness. It is correctness. It should return aligned frames. It should return only from usable memory. It should avoid protected ranges. It should express exhaustion. It should be easy to inspect. It should not depend on heap allocation. It should not allocate from memory that contains the data structures it still needs. If those conditions hold, the kernel can safely use it for the next major step: virtual memory and paging.
6.4: Protecting Kernel, Boot Info, Stack, and Framebuffer Memory
Section titled “6.4: Protecting Kernel, Boot Info, Stack, and Framebuffer Memory”The physical frame allocator must not return every frame from every usable-looking region. Some physical ranges must be protected even if they are not clearly excluded by the bootloader’s map or even if their category is easy to misunderstand. The kernel image, boot information, initial stack, descriptor tables, page tables, and framebuffer all deserve explicit protection. This is not defensive programming for appearance. It prevents the allocator from silently corrupting the exact structures the kernel depends on.
The kernel image contains executable code and static data. It may include text, read-only data, initialized data, uninitialized data, panic strings, formatting data, and statically allocated CPU structures. If a frame allocator returns a frame inside the kernel image, later code can overwrite the running kernel. The failure might appear as a strange instruction fault, corrupted output string, invalid descriptor table, or panic in unrelated code. Protecting the kernel image is non-negotiable.
The boot information structure should be protected at least until the kernel no longer needs it. Early boot information may contain the memory map itself. If the allocator overwrites the memory map while it is still being used, physical memory management becomes self-corrupting. The kernel may also need framebuffer metadata, physical memory offset information, module ranges, or firmware table addresses. Until those values are copied into kernel-owned structures or no longer needed, the frames containing the boot information must stay unavailable.
The initial stack also needs protection. Rust functions depend on a valid stack, and early startup may still be using a stack created by the bootloader. If the allocator hands out frames overlapping that stack, later allocations can overwrite return addresses, local variables, saved registers, or temporary values. Stack corruption can cause failures that look unrelated to memory allocation. A function may return to a bad address, a local variable may change unexpectedly, or a later exception may occur with a misleading instruction pointer.
The framebuffer is different from the stack or kernel image because it is device memory rather than normal kernel-owned RAM. It should not be returned as a frame for page tables, heap memory, or ordinary data. The display subsystem may write to it through a framebuffer abstraction, but the physical memory manager should not treat it as general-purpose memory. If the framebuffer range appears in the memory map as a special region, the allocator should reject it based on region type. If the bootloader passes framebuffer information separately, the kernel should also add that range to the protected list.
A protected range can be represented by start and end physical addresses. The kernel can build a list of such ranges during early memory initialization.
#[derive(Debug, Clone, Copy)]pub struct ProtectedRange { pub start: u64, pub end: u64, pub reason: ProtectedReason,}
#[derive(Debug, Clone, Copy)]pub enum ProtectedReason { KernelImage, BootInfo, InitialStack, Framebuffer, PageTables, CpuTables, Unknown,}impl ProtectedRange { pub const fn new(start: u64, end: u64, reason: ProtectedReason) -> Self { Self { start, end, reason } }
pub fn is_valid(&self) -> bool { self.start < self.end }
pub fn overlaps(&self, start: u64, end: u64) -> bool { self.start < end && start < self.end }}This version includes a reason for each protected range. That is useful for diagnostics. When the allocator skips a frame, you can print why the frame was skipped if needed. You do not want verbose skip output during normal operation, but during allocator debugging it can be valuable.
The allocator’s protected-range check can use this richer type.
pub fn frame_is_protected( frame_start: u64, protected_ranges: &[ProtectedRange],) -> bool { let frame_end = frame_start + PAGE_SIZE;
protected_ranges .iter() .copied() .filter(|range| range.is_valid()) .any(|range| range.overlaps(frame_start, frame_end))}This checks a full frame range against every valid protected range. If any overlap exists, the frame is unavailable. The overlap does not need to cover the whole frame. If even one byte of a frame belongs to protected memory, the allocator should not return that frame. Page-table mappings operate at frame granularity, so partial overlap is enough to make the frame unsafe for general use.
The allocator can be updated to use ProtectedRange.
pub struct ProtectedFrameAllocator<'a> { regions: &'a [MemoryRegion], protected: &'a [ProtectedRange], region_index: usize, next_frame: u64,}
impl<'a> ProtectedFrameAllocator<'a> { pub fn new(regions: &'a [MemoryRegion], protected: &'a [ProtectedRange]) -> Self { Self { regions, protected, region_index: 0, next_frame: 0, } }
pub fn allocate_frame(&mut self) -> Option<PhysFrame> { loop { let region = *self.regions.get(self.region_index)?;
let Some(range) = frame_range_from_region(region) else { self.region_index += 1; self.next_frame = 0; continue; };
if self.next_frame == 0 || self.next_frame < range.start { self.next_frame = range.start; }
if self.next_frame >= range.end { self.region_index += 1; self.next_frame = 0; continue; }
let candidate = self.next_frame; self.next_frame += PAGE_SIZE;
if frame_is_protected(candidate, self.protected) { continue; } } }}}return PhysFrame::from_start_address(candidate);}}This allocator is still one-way, but it now has stronger protection logic. It does not rely only on memory-region types. It also rejects frames that overlap explicit protected ranges. This is the safer architecture because the kernel can add protection for any range it cares about, regardless of how the bootloader classified it.
The next question is how to obtain the protected ranges. Some are known through linker symbols. The kernel image boundaries can be exposed by the linker, depending on the linker script or bootloader setup. In Rust, external symbols can be declared and their addresses read. This must be done carefully because the symbols represent addresses, not ordinary initialized Rust values.
unsafe extern "C" { static __kernel_start: u8; static __kernel_end: u8;}
pub fn kernel_image_range() -> ProtectedRange { let start = unsafe { core::ptr::addr_of!(__kernel_start) as u64 }; let end = unsafe { core::ptr::addr_of!(__kernel_end) as u64 };
ProtectedRange::new(start, end, ProtectedReason::KernelImage)}This code assumes linker symbols named __kernel_start and __kernel_end exist. The exact symbol names depend on your linker configuration. The important idea is that the kernel should protect the physical range containing its own image. If the kernel runs at a virtual address different from its physical load address, this calculation may need translation. You must know whether the symbol addresses are virtual
addresses, physical addresses, or identity-mapped addresses at the time you read them.
Boot information protection can be created from the pointer and size of the structure if that information is available. If the boot protocol gives a boot information pointer but not an exact size, the safest early option is to protect the containing page or a conservative range known to include the boot information. Exact sizing is better, but conservative protection is preferable to overwriting the data.
pub fn range_containing_object<T>( reference: &'static T, reason: ProtectedReason,) -> ProtectedRange { let start = reference as *const T as u64; let end = start + core::mem::size_of::<T>() as u64;
let aligned_start = align_down(start, PAGE_SIZE); let aligned_end = align_up(end, PAGE_SIZE);
ProtectedRange::new(aligned_start, aligned_end, reason)}This function protects all frames containing a given static object. It aligns the object range outward to page boundaries because the frame allocator works in page units. This is useful for protecting a boot information structure if it is represented as a single object. If the boot information contains references to separate arrays, such as a memory map slice, those arrays must be protected too.
pub fn range_containing_slice<T>( slice: &'static [T], reason: ProtectedReason,) -> ProtectedRange { let start = slice.as_ptr() as u64; let byte_len = core::mem::size_of_val(slice) as u64; let end = start + byte_len;
let aligned_start = align_down(start, PAGE_SIZE);let aligned_end = align_up(end, PAGE_SIZE);
ProtectedRange::new(aligned_start, aligned_end, reason)
This function protects the frames containing a slice. It is useful for memory maps because the map may be passed as a slice separate from the main boot information object. Without protecting the slice backing storage, the allocator might overwrite the map while still reading it.
Framebuffer protection comes from framebuffer metadata. The bootloader may provide a base physical address and buffer length. The kernel should align this range outward to full frames and add it to protected ranges.
Rust
pub struct FramebufferInfo { pub physical_address: u64, pub byte_len: u64, }
pub fn framebuffer_range(info: FramebufferInfo) -> Option
let start = align_down(info.physical_address, PAGE_SIZE);let end = align_up(info.physical_address + info.byte_len, PAGE_SIZE);
Some(ProtectedRange::new( start, end, ProtectedReason::Framebuffer,))}
This function returns nothing for an empty framebuffer range. For a valid range, it protects all frames touched by the framebuffer. Again, partial-frame overlap is enough. The allocator should never return a frame that contains even part of the framebuffer.
Initial stack protection is more difficult because the kernel must know the stack range. Some bootloaders provide stack details. Some kernel setups define their own stack in the linker script or startup code. If the stack is defined by the kernel, protect it the same way as other static memory. If the bootloader provides it but does not report the exact range, protect a conservative range if possible. The most important rule is that the current stack must not become allocator-owned memory.
A startup function can combine known protected ranges. In early code, a fixed-size array can store them, avoiding heap allocation.
Rust
pub struct ProtectedRanges { ranges: [Option<ProtectedRange>; 8],}
impl ProtectedRanges { pub const fn new() -> Self { Self { ranges: [None, None, None, None, None, None, None, None], } }
pub fn push(&mut self, range: ProtectedRange) { if !range.is_valid() { return; }
for slot in self.ranges.iter_mut() { if slot.is_none() { *slot = Some(range); return; } }
panic!("too many protected memory ranges"); }
pub fn as_slice_storage(&self) -> &[Option<ProtectedRange>] { &self.ranges }}This storage avoids dynamic allocation because the heap does not exist yet. The fixed capacity is a conscious early-kernel tradeoff. If the kernel needs more protected ranges, increase the capacity or introduce a better static storage strategy. Do not use Vec until the heap allocator is initialized.
Because the allocator expects a slice of actual ranges rather than options, a helper can copy valid ranges into another fixed array or the allocator can iterate over optional entries directly. For early code, making the allocator handle optional slots avoids another structure.
pub fn frame_is_protected_by_slots( frame_start: u64, protected_slots: &[Option<ProtectedRange>],) -> bool { let frame_end = frame_start + PAGE_SIZE;
protected_slots .iter() .filter_map(|slot| *slot) .filter(|range| range.is_valid()) .any(|range| range.overlaps(frame_start, frame_end))}This function lets the allocator work with fixed storage. It is a practical approach before dynamic allocation exists. The tradeoff is that optional slots appear in the allocator path. That is acceptable for the first design.
Diagnostic output should show protected ranges before allocation begins. If the allocator is skipping frames, you should know what it is protecting.
pub fn print_protected_ranges(ranges: &[Option<ProtectedRange>]) { serial_println!("protected physical ranges");
for range in ranges.iter().filter_map(|slot| *slot) { serial_println!( "start={:#018x}, end={:#018x}, reason={:?}", range.start, range.end,range.reason ); }
This output gives you confidence that the kernel image, boot information, memory map, stack, and framebuffer are not being quietly returned as free frames. It also helps catch address-space confusion. If a protected range appears as a high virtual address when the allocator expects physical addresses, the translation is wrong. That mistake must be fixed before allocation begins.
Address-space confusion is one of the major dangers at this stage. The frame allocator operates on physical addresses. Rust pointers are virtual addresses in long mode. If the bootloader maps physical memory at a virtual offset, a pointer value may not equal the physical address of the underlying memory. Linker symbols may also represent virtual addresses depending on how the kernel is linked and mapped. Before using pointer-derived addresses as physical ranges, confirm the mapping model. If the kernel is identity-mapped early, virtual and physical addresses may match for some regions. If it runs in the higher half, they usually do not. A frame allocator fed with virtual addresses will protect the wrong frames.
A safer design is to keep bootloader-provided physical addresses as the source for physical ranges whenever possible. Use pointer-derived ranges only when you know how to translate them. If the bootloader provides kernel physical start and end addresses, prefer those for allocator protection. If it provides framebuffer physical address and length, use those. If it provides boot information as a virtual pointer, understand how to obtain or infer the physical backing before protecting it as a physical range.
At the end of physical memory setup, the kernel should be able to report the memory map, classify usable ranges, report protected ranges, and allocate a few test frames that do not overlap protected memory. That is the threshold for moving into virtual memory work. Without these protections, paging code may appear to work at first while quietly corrupting the kernel. With them, every allocated frame has a defensible origin. The allocator may still be simple, but it is grounded in the map, aligned to page boundaries,
and constrained by explicit protection rules. That is the right foundation for a kernel that will soon build and modify its own address space.