Skip to content
ImagineWorld

x86_64 CPU Setup and Kernel Execution State

node_idnode-book_writing-operating-systems-in-rust_chapter-04-x86-64-cpu-setup-and-kernel-execution-state
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num4
chapter_titlex86_64 CPU Setup and Kernel Execution State
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 4 — x86_64 CPU Setup and Kernel Execution State

Section titled “Chapter 4 — x86_64 CPU Setup and Kernel Execution State”

Chapter 4: x86_64 CPU Setup and Kernel Execution State

Section titled “Chapter 4: x86_64 CPU Setup and Kernel Execution State”

A Rust kernel can begin executing only after the processor is in a state where the generated machine code makes sense. The compiler may produce clean 64-bit instructions, but the CPU still needs the correct execution mode, a valid stack, usable memory mappings, and processor tables that match how the kernel expects faults and interrupts to behave. Early kernel work is therefore not only about writing Rust functions. It is also about taking control of the processor environment in a careful and visible way.

The bootloader may already have done some of this work. It may have placed the CPU in 64-bit long mode, built initial page tables, loaded the kernel image, prepared a stack, and passed boot information to the kernel. That early help is valuable, but it should not make the CPU state feel automatic. The kernel still needs to understand what it inherited and what it must later own. A bootloader-provided execution state is a starting point. A stable kernel needs deliberate control over descriptor tables, interrupt stacks, control registers, and the memory translation environment.

This is where x86_64 setup begins to feel different from ordinary programming. Concepts such as the Global Descriptor Table, Task State Segment, interrupt stacks, control registers, and model-specific behavior are not library details. They are part of how the processor decides what code may execute, which stack is used during certain faults, how memory addresses are translated, and how privileged instructions behave. If these structures are wrong, the kernel may not receive a helpful error. It may fault again while trying to report the first fault, then reset the machine.

Rust helps by letting you express these structures through clear types and small initialization functions. It does not remove the need to understand what those structures mean. The goal is to keep CPU setup explicit, readable, and testable through early output. Each step should have a reason. Each unsafe operation should be placed behind a narrow function. Each processor state change should happen in a predictable order. This gives the

kernel a stronger foundation before exceptions, interrupts, memory allocation, and hardware input arrive.

4.1: Long Mode, Privilege Levels, and CPU State

Section titled “4.1: Long Mode, Privilege Levels, and CPU State”

The x86_64 architecture supports several execution modes, but a Rust kernel intended to run as 64-bit code expects long mode. Long mode is the execution environment that allows 64-bit instructions, 64-bit general-purpose registers, and the address model used by modern x86_64 software. If the processor is not in long mode, ordinary 64-bit Rust code is not the right kind of code for the current CPU state. This is why the bootloader’s preparation matters. The bootloader usually performs the early transition work so the kernel can start directly in a usable 64-bit environment.

Long mode itself includes more than one concept. In the mode used by a 64-bit kernel, the processor executes 64-bit code with paging enabled. Paging is not an optional side feature here. Long mode depends on paging being active. That means the addresses used by the kernel are virtual addresses translated through page tables into physical memory. Even at the first Rust instruction, address translation is already part of execution. If the entry address, stack address, code section, or boot information address is not mapped correctly, the kernel may fail immediately.

This is one reason a bootloader handoff should never be treated as a vague jump. The handoff includes assumptions about active page tables and address mappings. The kernel needs to know whether the bootloader identity-mapped some memory, mapped the kernel into a higher virtual address range, provided a direct mapping of physical memory, or used another arrangement. Later memory-management code depends on these facts. If the kernel tries to access a physical address as if it were a valid virtual address, a page fault may occur. If the page fault handler is not ready, that fault may become a reset rather than a readable diagnostic.

The processor also has privilege levels. On x86_64, privilege levels are often called rings. Ring 0 is the most privileged level and is where the kernel normally runs. Ring 3 is where ordinary user applications run once the operating system supports userspace. Rings 1 and 2 exist but are rarely used

in common operating-system designs. Early in this kernel, everything runs in ring 0. There is no userspace yet, no system-call boundary, and no separation between kernel code and application code. That is acceptable at this stage, but it is important to understand the consequence. All code currently has full privilege. A wrong instruction, wrong pointer, or wrong port write can affect the whole machine.

Privilege levels are connected to descriptors, selectors, and later interrupt behavior. In 64-bit mode, segmentation is mostly disabled for ordinary address calculation. That can make the Global Descriptor Table seem unimportant at first. It is still required. The processor still uses segment selectors for code and data privilege metadata, and the Task State Segment still matters for stack switching during certain events. A modern x86_64 kernel cannot simply ignore the GDT because it no longer uses segmentation for ordinary memory layout. The role changed, but it did not disappear.

CPU state also includes registers that control the processor’s behavior. General-purpose registers such as rax, rbx, rcx, rdx, rsp, and rip are visible in normal low-level debugging. The stack pointer rsp is especially important because Rust functions use the stack for calls, locals, saved values, and return addresses. If the stack points to unmapped memory or memory that the kernel later reuses incorrectly, ordinary function calls can corrupt execution. The instruction pointer rip shows where the processor is executing. When debugging early boot with a debugger, confirming that rip reaches the expected entry function is one of the clearest signs that the boot path reached your kernel.

Control registers are more specialized. They define major CPU behavior. cr0 contains flags related to protected mode and paging. cr2 stores the linear address that caused the most recent page fault. cr3 points to the active top-level page table structure. cr4 contains feature controls used by paging and processor extensions. Extended feature state also involves model-specific registers. You do not need to manipulate every one of these at the beginning, but you should learn to read the important ones. When a page fault

happens, cr2 is often one of the first values you want. When investigating address translation, cr3 tells you which page table hierarchy is active.

The flags register is another piece of execution state. It contains status and control flags, including whether interrupts are enabled. Early kernel code often runs with interrupts disabled until the Interrupt Descriptor Table and interrupt controller are configured. Enabling interrupts before the kernel has valid handlers is risky. If hardware interrupts arrive and the CPU does not have a correct descriptor table, the result can be a fault chain rather than a clean interrupt. Controlled sequencing matters. The kernel should prepare the GDT, TSS, IDT, and interrupt-handling path before allowing external interrupts.

Processor state also includes hidden state loaded from descriptor tables. When a segment selector is loaded, the CPU does not merely keep the selector value. It also caches descriptor information internally. This is why loading a new GDT is not always enough by itself. Segment registers may need to be reloaded so the CPU uses descriptors from the new table. Code segment changes often require a far return or a helper function that performs the required transition safely. Library abstractions can help, but the underlying idea remains important: the CPU has state that is not visible as ordinary Rust variables.

A careful kernel treats CPU setup as a staged process. First, it relies on the bootloader to reach the Rust entry point. Then it initializes the earliest output path so startup can be observed. Then it installs the GDT, including descriptors needed for kernel code and the Task State Segment. Then it prepares known-good stacks for faults that need them. Then it installs the Interrupt Descriptor Table. Only after the fault and interrupt paths are ready should the kernel consider enabling interrupts. Later, the memory manager will take stronger control of page tables and address mappings.

The execution state is not static. It evolves as the kernel initializes. At entry, the kernel may use a bootloader-provided stack and page tables. After GDT and TSS setup, it has stronger control over segmentation metadata and special interrupt stacks. After IDT setup, it can handle exceptions more gracefully. After memory setup, it can manage mappings and allocations.

After interrupt-controller setup, it can receive timer and keyboard interrupts. Each stage reduces dependence on temporary boot assumptions and increases kernel ownership.

The professional habit is to make these transitions visible. Print before and after CPU setup steps. If the kernel prints serial online but not gdt loaded, the failure window is small. If it prints gdt loaded but fails before idt loaded, the new code has a clear suspect area. If enabling interrupts causes a reset, the problem may be in IDT setup, interrupt-controller configuration, handler ABI, or stack handling. Without staged output, all of these failures can look like the same black screen or sudden reboot.

Long mode, privilege levels, and CPU state are not abstract background. They explain why the next pieces exist. The GDT gives the processor descriptor information that still matters in 64-bit mode. The TSS gives the processor known stacks for specific privilege transitions and interrupt-stack cases. Control registers show and control the execution environment. Together, these structures help move the kernel from “bootloader started my Rust function” to “the kernel understands and controls its own CPU state.”

4.2: Setting Up the Global Descriptor Table

Section titled “4.2: Setting Up the Global Descriptor Table”

The Global Descriptor Table is one of the first CPU structures a kernel should take control of. In older x86 modes, the GDT played a large role in segmentation, where logical addresses were translated through segment bases and limits. In 64-bit long mode, ordinary segmentation is mostly inactive for code, data, and stack memory. The base and limit fields of most segment descriptors are ignored for normal address calculation. That can make the GDT seem like leftover machinery, but it remains part of the processor’s execution model.

The GDT still provides the code segment descriptor that identifies kernel code execution. It also provides the descriptor for the Task State Segment, which becomes important when setting up safe stacks for faults and privilege transitions. Even if the bootloader already installed a GDT, the kernel should install its own because the kernel should not depend

indefinitely on bootloader-owned processor tables. Once the kernel starts configuring exceptions, interrupts, and stack handling, it needs descriptor-table state that matches its own design.

A GDT is an array of descriptors. A descriptor defines a segment or system structure. The processor does not use Rust types directly. It uses a packed binary format defined by the architecture. You can create this structure manually, but for a Rust kernel it is often better to use a well-tested architecture crate for the descriptor encoding while still understanding the meaning. This reduces the chance of bitfield mistakes in early CPU setup.

The simplest useful GDT for early kernel code contains a kernel code segment. The code segment selector is then loaded so the CPU uses the descriptor from the new table. The following example uses a lazy initialization pattern and an architecture support crate to construct and load the GDT.

Rust

use lazy_static::lazy_static;
use x86_64::instructions::segmentation::{CS, Segment};
use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector};
lazy_static! {
static ref GDT: (GlobalDescriptorTable, Selectors) = {
let mut gdt = GlobalDescriptorTable::new();
let code_selector = gdt.append(Descriptor::kernel_code_segment());
(
gdt,
Selectors {
code_selector,
},
)
};
}
struct Selectors {
code_selector: SegmentSelector,
}
pub fn init() {

GDT.0.load();

unsafe { CS::set_reg(GDT.1.code_selector); }

This code creates a GDT with a kernel code segment and then loads it. The CS::set_reg operation is unsafe because changing the code segment affects the processor’s execution state. The compiler cannot prove that the selector points to a valid descriptor or that the descriptor is appropriate for the current mode. The safety condition comes from the code that built and loaded the GDT. The selector must come from the same table that was just loaded, and the descriptor must be a valid kernel code segment.

This first version is enough to show the basic process, but it is not the full CPU setup you want before handling serious exceptions. The next step is to add a Task State Segment descriptor. The TSS is a special structure that the CPU can use for stack information. In long mode, it is not used for hardware task switching in the old sense, but it still matters for interrupt stack table entries and privilege-level stack fields. The GDT stores a descriptor that points to the TSS.

use lazy_static::lazy_static;
use x86_64::VirtAddr;
use x86_64::instructions::segmentation::{CS, Segment};
use x86_64::instructions::tables::load_tss;
use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector};
use x86_64::structures::tss::TaskStateSegment;
pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
lazy_static! {
static ref TSS: TaskStateSegment = {
let mut tss = TaskStateSegment::new();
const STACK_SIZE: usize = 4096 * 5;
static mut DOUBLE_FAULT_STACK: [u8; STACK_SIZE] = [0; STACK_SIZE];
<!-- page: 103 -->
let stack_start =
VirtAddr::from_ptr(core::ptr::addr_of!(DOUBLE_FAULT_STACK));
let stack_end = stack_start + STACK_SIZE;
tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = stack_end;
tss
};
lazy_static! {
static ref GDT: (GlobalDescriptorTable, Selectors) = {
let mut gdt = GlobalDescriptorTable::new();
let code_selector =
gdt.append(Descriptor::kernel_code_segment());
let tss_selector =
gdt.append(Descriptor::tss_segment(&TSS));
(
gdt,
Selectors {
code_selector,
tss_selector,
},
)
};
}
struct Selectors {
code_selector: SegmentSelector,
tss_selector: SegmentSelector,
}
pub fn init() {
GDT.0.load();
unsafe {
CS::set_reg(GDT.1.code_selector);
load_tss(GDT.1.tss_selector);
}
}
This version adds a static TSS and a dedicated stack for double faults. The stack is represented as a static byte array. The TSS stores the end address of the stack because x86_64 stacks grow downward. When the CPU uses this
<!-- page: 104 -->
interrupt stack table entry, it starts from the top of the stack region and moves downward as values are pushed.
The use of `static mut` deserves careful attention. A mutable static is dangerous because it can allow aliasing and unsynchronized access. In this case, the stack is not being accessed as an ordinary shared data structure. It is reserved memory that the CPU may use as a stack during a double fault. The code takes its address using raw-pointer construction rather than creating an ordinary mutable reference. That distinction matters in Rust because references carry aliasing guarantees. For low-level reserved memory, raw pointers are often the more honest representation.
A more robust design isolates stack allocation and avoids exposing the static mutable array through normal references. It can also align the stack so it begins at a predictable boundary. Stack alignment is important because the ABI and processor behavior may assume certain alignment guarantees during calls and interrupt handling. While early code may appear to work without explicit alignment, treating stack layout casually is not a good habit.
## Rust
```rust
use lazy_static::lazy_static;
use x86_64::VirtAddr;
use x86_64::instructions::segmentation::{CS, Segment};
use x86_64::instructions::tables::load_tss;
use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector};
use x86_64::structures::tss::TaskStateSegment;
pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
#[repr(align(16))]
struct KernelStack {
bytes: [u8; KernelStack::SIZE],
}
impl KernelStack {
const SIZE: usize = 4096 * 5;
const fn new() -> Self {
Self {
bytes: [0; Self::SIZE],
}
}
}

fn start_address(&self) -> VirtAddr { VirtAddr::from_ptr(self.bytes.as_ptr()) }

fn end_address(&self) -> VirtAddr { self.start_address() + Self::SIZE }

static DOUBLE_FAULT_STACK: KernelStack = KernelStack::new();

lazy_static! { static ref TSS: TaskStateSegment = { let mut tss = TaskStateSegment::new(); tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = DOUBLE_FAULT_STACK.end_address(); tss }; }

lazy_static! { static ref GDT: (GlobalDescriptorTable, Selectors) = { let mut gdt = GlobalDescriptorTable::new();

let code_selector =
gdt.append(Descriptor::kernel_code_segment());
let tss_selector =
gdt.append(Descriptor::tss_segment(&TSS));
(
gdt,
Selectors {
code_selector,
tss_selector,
},
)
};

}

struct Selectors { code_selector: SegmentSelector, tss_selector: SegmentSelector, }

pub fn init() { GDT.0.load(); }

rust unsafe { CS::set_reg(GDT.1.code_selector); load_tss(GDT.1.tss_selector); }

This version wraps the stack bytes inside a type and gives the stack explicit alignment. It exposes only address calculations. The stack memory is still static, but it is not declared as `static mut`. The CPU will use this memory as a stack when the configured interrupt stack table entry is selected. Rust does not track that use as a normal mutable borrow, so the design must ensure the stack is reserved exclusively for that purpose.
The GDT initialization function should run early, after serial output is available and before the Interrupt Descriptor Table is loaded with handlers that rely on the TSS. A typical startup sequence initializes serial output, prints an early checkpoint, initializes the GDT, then prints another checkpoint. This gives you visibility into failures that occur during descriptor-table setup.
## Rust
```rust
#[unsafe(no_mangle)]
pub extern "C" fn _start() -> ! {
serial::init();
serial_println!("kernel entered");
gdt::init();
serial_println!("gdt loaded");
loop {
x86_64::instructions::hlt();
}
}

This entry sequence is intentionally small. It gives a clear checkpoint before and after GDT setup. If the kernel prints kernel entered but not gdt loaded, the failure likely occurred inside or immediately after GDT initialization. If it prints both lines, the new GDT was loaded successfully enough for execution to continue.

A GDT bug can produce failures that look unrelated. If the code segment selector is invalid, execution can fault. If the TSS descriptor is wrong, loading the TSS can fault. If the double-fault stack address is invalid or unmapped, the system may reset when a double fault occurs. If the GDT is stored in memory that is later overwritten or unmapped, the processor may fail during later descriptor use. For this reason, the GDT and TSS should live in stable static memory that remains mapped for the lifetime of the kernel.

The GDT is not a feature you will constantly change after initialization, but it is foundational. It tells the CPU which descriptors define kernel execution and where to find the TSS. Once it is loaded, later exception and interrupt setup can rely on it. The important outcome is not that the code contains a GDT because tradition says kernels need one. The important outcome is that the kernel has taken ownership of descriptor state that affects code execution and safe fault handling.

4.3: Configuring the Task State Segment and Safe Interrupt Stacks

Section titled “4.3: Configuring the Task State Segment and Safe Interrupt Stacks”

The Task State Segment has a confusing name because its modern use in a 64-bit kernel is not the same as the old hardware task-switching model. In long mode, the TSS is still a special CPU structure, but it is mainly useful for stack information. It can hold stack pointers for privilege-level changes and entries in the interrupt stack table. For an early kernel, the interrupt stack table is the important part because it allows selected interrupt or exception handlers to run on known-good stacks.

A known-good stack matters most when the current stack may be damaged, exhausted, unmapped, or unsafe to use. The classic example is a double fault. A double fault occurs when the processor encounters a second exception while trying to call the handler for a previous exception. One common cause is a stack overflow. If the current stack overflows into an unmapped guard page and the page-fault handler tries to use the same broken stack, handling the page fault may itself fail. The CPU then raises a

double fault. If the double-fault handler also tries to use the same broken stack, the machine may triple-fault and reset.

The interrupt stack table gives the CPU a way out. For selected IDT entries, the handler can specify an IST index. When that exception or interrupt occurs, the CPU switches to the corresponding stack address stored in the TSS before calling the handler. This means the double-fault handler can use a separate reserved stack even if the normal kernel stack is not usable. That is why the TSS must be configured before the IDT entry for double faults can safely reference an IST index.

The TSS itself must live in memory that remains valid and mapped. The GDT contains a descriptor pointing to it. Loading the TSS tells the CPU which TSS selector to use. The TSS stack entries must point to memory that is also valid and mapped. It is not enough to create a local array inside an initialization function because that array would disappear when the function returns. The stack must be static or otherwise allocated from memory that remains reserved for the life of the kernel.

A clean setup begins by reserving a stack and writing its top address into the TSS. Since stacks grow downward on x86_64, the TSS receives the end address of the stack region, not the beginning.

use lazy_static::lazy_static;
use x86_64::VirtAddr;
use x86_64::structures::tss::TaskStateSegment;
pub const DOUBLE_FAULT_IST_INDEX: u16 = 0;
#[repr(align(16))]
struct InterruptStack {
bytes: [u8; InterruptStack::SIZE],
}
impl InterruptStack {
const SIZE: usize = 4096 * 5;
const fn new() -> Self {
Self {

bytes: [0; Self::SIZE], }

fn top(&self) -> VirtAddr { let start = VirtAddr::from_ptr(self.bytes.as_ptr()); start + Self::SIZE }

static DOUBLE_FAULT_STACK: InterruptStack = InterruptStack::new();

lazy_static! { pub static ref TSS: TaskStateSegment = { let mut tss = TaskStateSegment::new(); tss.interrupt_stack_table[DOUBLE_FAULT_IST_INDEX as usize] = DOUBLE_FAULT_STACK.top(); tss }; }

This code reserves a statically allocated stack and stores its top address in the TSS interrupt stack table. The repr(align(16)) annotation gives the stack object a clear alignment. The stack is not exposed as mutable Rust data. Its job is to be used by the processor during a specific exception path. That is a low-level ownership rule: the stack memory is reserved for the CPU’s handler entry behavior, not for general kernel allocation.

The TSS alone does nothing until it is described in the GDT and loaded. The GDT must contain a TSS descriptor, and the kernel must load that selector with the appropriate instruction. This ties the GDT and TSS together.

use lazy_static::lazy_static;
use x86_64::instructions::segmentation::{CS, Segment};
use x86_64::instructions::tables::load_tss;
use x86_64::structures::gdt::{Descriptor, GlobalDescriptorTable, SegmentSelector};
use crate::tss::TSS;
lazy_static! {
static ref GDT: (GlobalDescriptorTable, Selectors) = {
<!-- page: 110 -->
rust
let mut gdt = GlobalDescriptorTable::new();
let code_selector =
gdt.append(Descriptor::kernel_code_segment());
let tss_selector =
gdt.append(Descriptor::tss_segment(&TSS));
(
gdt,
Selectors {
code_selector,
tss_selector,
},
)
);
struct Selectors {
code_selector: SegmentSelector,
tss_selector: SegmentSelector,
}
pub fn init() {
GDT.0.load();
unsafe {
CS::set_reg(GDT.1.code_selector);
load_tss(GDT.1.tss_selector);
}
}

The order here matters. The GDT is loaded first. Then the code segment selector is loaded. Then the TSS selector is loaded. Loading the TSS before the GDT contains the proper descriptor would be invalid. Loading a selector that does not refer to a valid TSS descriptor would fault. These instructions change processor state, so the unsafe block is appropriate. The safety comes from the fact that the descriptors were created correctly and that the underlying static TSS remains valid.

Once the TSS exists and has a double-fault stack, the IDT can use the corresponding IST index for the double-fault handler. This connects the exception-handling path to the safe stack.

Rust

use lazy_static::lazy_static; use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame};

use crate::gdt::DOUBLE_FAULT_IST_INDEX;

lazy_static! { static ref IDT: InterruptDescriptorTable = { let mut idt = InterruptDescriptorTable::new();

unsafe {
idt.double_fault
.set_handler_fn(double_fault_handler)
.set_stack_index(DOUBLE_FAULT_IST_INDEX);
}
idt
};

}

pub fn init() { IDT.load(); }

extern “x86-interrupt” fn double_fault_handler( stack_frame: InterruptStackFrame, error_code: u64, ) -> ! { panic!(“double fault: {:#?}, error code: {}”, stack_frame, error_code); }

The call to set_stack_index is unsafe because the compiler cannot verify that the index refers to a valid TSS interrupt stack table entry. You must guarantee that the TSS has been initialized, that the stack entry exists, and that the GDT and TSS have been loaded before a double fault can use this IDT entry. This is a good example of Rust’s low-level model. The unsafe call is not bad by itself. It is a precise marker that the programmer must uphold architecture-specific conditions.

The double-fault handler returns ! because a double fault is not something an early kernel should try to recover from. The best behavior is to report the failure and stop. Later, a mature kernel may have more specific diagnostic behavior, but continuing after a double fault during early development is usually unsafe. The system state is already suspect.

The double-fault stack should be large enough for the handler and diagnostic output, but it should not be treated as unlimited. Printing complex debug information from a fault path can use stack space. If the double-fault stack is too small, the handler itself may overflow. A few pages are commonly used for an early educational kernel, but the exact size is a design choice. Once paging and guard pages are available, a more complete design can place guard pages around critical stacks so overflows become detectable faults rather than silent corruption.

The TSS can hold more than one IST entry. The double-fault stack is the first high-value use, but other exceptions may benefit from dedicated stacks as the kernel matures. A non-maskable interrupt, machine-check exception, or critical diagnostic path may use its own stack in more advanced designs. For the current stage, one double-fault stack is enough to prevent one of the most common early reset patterns.

There is a subtle but important difference between reserving a stack and proving that the CPU can use it. If the stack memory is not mapped in the active page tables, the CPU can fault while switching to it. If the stack address is wrong, the handler may corrupt unrelated memory. If the IST index in the IDT does not match the TSS entry, the handler may not use the stack you intended. If the GDT was loaded but the TSS was not, the IST configuration is not complete. This is why staged initialization and serial checkpoints are useful.

A typical initialization flow should load the GDT and TSS before loading the IDT. Then the IDT can reference the configured IST index. After that, the kernel can deliberately test the double-fault path only when it has enough output to observe the result. Testing fault paths should be done carefully because some tests intentionally break execution. A controlled double-fault test is useful, but it should not remain in normal startup code.

pub fn init_cpu_tables() {
crate::gdt::init();
serial_println!("gdt and tss loaded");
}
crate::idt::init();
serial_println!("idt loaded");
}

This function gives the startup sequence a clear structure. It treats GDT, TSS, and IDT setup as related CPU-table initialization. The serial checkpoints are not decoration. They make it easier to identify whether the kernel failed while loading descriptors or while loading interrupt handlers.

The TSS also includes privilege stack table entries, which become important when moving between privilege levels. Early in the kernel, everything runs in ring 0, so privilege transitions are not active yet. Later, when userspace is introduced, the CPU will need a kernel stack to use when an interrupt or system call transfers from ring 3 to ring 0. The TSS provides stack pointers for those transitions. Even if that feature is not used immediately, configuring the TSS correctly now prepares the mental model for future userspace support.

Safe interrupt stacks are about damage control. They do not prevent every fault. They do not make invalid memory access safe. They do not fix a broken page table. What they do is give the processor a reliable place to run certain emergency handlers when the current stack cannot be trusted. That single capability can turn a silent reset into a readable double-fault message. In early kernel development, that is a major improvement.

4.4: Reading Control Registers and Understanding Processor State

Section titled “4.4: Reading Control Registers and Understanding Processor State”

Control registers reveal the processor configuration that the kernel is running under. They are not ordinary variables, and they are not stored in memory where Rust can borrow them. They are CPU registers with special meaning. Reading them helps you understand paging state, page-fault addresses, active page tables, and enabled processor features. Writing them can change major execution behavior, so early code should read first and modify only when the design requires it.

The most immediately useful control registers are cr2 and cr3. cr2 contains the virtual address that caused the most recent page fault. When a page-fault handler runs, reading cr2 tells you which address the CPU could not translate or access according to the page-table permissions. That value is essential for debugging memory-management bugs. cr3 contains the physical address of the active top-level page table, along with related control bits depending on CPU features. Reading cr3 helps confirm which address space is currently active.

Architecture support crates often provide typed access to these registers, which is safer than writing inline assembly each time. The following example reads cr2 and prints the faulting address from inside a page-fault handler.

Rust

use x86_64::registers::control::Cr2;
use x86_64::structures::idt::{InterruptStackFrame, PageFaultErrorCode};
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!("stack frame: {:?}", stack_frame);
loop {
x86_64::instructions::hlt();
}
}

This handler reports the page-fault address, the error code, and the interrupt stack frame. The address from cr2 answers the first practical question: what was the kernel trying to access? The error code answers the second: what kind of access failed? The stack frame gives the instruction pointer and other saved state. Together, these values can turn a confusing crash into a clear memory bug.

The page-fault error code contains important meaning. It can indicate whether the fault was caused by a non-present page, a protection violation, a write access, a user-mode access, an instruction fetch, or other conditions depending on enabled features. This is why printing only page fault is not enough. A write to an unmapped heap page is different from executing code from a non-executable page. A user-mode access violation is different from a kernel-mode mapping mistake. The same exception vector can represent different problems.

A more useful page-fault handler can separate the fields and print a message that is easier to read. The exact methods available depend on the IDT and register support crate you use, but the pattern is consistent: decode the error code into useful facts before stopping.

use x86_64::registers::control::Cr2;
use x86_64::structures::idt::{InterruptStackFrame, PageFaultErrorCode};
extern "x86-interrupt" fn page_fault_handler(
stack_frame: InterruptStackFrame,
error_code: PageFaultErrorCode,
) {
let accessed_address = Cr2::read();
serial_println!("page fault at {:?}", accessed_address);
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!("mode: user");
} else {
serial_println!("mode: kernel");
}
}
}
if error_code.contains(PageFaultErrorCode::INSTRUCTION_FETCH)
{
serial_println!("instruction fetch fault");
}
serial_println!("stack frame: {:?}", stack_frame);
loop {
x86_64::instructions::hlt();
}

This style of output becomes very valuable once paging code is added. If the kernel maps a heap page without the writable flag, the page fault will show a protection violation on a write. If the kernel tries to access memory that was never mapped, it will show a non-present page. If an instruction fetch fails, the instruction pointer or execute permissions become suspicious. These distinctions save time because they point directly at the kind of mapping mistake involved.

Reading cr3 is useful when working with page tables. It tells you where the active top-level page-table frame is located. At first, the bootloader may set up the active page tables. Later, the kernel may create or modify mappings. Printing cr3 helps confirm the active table during early memory work.

use x86_64::registers::control::Cr3;
pub fn print_active_page_table() {
let (level_4_frame, flags) = Cr3::read();
serial_println!("active level 4 frame: {:?}", level_4_frame);
serial_println!("cr3 flags: {:?}", flags);
}

This function does not change processor state. It reads and reports it. That is a good first step. Before writing to control registers or replacing page tables, learn to inspect the current state. If a later mapping operation fails, knowing the active top-level table is essential.

Other control registers help explain the execution environment. cr0 contains the paging-enable bit and other major controls. cr4 contains feature controls such as physical-address extension and other processor capabilities used by modern paging modes. In a typical long-mode kernel handed off by a bootloader, the expected bits are already set. Reading them can confirm assumptions.

use x86_64::registers::control::{Cr0, Cr4};
pub fn print_control_state() {
let cr0 = Cr0::read();
let cr4 = Cr4::read();
serial_println!("cr0: {:?}", cr0);
serial_println!("cr4: {:?}", cr4);
}

This diagnostic function is useful during early CPU setup. It can be called after serial output is initialized. If the output confirms expected paging and mode-related features, you have evidence that the bootloader prepared the CPU as expected. If the values do not match assumptions, the boot path or target configuration may not be the one you think it is.

You can also read the flags register to see whether interrupts are currently enabled. This helps verify initialization order. Before the IDT and interrupt controller are ready, interrupts should generally remain disabled. After enabling interrupts, reading flags can confirm the change.

use x86_64::registers::rflags::RFlags;
pub fn print_interrupt_flag() {
let flags = RFlags::read();
if flags.contains(RFlags::INTERRUPT_FLAG) {
serial_println!("interrupts: enabled");
} else {
serial_println!("interrupts: disabled");
}
}

This kind of small diagnostic function is helpful because interrupt state is invisible in normal source code. A function call to enable interrupts may not behave as expected if it is not reached, if a fault occurs first, or if later code disables interrupts again. Printing the actual flag gives you direct evidence.

Writing control registers is far more sensitive than reading them. Changing cr3, for example, switches the active page-table hierarchy. If the new page table does not map the currently executing code, stack, GDT, IDT, TSS, and output device memory as needed, the CPU may fault immediately. Changing cr0 or cr4 can enable or disable processor behavior that affects the entire kernel. These operations belong inside carefully designed memory-management code, not scattered through startup experiments.

When the time comes to switch page tables, the code should be explicit about the safety requirements. The new table must be valid. It must be physically accessible to the CPU. It must map the instruction stream that continues after the switch. It must map the current stack. It must preserve access to any CPU tables and devices required by immediate code. If those conditions are not met, the write to cr3 may be the last instruction that works.

use x86_64::PhysAddr;
use x86_64::registers::control::{Cr3, Cr3Flags};
use x86_64::structures::paging::{PhysFrame, Size4KiB};
pub unsafe fn switch_to_page_table(frame_start: PhysAddr) {
let frame =
PhysFrame::<Size4KiB>::containing_address(frame_start);
unsafe {
Cr3::write(frame, Cr3Flags::empty());
}
}

This function is unsafe for the right reason. It changes the active page table. Rust cannot verify that the new page table is valid or that it maps the current execution context. The function should not be called until the memory-

management code can prove those conditions. In many early kernels, you do not need to switch page tables immediately. It is often better to inspect and extend the existing mapping first.

Processor-state diagnostics should be integrated into the kernel’s debug output. During early startup, after the GDT and IDT are loaded, you can print control state to confirm the environment.

pub fn print_cpu_state() {
serial_println!("cpu state");
crate::cpu::print_control_state();
crate::cpu::print_active_page_table();
crate::cpu::print_interrupt_flag();
}

This function collects useful diagnostics behind one call. It should not run constantly in normal operation because the output can become noisy. During early development, it can answer important questions. Is paging enabled? Which page table is active? Are interrupts enabled? Does the state match the kernel’s initialization order?

A page-fault handler should become one of the most informative diagnostics in the system. Once the IDT is active, the handler can print cr2, the error code, and the instruction pointer from the stack frame. This is far better than a silent reset. It also prepares you for memory-management work, where page faults are not just crashes. They are evidence.

use x86_64::registers::control::Cr2;
use x86_64::structures::idt::{InterruptStackFrame, PageFaultErrorCode};
pub extern "x86-interrupt" fn page_fault_handler(
stack_frame: InterruptStackFrame,
error_code: PageFaultErrorCode,
) {
let address = Cr2::read();
serial_println!("page fault");
}
serial_printfln!("address: {:?}", address);
serial_printfln!("error code: {:?}", error_code);
serial_printfln!("instruction pointer: {:?}",
stack_frame.instruction_pointer);
serial_printfln!("stack pointer: {:?}",
stack_frame.stack_pointer);
crate::arch::halt_loop();
}

This handler prints the accessed address, error code, instruction pointer, and stack pointer. The instruction pointer can show where the fault occurred. The stack pointer can reveal whether the kernel was using a plausible stack. If the accessed address is near zero, the problem may be a null pointer or missing mapping. If the address is near a device region, the problem may be an unmapped MMIO access. If the instruction pointer is itself unmapped or strange, the kernel may have jumped through a bad function pointer or returned into invalid memory.

Understanding processor state also helps you avoid false conclusions. A page fault does not always mean “the address does not exist.” It may mean the page is present but not writable. It may mean user code tried to access supervisor memory. It may mean instruction fetch was blocked. It may mean reserved bits were set in a page-table entry. The control register and error-code data separate these cases. Debugging without them leads to guesswork.

Control-register reading should stay close to architecture-specific code. Higher-level kernel modules should not depend on raw CPU registers unless they truly need that information. A memory manager may need page-table state. An exception handler needs cr2. A general shell command might print CPU diagnostics for inspection. Ordinary drivers and allocator code should not casually read control registers. Keeping these boundaries clear prevents architecture details from spreading through the whole project.

At this stage, the most important control-register habit is observational discipline. Read the state. Print it clearly. Use it to verify assumptions. Do not write major control registers until the kernel has the surrounding structures required to survive the change. The processor is already running

in a prepared state from the bootloader. Your job is to understand that state, then gradually replace temporary assumptions with kernel-owned configuration.

Once the kernel can load its GDT, configure its TSS, prepare safe interrupt stacks, and read important processor state, it has moved beyond merely being started by a bootloader. It now has direct control over key parts of the x86_64 execution environment. That control is what makes the next stage possible. Exception handling and memory management depend on these foundations. Without them, faults are silent, stacks are fragile, and page-table bugs are much harder to interpret. With them, the kernel can begin handling failures in a way that produces evidence instead of confusion.