Skip to content
ImagineWorld

Advanced Boot, Hardware Discovery, and Next-System Features

node_idnode-book_writing-operating-systems-in-rust_chapter-11-advanced-boot-hardware-discovery-and-next-system-features
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num11
chapter_titleAdvanced Boot, Hardware Discovery, and Next-System Features
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 11 — Advanced Boot, Hardware Discovery, and Next-System Features

Section titled “Chapter 11 — Advanced Boot, Hardware Discovery, and Next-System Features”

Chapter 11: Advanced Boot, Hardware Discovery, and Next-System Features

Section titled “Chapter 11: Advanced Boot, Hardware Discovery, and Next-System Features”

A working educational kernel is a strong foundation, but it is not the endpoint of operating-system design. Once the kernel can boot, manage memory, handle exceptions, receive hardware interrupts, allocate heap memory, accept keyboard input, run a small shell, and support QEMU-based tests, the next questions become more architectural. How would the kernel be loaded without relying completely on the current boot path? How does it discover real hardware instead of assuming fixed devices? How does it move from legacy interrupt controllers to modern interrupt routing? How does it grow toward filesystems, userspace, scheduling, and system calls without collapsing under accidental complexity?

These questions matter because a kernel that works only in a tightly controlled emulator setup can teach the foundations, but it does not yet behave like a system designed for wider hardware conditions. Real machines expose firmware tables, device buses, multiple processors, runtime memory regions, boot-service transitions, graphics modes, and interrupt routing details that are not always convenient. Even under QEMU, changing firmware mode, boot protocol, CPU count, or device configuration can reveal assumptions that were hidden by the first setup.

Advanced boot and hardware discovery should be approached with the same discipline used throughout the kernel. Do not add every feature at once. Do not rewrite the boot path before the current kernel is observable and testable. Do not treat firmware-provided addresses, ACPI tables, APIC registers, or multiprocessor startup paths as ordinary safe data. Each new layer should have a clear purpose, a narrow interface, and diagnostics that confirm what the kernel received and what it configured.

The goal now is to understand the next professional boundaries. A UEFI loader introduces the responsibilities of firmware interaction and the moment where boot services end. Modern boot protocols define how a

loader and kernel exchange structured data. ACPI and APIC support replace fixed hardware assumptions with discovered platform information. SMP introduces multiple CPUs and a much stricter synchronization model. Filesystems, userspace, scheduling, and system calls move the project from a single kernel environment toward a fuller operating-system design. Each of these topics is large enough to deserve careful treatment, but the foundation already built makes them realistic next steps rather than vague ambitions.

11.1: Understanding UEFI Loaders and Exit Boot Services

Section titled “11.1: Understanding UEFI Loaders and Exit Boot Services”

A UEFI loader is a program that runs before the kernel and uses firmware services to prepare the operating-system handoff. Unlike the kernel, a UEFI loader begins while firmware boot services are still available. It can open files, query firmware tables, allocate memory, obtain the memory map, locate graphics output information, and load a kernel image from a filesystem. Its job is not to become the operating system. Its job is to prepare enough information and machine state for the kernel, then end its dependency on boot services and transfer control.

This distinction is important. A UEFI loader and a kernel are different pieces of software with different responsibilities. The loader is allowed to ask firmware for help. The kernel must not casually rely on firmware boot services after the handoff. Once boot services are exited, the loader and kernel take responsibility for the machine state. Runtime services may still exist in special cases, but boot services such as allocation, file loading, and protocol discovery are no longer available. A kernel that tries to keep using boot services after they are gone is broken by design.

A UEFI loader typically performs several steps. It starts as a UEFI application. It obtains access to the system table and boot services. It locates and loads the kernel image. It obtains graphics information if framebuffer output is needed. It gathers the memory map. It prepares a handoff structure containing the data the kernel needs. It exits boot services. It then

jumps to the kernel entry point. The exact implementation depends on the loader design, but this sequence captures the main responsibilities.

The memory map is one of the most sensitive parts of this process. UEFI boot services manage memory before the operating system takes over. Calling allocation functions can change the memory map. That means a loader cannot casually obtain a memory map, make more allocations, and assume the old map is still valid. The loader usually needs to obtain the map close to the call that exits boot services. If the exit attempt fails because the map changed, the loader must obtain the map again and retry. This is one of the most common places where UEFI loader code becomes more demanding than it first appears.

The following code illustrates the shape of a UEFI application entry point. It is not a complete loader, but it shows the separation between loader initialization, boot information preparation, and kernel transfer.

Rust

#![no_main]
#![no_std]
use core::panic::PanicInfo;
#[repr(C)]
pub struct KernelBootInfo {
pub framebuffer_base: u64,
pub framebuffer_size: u64,
pub framebuffer_width: u32,
pub framebuffer_height: u32,
pub framebuffer_stride: u32,
pub memory_map_base: u64,
pub memory_map_len: u64,
pub physical_memory_offset: u64,
}
type KernelEntry = extern "C" fn(&'static KernelBootInfo) -> !;
#[unsafe(no_mangle)]
pub extern "efiapi" fn efi_main(
image_handle: usize,
system_table: usize,
) -> usize {
let _image_handle = image_handle;
let _system_table = system_table;
let boot_info = prepare_boot_info();
let kernel_entry = load_kernel_entry();
exit_boot_services();
kernel_entry(boot_info)
}
fn prepare_boot_info() -> &'static KernelBootInfo {
loop {}
}
fn load_kernel_entry() -> KernelEntry {
loop {}
}
fn exit_boot_services() {
loop {}
}
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}

This code uses placeholders because the exact UEFI API depends on the support crate and loader design. The structure is the important part. The loader entry uses the UEFI calling convention. It prepares a KernelBootInfo structure using a C-compatible layout. It obtains a function pointer to the kernel entry. It exits boot services before calling the kernel. The kernel entry receives a reference to boot information and never returns.

The KernelBootInfo structure must be designed as an ABI boundary. It should use #[repr(C)] so its layout is predictable across the loader and kernel boundary. It should contain plain data, fixed-size fields, and pointers or addresses with carefully defined meaning. Avoid passing Rust-specific types such as Vec, String, trait objects, references with unclear ownership, or enum layouts that are not explicitly represented. The loader and kernel may be separate binaries. Their shared structures should be simple, stable, and documented in the code.

A more careful handoff structure separates framebuffer information, memory-map information, and kernel image information. This makes the kernel side easier to validate.

Rust

#[repr(C)]
#[derive(Clone, Copy)]
pub struct FramebufferInfo {
pub base: u64,
pub byte_len: u64,
pub width: u32,
pub height: u32,
pub stride: u32,
pub bytes_per_pixel: u32,
pub pixel_format: PixelFormat,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub enum PixelFormat {
Rgb = 0,
Bgr = 1,
Unknown = 2,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct MemoryMapInfo {
pub base: u64,
pub entry_count: u64,
pub entry_size: u64,
}
#[repr(C)]
#[derive(Clone, Copy)]
pub struct KernelImageInfo {
pub physical_start: u64,
pub physical_end: u64,
pub virtual_start: u64,
pub virtual_end: u64,
}
#[repr(C)]
pub struct KernelBootInfo {
pub framebuffer: FramebufferInfo,
pub memory_map: MemoryMapInfo,
pub kernel_image: KernelImageInfo,
}

pub physical_memory_offset: u64, pub rsdp_address: u64, }

This structure gives the kernel a cleaner handoff. The framebuffer fields describe how to draw pixels. The memory-map fields tell the kernel where to find the final memory map and how to walk it. The kernel image fields protect the kernel from allocating over itself. The physical memory offset gives the kernel a way to access physical memory through a direct mapping if the loader created one. The RSDP address points toward ACPI hardware discovery if available.

The loader must ensure the memory holding this structure remains valid after boot services exit. If the boot information is allocated from memory that becomes available to the kernel and is then overwritten immediately, the kernel loses its startup data. A simple design places the boot information in memory that the kernel treats as reserved during early initialization. The kernel can later copy the data into its own permanent structures if it wants to free the original pages.

Loading the kernel image is another important boundary. A robust loader should understand the kernel binary format it supports. If the kernel is an ELF file, the loader should read program headers, allocate or map memory for loadable segments, copy segment data, zero uninitialized areas, apply the intended permissions where possible, and obtain the entry address. A simplistic loader that copies a file blob to an arbitrary address and jumps to it will fail once the kernel has separate sections, alignment requirements, or a higher-half layout.

The following code illustrates a loader-side function shape for loading a kernel, without tying it to a full filesystem or ELF implementation.

Rust

#[repr(C)] pub struct LoadedKernel { pub entry: KernelEntry, pub physical_start: u64, pub physical_end: u64,

pub virtual_start: u64, pub virtual_end: u64,

pub fn load_kernel_image(kernel_bytes: &[u8]) -> Result<LoadedKernel, LoadError> { let elf = parse_elf(kernel_bytes)?; validate_kernel_image(&elf)?; let loaded = load_segments(&elf)?; Ok(LoadedKernel { entry: loaded.entry, physical_start: loaded.physical_start, physical_end: loaded.physical_end, virtual_start: loaded.virtual_start, virtual_end: loaded.virtual_end, }) }

pub enum LoadError { InvalidImage, UnsupportedFormat, AllocationFailed, SegmentLoadFailed, }

struct ParsedElf;

fn parse_elf(_bytes: &[u8]) -> Result<ParsedElf, LoadError> { Err(LoadError::UnsupportedFormat) }

fn validate_kernel_image(_elf: &ParsedElf) -> Result<(), LoadError> { Ok(()) }

fn load_segments(_elf: &ParsedElf) -> Result<LoadedKernel, LoadError> { Err(LoadError::SegmentLoadFailed) }

This example is not a complete ELF loader. It shows the correct separation of concerns. Parsing, validation, segment loading, and result construction are different steps. A serious loader should reject unsupported images clearly rather than jumping into unknown bytes. Loader failures should be

diagnosable before boot services are exited, when firmware output may still be available.

Exit boot services is the point where the loader stops relying on firmware boot services. This step should happen as late as practical. After it succeeds, the loader should avoid allocations through boot services, file reads through firmware protocols, or calls that depend on the boot-services environment. The loader should already have loaded the kernel, prepared boot information, obtained the final memory map, and made any required graphics or table information available.

A realistic exit sequence often needs a retry path because the memory map can change. The shape looks like this.

Rust

pub enum ExitBootServicesError {
MemoryMapBufferTooSmall,
MemoryMapChanged,
FirmwareRejectedExit,
}
pub fn finalize_firmware_handoff() -> Result<MemoryMapInfo, ExitBootServicesError> {
let mut attempts = 0;
loop {
attempts += 1;
let memory_map = get_current_memory_map()?;
match try_exit_boot_services(&memory_map) {
Ok(()) => {
return Ok(memory_map.info());
}
Err(ExitBootServicesError::MemoryMapChanged) if attempts < 4 => {
continue;
}
Err(error) => {
return Err(error);
}
}
}
}

pub struct FinalMemoryMap;

impl FinalMemoryMap { pub fn info(&self) -> MemoryMapInfo { MemoryMapInfo { base: 0, entry_count: 0, entry_size: 0, } } }

fn get_current_memory_map() -> Result<FinalMemoryMap, ExitBootServicesError> { Err(ExitBootServicesError::MemoryMapBufferTooSmall) }

fn try_exit_boot_services( _memory_map: &FinalMemoryMap, ) -> Result<(), ExitBootServicesError> { Err(ExitBootServicesError::FirmwareRejectedExit) }

This code again uses placeholders, but the control flow is the point. The loader obtains the current memory map, attempts to exit boot services using that map, and retries if the map changed. Real loader code must use the firmware-provided key or token associated with the memory map. If the key is stale, exit fails. This is not a rare corner case. Allocations made while preparing the memory-map buffer can themselves change the map.

After boot services are exited, the kernel must interpret the final memory map carefully. Some memory types can become available to the operating system. Some must remain reserved. Runtime-service memory must be preserved if runtime services are supported. ACPI tables and other firmware data may need to remain readable. The loader should pass enough information for the kernel to make those decisions. The kernel should not treat the whole map as free.

A UEFI loader is valuable because it teaches what a bootloader really does. It loads a kernel image, gathers firmware data, prepares graphics and memory information, exits firmware boot services, and transfers control through a defined ABI. It also teaches why using an existing bootloader is

practical for early kernel work. Writing a loader correctly is a serious project by itself. Once your kernel already has logging, paging, allocation, and exception handling, writing or studying a UEFI loader becomes much more productive because failures can be investigated with a stronger mental model.

11.2: Comparing Modern Boot Protocols and Kernel Handoff Structures

Section titled “11.2: Comparing Modern Boot Protocols and Kernel Handoff Structures”

A boot protocol defines the agreement between the bootloader and the kernel. It answers practical questions that the kernel cannot ignore. How is the kernel loaded? Which CPU mode is active at entry? Where is the stack? Is paging enabled? How does the kernel receive the memory map? Is there a framebuffer? Is physical memory directly mapped? Where are firmware tables? What is the entry function signature? Which registers or structures carry the handoff data? If those answers are unclear, the kernel entry point is built on assumptions.

Modern boot protocols try to make this handoff more structured. Instead of forcing every kernel to write its own firmware loader from the beginning, a bootloader can provide a defined interface. The kernel can request certain information, and the bootloader can pass responses. This allows the kernel to focus on memory management, interrupts, drivers, and system services while still receiving reliable startup data.

Different boot protocols make different tradeoffs. Some are simple and architecture-focused. Some are designed to work across firmware types. Some pass a fixed boot information structure. Some use request and response records. Some support framebuffer setup, memory maps, modules, higher-half kernels, physical memory direct maps, and kernel address information. The kernel should not hard-code assumptions from one protocol throughout the whole system. Instead, it should translate protocol-specific data into kernel-owned boot information at the boundary.

A clean handoff model starts with a kernel-owned structure. This is the internal form that the rest of the kernel uses, regardless of how the loader provided the data.

Rust

use x86_64::{PhysAddr, VirtAddr};
pub struct KernelBootInfo {
pub memory_regions: &'static [MemoryRegion],
pub framebuffer: Option<FramebufferInfo>,
pub physical_memory_offset: Option<VirtAddr>,
pub kernel_physical_start: PhysAddr,
pub kernel_physical_end: PhysAddr,
pub rsdp_address: Option<PhysAddr>,
}
#[derive(Clone, Copy)]
pub struct FramebufferInfo {
pub base: PhysAddr,
pub byte_len: u64,
pub width: usize,
pub height: usize,
pub stride: usize,
pub bytes_per_pixel: usize,
pub pixel_format: PixelFormat,
}
#[derive(Clone, Copy)]
pub enum PixelFormat {
Rgb,
Bgr,
Unknown,
}
#[derive(Clone, Copy)]
pub struct MemoryRegion {
pub start: PhysAddr,
pub byte_len: u64,
pub kind: MemoryRegionKind,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum MemoryRegionKind {
Usable,
Reserved,
Firmware,
Bootloader,
}

Kernel, Framebuffer, Unknown, }

This structure uses strong address types for physical and virtual addresses. The framebuffer base is physical because the framebuffer is a physical device memory region until mapped. The physical memory offset is virtual because it identifies a virtual direct-mapping window. The memory regions use physical addresses because they describe machine memory. This separation reduces one of the most common handoff bugs: confusing physical and virtual addresses.

The boot module can translate from a specific protocol into this internal form. The rest of the kernel should call memory::init, drivers::framebuffer::init, and acpi::init using kernel-owned data rather than protocol-owned data. This makes the system more adaptable.

pub enum BootProtocolError {
MissingMemoryMap,
InvalidFramebuffer,
MissingKernelImageRange,
UnsupportedPixelFormat,
}
pub trait BootProtocolAdapter {
fn build_kernel_boot_info(
&'static self,
) -> Result<KernelBootInfo, BootProtocolError>;
}
pub fn initialize_from_protocol(
adapter: &'static dyn BootProtocolAdapter,
) -> Result<KernelBootInfo, BootProtocolError> {
let boot_info = adapter.build_kernel_boot_info()?;
validate_boot_info(&boot_info)?;
Ok(boot_info)
}
fn validate_boot_info(
boot_info: &KernelBootInfo,

) -> Result<(), BootProtocolError> { if boot_info.memory_regions.is_empty() { return Err(BootProtocolError::MissingMemoryMap); }

if boot_info.kernel_physical_start >=
boot_info.kernel_physical_end {
return Err(BootProtocolError::MissingKernelImageRange);
}
Ok(())

}

This pattern makes the protocol adapter responsible for translation and the kernel responsible for validation. In real early kernel code, a trait object may not be necessary. A plain function for the chosen boot protocol is enough. The value here is the architecture of the idea: convert external boot data into internal boot data, then validate it before use.

A request-and-response style protocol can be represented by static request structures placed in special sections or recognized by the bootloader. The bootloader fills responses before entering the kernel. The kernel then reads those responses during early initialization. The exact details depend on the protocol, but the Rust shape can be expressed through typed request and response structures.

#[repr(C)]
pub struct MemoryMapRequest {
pub id: u64,
pub revision: u64,
pub response: *const MemoryMapResponse,
}
#[repr(C)]
pub struct MemoryMapResponse {
pub entry_count: u64,
pub entries: *const RawMemoryMapEntry,
}
#[repr(C)]
pub struct RawMemoryMapEntry {
pub base: u64,
pub length: u64,
}

pub kind: u64, }

#[used] #[unsafe(link_section = “.boot_requests”)] static MEMORY_MAP_REQUEST: MemoryMapRequest = MemoryMapRequest { id: 0x1000, revision: 0, response: core::ptr::null(), };

This example shows the mechanics of a static request, but the numeric identifiers are placeholders. A real protocol defines exact IDs, structure layouts, alignment requirements, and section names. The #[used] attribute tells the compiler not to discard the static item even if Rust code does not reference it directly. The link_section attribute places it into a section where the bootloader can find it. This is a low-level ABI contract, so exact layout matters.

The kernel should not trust response pointers blindly. It should check for null pointers, validate entry counts, and convert raw entries to internal memory regions.

Rust

pub unsafe fn read_memory_map_response( response: *const MemoryMapResponse, ) -> Result<&‘static [RawMemoryMapEntry], BootProtocolError> { if response.is_null() { return Err(BootProtocolError::MissingMemoryMap); }

let response = unsafe {
&*response
};
if response.entries.is_null() {
return Err(BootProtocolError::MissingMemoryMap);
}
let entries = unsafe {
core::slice::from_raw_parts(
response.entries,
response.entry_count as usize,
)
}

}

};

Ok(entries) }

This function is unsafe because it converts raw pointers from the bootloader into Rust references and slices. The safety depends on the bootloader providing valid memory that remains alive for the kernel’s early initialization. The function checks for null pointers, but it cannot prove that the memory is actually valid or that the entry count is trustworthy. That is why this code belongs at the boot boundary, not deep inside the memory manager.

After reading raw entries, convert them to kernel-owned region types.

Rust

pub fn translate_raw_region(entry: RawMemoryMapEntry) -> MemoryRegion { let kind = match entry.kind { 1 => MemoryRegionKind::Usable, 2 => MemoryRegionKind::Reserved, 3 => MemoryRegionKind::Firmware, 4 => MemoryRegionKind::Bootloader, 5 => MemoryRegionKind::Kernel, 6 => MemoryRegionKind::Framebuffer, _ => MemoryRegionKind::Unknown, };

MemoryRegion {
start: x86_64::PhysAddr::new(entry.base),
byte_len: entry.length,
kind,
}

}

The numeric values are placeholders unless matched to a real protocol. The important behavior is conservative translation. Unknown kinds become Unknown, not Usable. Only regions explicitly marked usable should feed the frame allocator, and even then protected ranges must still be applied.

A fixed handoff-structure protocol can be simpler. The bootloader passes one pointer to a complete boot information structure. The kernel entry

receives that pointer and validates the structure. This is easier to reason about, but it can be less flexible when new data types are added.

#[repr(C)]
pub struct FixedBootInfo {
pub magic: u64,
pub version: u32,
pub memory_map_base: u64,
pub memory_map_count: u64,
pub framebuffer_base: u64,
pub framebuffer_len: u64,
pub rsdp_address: u64,
}
const BOOT_INFO_MAGIC: u64 = 0x4b45524e454c4249;
pub unsafe fn validate_fixed_boot_info(
pointer: *const FixedBootInfo,
) -> Result<&'static FixedBootInfo, BootProtocolError> {
if pointer.is_null() {
return Err(BootProtocolError::MissingMemoryMap);
}
let boot_info = unsafe {
&*pointer
};
if boot_info.magic != BOOT_INFO_MAGIC {
return Err(BootProtocolError::MissingMemoryMap);
}
Ok(boot_info)
}

A magic value and version field help detect invalid or incompatible handoff data. The kernel should reject structures that do not match its expected format. Silent acceptance of invalid boot information is dangerous because the kernel may later interpret random memory as a memory map or framebuffer address.

Comparing boot protocols should be practical, not ideological. A boot protocol is good for a kernel if it provides the data the kernel needs, has a clear ABI, supports the target firmware and architecture, fits the

development workflow, and does not force unnecessary early complexity. For this kernel, the important data includes a memory map, kernel image boundaries, framebuffer information, a physical memory direct map or another way to access page tables, firmware table pointers, loaded modules if needed, and a well-defined entry state.

The kernel should also be designed so changing boot protocols does not rewrite the whole system. The boot boundary absorbs protocol details. The memory manager receives MemoryRegion values. The framebuffer driver receives FramebufferInfo. The ACPI code receives an RSDP physical address if present. The paging code receives a physical memory offset if the boot path provides one. This architecture keeps the kernel from becoming married to one bootloader’s raw structures.

Boot protocol comparison leads to a useful professional habit: treat startup data as untrusted until validated. A bootloader may be correct, but the kernel still needs checks. Is the memory map present? Are region lengths nonzero? Does the framebuffer range have a plausible size? Does the kernel image range make sense? Is the physical memory offset present before using an offset page-table mapper? Is the RSDP pointer nonzero before ACPI initialization? Early validation produces clear failure messages instead of later page faults.

11.3: Introducing ACPI, APIC, SMP, and Real Hardware Constraints

Section titled “11.3: Introducing ACPI, APIC, SMP, and Real Hardware Constraints”

The kernel so far has used a deliberately controlled hardware model. The legacy PIC routes timer and keyboard interrupts. The PIT can provide a timer tick. The keyboard controller can produce scancodes. The framebuffer or VGA path can show output. This is enough for a strong educational kernel, but real hardware support requires discovery rather than fixed assumptions. Modern systems do not ask the kernel to guess where every interrupt controller, processor, timer, and device lives. They provide firmware tables that describe platform configuration. The most important family of tables for this stage is ACPI.

ACPI provides structured information about hardware configuration, power management, interrupt routing, timers, processor topology, and other platform details. For a kernel, one of the first ACPI goals is to find the tables that describe interrupt controllers and processors. The loader may pass the physical address of the RSDP, which is the starting point for locating ACPI tables. The kernel then maps and parses those tables carefully. ACPI data should be treated as firmware-provided structured memory. It is not heap memory. It should not be overwritten. It must be mapped before access, validated before use, and parsed with attention to table lengths and checksums.

ACPI matters because it leads the kernel away from hard-coded hardware assumptions. With the legacy PIC, the kernel assumes IRQ0 is the timer and IRQ1 is the keyboard, remapped to selected IDT vectors. With APIC support, interrupt routing becomes more flexible and more complex. The local APIC handles per-CPU interrupt delivery and timer functionality. The local APIC routes external device interrupts to local APICs. ACPI tables can describe which processors exist, where APIC structures are located, and how interrupt lines are connected. This information is required for a modern interrupt model.

The APIC changes the way the kernel thinks about interrupts. The legacy PIC is a simple starting point, but it is not designed for modern multiprocessor interrupt routing. The local APIC is associated with a CPU. It can receive interrupts, send inter-processor interrupts, and provide a local timer. The I/O APIC receives external interrupt lines and routes them to local APICs using redirection entries. Moving from PIC to APIC means the kernel must configure memory-mapped APIC registers, understand interrupt vectors, mask and unmask routes, and send end-of-interrupt signals through the local APIC rather than the PIC.

This also changes timer design. The PIT is useful for early ticks, but APIC timers and other modern timer sources provide better integration with processor interrupt handling. A kernel can begin with PIT because it is easy to see working. Later, it can calibrate or configure local APIC timers for per-CPU scheduling ticks. A mature kernel may support multiple timer sources and choose one based on hardware capabilities. For this project, the

important point is that the timer architecture should not be permanently tied to the PIT. The timer module should expose a kernel tick or time interface while hiding the underlying hardware source.

SMP, or symmetric multiprocessing, introduces multiple CPUs running kernel code. This is one of the biggest changes in operating-system development because assumptions that are safe on one CPU become unsafe on many CPUs. Disabling interrupts on one CPU does not stop another CPU. A spinlock that worked in a single-core kernel may now contend across cores. Global state can be modified truly concurrently. Per-CPU data becomes necessary. Page-table changes may require TLB shootdowns, where one CPU tells other CPUs to invalidate stale translations. Scheduling becomes per-core or coordinated across cores. Interrupt routing must decide which CPU handles which interrupt.

Starting additional processors on x86_64 requires a careful sequence. The bootstrap processor is the CPU that starts first and runs the initial kernel. Application processors must be discovered, prepared, and started through architecture-specific mechanisms. The kernel needs startup code for secondary processors, per-CPU stacks, per-CPU GDT or TSS state where needed, local APIC setup, and synchronization so secondary CPUs do not run into uninitialized global state. This is not a small add-on. It is a major architectural milestone.

Real hardware constraints also affect memory. Physical memory may not be one simple contiguous range. Some addresses may be reserved for devices. Some memory may be above 4 GiB. Some regions may have different caching requirements. Memory-mapped device registers must not be treated like normal cached RAM. Firmware runtime regions may need special handling. ACPI tables may live in regions that are not ordinary usable memory. A frame allocator must stay conservative and use the memory map correctly. A virtual memory manager must map device memory with appropriate flags.

Device discovery is another major step. Early code can assume a serial port at a legacy base address or a keyboard data port at 0x60, but a more capable kernel needs to discover devices through buses such as PCI. PCI

configuration space describes devices, vendors, classes, BARs, interrupt lines, and memory-mapped regions. A driver model can then bind drivers to devices based on class codes or identifiers. That system is beyond the current kernel, but the design should leave room for it. Drivers should not be random global functions. They should become services that can be initialized, registered, and queried.

Real machines also produce firmware and hardware differences. A feature that works in QEMU may rely on emulated behavior that is more forgiving than physical hardware. A framebuffer format may differ. A keyboard path may not be present in the same way. Serial output may not be available or visible. Interrupt routing may differ. ACPI tables may describe a setup that does not match simple PIC assumptions. Testing under QEMU is essential, but it is not proof of universal hardware support. The professional response is not to abandon QEMU. It is to treat QEMU as a controlled first target and build diagnostics that can later help on wider hardware.

The kernel should therefore develop hardware discovery as a staged system. First, accept firmware table pointers from the bootloader. Then map and validate ACPI root tables. Then parse only the tables needed for the next feature. For APIC support, that usually means finding processor and APIC information. Then create internal data structures that describe CPUs and interrupt controllers. Then initialize the local APIC on the bootstrap processor. Then route a small number of interrupts through the I/O APIC. Then consider starting additional processors. Each stage should print diagnostics and have a clear fallback or failure path.

SMP also forces a stronger policy around global locks and interrupt context. Earlier, disabling interrupts while holding a lock could prevent reentrant interrupt deadlock on one CPU. On multiple CPUs, that does not stop another CPU from taking or waiting on the same lock. Locks need clear ordering. Per-CPU data should reduce contention. Interrupt handlers must avoid long critical sections. Allocators may need per-CPU caches or stronger synchronization. Logging must handle multiple CPUs without interleaving unreadable output. The scheduler must protect run queues. Page-table changes must coordinate across cores.

These are not reasons to avoid ACPI, APIC, or SMP. They are reasons to treat them as major design upgrades. A kernel that handles them well becomes much more serious. It moves from a controlled single-core educational system toward a platform-aware operating system. The foundation already built still matters: serial logging, exception handling, memory maps, page tables, heap allocation, tests, and shell diagnostics all help make advanced hardware work possible. Without those tools, ACPI and SMP debugging quickly becomes guesswork.

11.4: Roadmap to Filesystems, Userspace, Scheduling, and System Calls

Section titled “11.4: Roadmap to Filesystems, Userspace, Scheduling, and System Calls”

A kernel with boot support, memory management, interrupts, heap allocation, input, and diagnostics has reached a meaningful stage, but a complete operating system needs more. The next major features are filesystems, userspace, scheduling, and system calls. These are not small additions. Each one changes the kernel’s responsibilities and introduces new failure modes. They should be added in an order that builds on the current foundation rather than fighting it.

A filesystem gives the kernel a way to organize persistent data. Before a filesystem, the kernel may be able to load modules from the bootloader or use an initial RAM disk, but it does not have a general way to name, open, read, write, and manage files. The first practical step is often an initial RAM disk because it avoids writing a full storage driver immediately. The bootloader can load a file archive as a module, and the kernel can parse it from memory. This allows the kernel to test path lookup, file metadata, and read operations without controlling a disk device yet.

After an initial RAM disk, a simple filesystem such as FAT-style storage is a reasonable next target because it is widely understood and easier than a modern journaling filesystem. Even then, the kernel needs a block-device abstraction. A filesystem should not talk directly to one disk controller. It should request blocks from a block device. The block device may later be backed by an ATA driver, AHCI driver, NVMe driver, RAM disk, or virtual

device. This separation keeps filesystem code independent of hardware transport.

A virtual filesystem layer comes after that. It provides a common interface for different filesystems and devices. Paths can be resolved into nodes. Files can be opened and read through handles. Directories can be listed. Device files or pseudo-files can be added later. A VFS is not just a convenience. It is the layer that prevents the rest of the kernel from depending on one on-disk format. Without it, every service that needs file access becomes tied to the first filesystem implementation.

Userspace is a larger boundary. Up to now, all code runs in kernel mode. That means every function has full privilege. Userspace introduces less-privileged execution, separate address spaces, controlled transitions into the kernel, and isolation between programs. This requires page-table policy, privilege-level setup, user-accessible mappings, kernel-only mappings, user stacks, executable loading, and a safe way to enter and leave user mode. It also requires the kernel to stop trusting pointers from user programs. A pointer passed from user mode is not automatically safe for the kernel to read or write. It must be validated against the current process address space and access permissions.

Loading user programs usually means parsing an executable format, mapping code and data segments into a process address space, creating a user stack, setting an initial instruction pointer, and entering ring 3 with the correct CPU state. This depends on earlier paging work. Each process needs a virtual address space. Kernel memory may be mapped into every address space at high addresses, but user mappings must be isolated. A bug in this layer can allow one process to corrupt another process or the kernel, so correctness matters.

Scheduling is the system that decides what runs. The first scheduler can be cooperative, where tasks yield voluntarily. This is easier because context switches occur at known points. A preemptive scheduler uses timer interrupts to regain control and switch tasks even when they do not yield. That is closer to what general-purpose operating systems need, but it is harder. Preemption means a task can be interrupted while holding locks or

modifying data. The kernel must preserve CPU state, switch stacks, manage run queues, and enforce synchronization rules.

A task structure begins as saved execution state plus scheduling metadata. For kernel tasks, this may include a stack pointer, state, and function entry. For user processes, it also includes an address space, user registers, file handles, signal or event state, and permissions. Context switching requires saving the old task’s state and restoring the new task’s state. On x86_64, that includes general-purpose registers and stack state, with additional considerations for floating-point and SIMD state if those features are used. Early kernels can avoid floating-point in kernel and user tasks until they implement proper state saving.

System calls provide the controlled boundary between userspace and the kernel. User programs cannot directly access hardware, page tables, or kernel data structures. They request services through system calls. A system call interface might provide operations such as writing to a console, reading input, allocating memory, opening files, reading files, creating processes, waiting for events, and exiting. The interface must validate arguments carefully. A user pointer may point to unmapped memory, read-only memory, kernel memory, or a buffer shorter than claimed. The kernel must copy data across the boundary safely.

The system-call mechanism itself is architecture-specific. x86_64 provides fast syscall instructions, but using them requires model-specific register setup and careful entry and exit paths. A simpler early design can use software interrupts for system calls, because the IDT path is already understood. That may be slower, but it is easier to reason about while developing the first userspace boundary. Later, the kernel can move to a faster mechanism once the semantics are correct.

The order of these next features should be conservative. A good path is to add an initial RAM disk before full disk drivers, then add a simple VFS, then load a very small user program from memory, then enter user mode with a fixed address space, then implement one or two system calls, then add cooperative task switching, then move toward preemptive scheduling. Full storage drivers, advanced filesystems, process trees, permissions, pipes,

networking, and graphics can come later. Building too much at once makes failure hard to diagnose.

The kernel shell can support this roadmap by exposing diagnostic commands. It can list memory regions, show loaded modules, print the active address space, display tick counts, run allocator tests, trigger controlled page faults, list tasks, and later inspect filesystem roots. A shell command is not a user program, but it gives the kernel a practical control surface while userspace is still under construction. Once userspace exists, the shell can eventually move out of the kernel and become a user process. That is a major design milestone because it means interactive command handling no longer needs full kernel privilege.

Testing must also grow with the features. Filesystem tests should use known in-memory images. VFS tests should check path resolution and file reads. User-mode tests should intentionally attempt invalid memory access and confirm the kernel rejects it safely. Scheduler tests should verify that tasks switch and that timer ticks continue. System-call tests should pass valid and invalid arguments. Page-fault tests should distinguish kernel faults from user faults. The more capable the kernel becomes, the more important regression testing becomes.

The biggest professional shift is moving from a single address space and single execution context toward isolated, scheduled execution. Memory safety at the Rust level remains valuable, but the kernel now enforces safety between programs through page tables, privilege levels, and system-call validation. Rust can help structure the code, but the CPU and kernel policy provide isolation. A wrong user-accessible page flag, a missing pointer check, or a scheduler bug can break that isolation. The same discipline used for early unsafe code applies at system scale: state the invariant, encode what you can in types, check what must be checked at runtime, and keep dangerous operations behind narrow interfaces.

A realistic next-system roadmap does not promise everything at once. It treats each feature as a layer. Storage needs block devices. Filesystems need block and VFS abstractions. Userspace needs address spaces and privilege transitions. Scheduling needs task state and timer support. System calls

need a safe entry path and argument validation. Multicore support needs APIC, per-CPU state, and stronger synchronization. Networking needs drivers, buffers, protocols, timers, and user-facing APIs. Each feature depends on foundations that are already present or must be built first.

The kernel built so far is therefore not a toy in the dismissive sense. It is an educational kernel with the core mechanisms required for further work: boot handoff, serial diagnostics, CPU tables, exception handling, memory maps, frame allocation, paging, heap allocation, hardware interrupts, timer ticks, keyboard input, shell commands, tests, and QEMU debugging. Those are real operating-system foundations. The next stage is to turn those foundations into policy: how files are named, how programs are isolated, how tasks share the CPU, how userspace requests services, and how hardware is discovered instead of assumed.