Skip to content
ImagineWorld

Hardware Interrupts, Timers, and Input Devices

node_idnode-book_writing-operating-systems-in-rust_chapter-09-hardware-interrupts-timers-and-input-devices
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleHardware Interrupts, Timers, and Input Devices
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 9 — Hardware Interrupts, Timers, and Input Devices

Section titled “Chapter 9 — Hardware Interrupts, Timers, and Input Devices”

Chapter 9: Hardware Interrupts, Timers, and Input Devices

Section titled “Chapter 9: Hardware Interrupts, Timers, and Input Devices”

Hardware interrupts are the point where the kernel starts responding to devices instead of only reacting to CPU exceptions or running code in a fixed startup sequence. Until now, the kernel has handled events that come from the processor itself, such as breakpoints, page faults, general protection faults, and double faults. Those exceptions are essential, but they are not enough for a usable system. A kernel also needs to receive external events from hardware. The timer must be able to interrupt the CPU at regular intervals. The keyboard must be able to report input. Storage controllers, network devices, and other hardware will eventually need similar attention.

This changes the execution model. Once hardware interrupts are enabled, the kernel can be interrupted between ordinary instructions. A timer interrupt can arrive while the kernel is printing. A keyboard interrupt can arrive while the shell is waiting for input. A device interrupt can arrive while shared state is being modified. The kernel must therefore prepare interrupt handlers, route hardware interrupt lines to known IDT vectors, acknowledge the interrupt controller, and protect shared data that can be touched from both normal code and interrupt context.

Early x86_64 kernel projects often begin with the legacy Programmable Interrupt Controller because it is simple to set up in QEMU and teaches the core interrupt flow clearly. It is not the final interrupt controller design for a modern multiprocessor kernel. More advanced kernels use APIC and I/O APIC paths, often discovered through firmware tables. That comes later. The legacy PIC is useful here because it allows the kernel to receive timer and keyboard interrupts with relatively little code while still teaching the necessary rules: choose interrupt vectors, install IDT handlers, initialize the controller, unmask the lines you need, enable CPU interrupts, and send end-of-interrupt signals after handling them.

Hardware input also introduces a new design pressure. Interrupt handlers should be short. They should avoid heap allocation, avoid complex

formatting, avoid waiting for locks that might already be held, and avoid doing large amounts of work while the CPU is inside interrupt context. The handler should capture the event, acknowledge the controller, and defer larger processing when possible. For a keyboard, that means reading the scancode and placing it into a fixed-size buffer. For a timer, that means incrementing a tick counter and returning. A kernel that does too much inside interrupt handlers becomes fragile quickly.

9.1: Configuring the Programmable Interrupt Controller

Section titled “9.1: Configuring the Programmable Interrupt Controller”

The Programmable Interrupt Controller is the legacy hardware component that routes external interrupt requests to the CPU. On classic PC-compatible systems, there are two 8259 PICs arranged as a master and a slave. The master handles IRQ lines 0 through 7, and the slave handles IRQ lines 8 through 15. The slave is connected through one of the master’s lines, so the two controllers behave as a chained system. In early kernel development, the two most useful lines are IRQ0 for the timer and IRQ1 for the keyboard.

The CPU does not see IRQ numbers directly. It receives interrupt vectors. A vector is an index into the Interrupt Descriptor Table. CPU exceptions already use the low vectors, especially the range from 0 through 31. If the PIC is left at its old default mapping, hardware IRQs can conflict with CPU exception vectors. That is dangerous because the kernel could receive a timer interrupt and interpret it as a CPU exception, or vice versa. The PIC should be remapped so hardware interrupts use vectors that do not overlap the CPU-defined exception range.

A common early layout maps the master PIC to start at vector 32 and the slave PIC to start at vector 40. That means IRQ0 becomes vector 32, IRQ1 becomes vector 33, and so on. This keeps CPU exceptions and hardware interrupts separate. The exact vector range can be changed later, but using 32 through 47 is a practical starting point.

The kernel should encode these interrupt indexes clearly. The timer and keyboard handlers should not be scattered around as bare numbers.

#[derive(Debug, Clone, Copy)]
#[repr(u8)]
pub enum InterruptIndex {
Timer = 32,
Keyboard = 33,
}
impl InterruptIndex {
pub fn as_u8(self) -> u8 {
self as u8
}
pub fn as_usize(self) -> usize {
usize::from(self.as_u8())
}
}

This enum gives names to the vectors used by hardware interrupt handlers. The repr(u8) annotation makes the representation explicit. The Timer entry corresponds to vector 32, and Keyboard corresponds to vector 33. Naming these values prevents confusion between IRQ numbers and IDT vector numbers. IRQ0 is not vector 0 after remapping. It is vector 32 in this layout.

The IDT must include entries for these vectors before hardware interrupts are enabled. If the timer fires and the IDT does not have a valid handler for vector 32, the CPU may fault while trying to handle the interrupt. If that fault path also fails, the system can reset. Install the handlers first, initialize the PIC, and only then enable CPU interrupts.

use lazy_static::lazy_static;
use x86_64::structures::idt::{InterruptDescriptorTable, InterruptStackFrame};
lazy_static! {
static ref IDT: InterruptDescriptorTable = {
let mut idt = InterruptDescriptorTable::new();
idt.breakpoint.set_handler_fn(breakpoint_handler);
idt.page_fault.set_handler_fn(page_fault_handler);
};
}
idt[InterruptIndex::Timer.as_usize()].set_handler_fn(timer_interrupt_handler);
idt[InterruptIndex::Keyboard.as_usize()].set_handler_fn(keyboard_interrupt_handler);
idt
};
pub fn init_idt() {
IDT.load();
}
extern "x86-interrupt" fn breakpoint_handler(stack_frame: InterruptStackFrame) {
serial_println!("breakpoint exception");
serial_println!("{:#?}", stack_frame);
}
extern "x86-interrupt" fn page_fault_handler(
stack_frame: InterruptStackFrame,
error_code: x86_64::structures::idt::PageFaultErrorCode,
) {
let address = x86_64::registers::control::Cr2::read();
serial_println!("page fault at {:?}", address);
serial_println!("error code: {:?}", error_code);
serial_println!("stack frame: {:?}", stack_frame);
crate::arch::halt_loop();
}
extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) {
serial_println!("timer interrupt");
}
extern "x86-interrupt" fn
keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) {
serial_println!("keyboard interrupt");
}

This first version installs handlers, but it is not complete. The timer and keyboard handlers print messages, but they do not acknowledge the PIC. A hardware interrupt must be acknowledged after it is handled. With the legacy PIC, this is done by sending an end-of-interrupt command to the

appropriate controller. If the kernel does not send EOI, the PIC may not deliver further interrupts on that line. The result can be confusing because the first interrupt may appear to work, then later interrupts stop.

A common way to configure the PIC in Rust is to wrap the chained controllers in a lock. The PIC itself is a global hardware resource. The kernel should not have multiple independent mutable controllers for the same ports. A static lock-protected object gives one controlled access point.

Rust

e pic8259::ChainedPics;
e spin::Mutex;
const PIC_1_OFFSET: u8 = 32;
const PIC_2_OFFSET: u8 = PIC_1_OFFSET + 8;
pub static PICS: Mutex<ChainedPics> = Mutex::new(unsafe {
ChainedPics::new(PIC_1_OFFSET, PIC_2_OFFSET)
});
pub fn init_pics() {
unsafe {
PICS.lock().initialize();
}
serial_println!("programmable interrupt controller initialized");
}

The initialization is unsafe because it writes to hardware I/O ports and changes interrupt routing behavior. The PIC offsets define where IRQs appear in the IDT after remapping. The master PIC starts at 32, and the slave PIC starts at 40. Once initialized, the timer interrupt arrives at vector 32 and the keyboard interrupt at vector 33.

The interrupt handlers should send EOI through the PIC after completing their work. For timer and keyboard, both are on the master PIC, so acknowledging the vector through the chained PIC abstraction is enough.

<!-- page: 257 -->
extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) {
serial_println!("timer interrupt");
unsafe {
crate::interrupts::PICS
.lock()
.notify_end_of_interrupt(InterruptIndex::Timer.as_u8());
}
}
extern "x86-interrupt" fn keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) {
serial_println!("keyboard interrupt");
unsafe {
crate::interrupts::PICS
.lock()
.notify_end_of_interrupt(InterruptIndex::Keyboard.as_u8());
}
}
This version acknowledges the interrupt after printing. It is still not ideal because printing inside frequent interrupt handlers quickly becomes noisy and may interact badly with locks. The timer interrupt can fire repeatedly, and printing every tick can overwhelm the serial output. The keyboard interrupt should eventually read the scancode before acknowledging. Still, this version shows the critical structure: handler runs, work is done, EOI is sent.
Initialization order matters. The GDT and TSS should already be loaded. The IDT should be loaded. The PIC should be initialized. Only then should CPU interrupts be enabled. Enabling CPU interrupts is the instruction that allows maskable hardware interrupts to arrive. Do it too early and the CPU may receive an event with no valid handler path.
Rust
pub fn init_interrupts() {
crate::gdt::init();
serial_println!("gdt and tss loaded");
}
<!-- page: 258 -->
rust
crate::interrupts::init_idt();
serial_println!("idt loaded");
crate::interrupts::init_pics();
serial_println!("pic initialized");
x86_64::instructions::interrupts::enable();
serial_println!("hardware interrupts enabled");
}

This function makes the order readable. The serial checkpoints are important. If the kernel fails after pic initialized but before hardware interrupts enabled, the problem likely occurs during the enable operation or immediately after the first interrupt arrives. If the kernel floods the terminal with timer messages, the timer interrupt is firing. If it hangs after the first timer message, the EOI path or locking may be wrong.

The PIC is legacy hardware, so keep its role in perspective. It is useful for early timer and keyboard work, especially in QEMU. It teaches routing, vector remapping, handler installation, and EOI. It is not the final answer for multiprocessor interrupt routing. Later, the kernel will need to understand local APICs, I/O APICs, ACPI tables, and per-core interrupt handling. For now, the PIC gives you a controlled way to add real hardware interrupts without taking on the full complexity of modern interrupt architecture.

9.2: Handling Timer Interrupts and Kernel Ticks

Section titled “9.2: Handling Timer Interrupts and Kernel Ticks”

The timer interrupt is the first repeating hardware event a kernel usually handles. It gives the kernel a periodic signal from the hardware, which can be used to track time, drive scheduling, update counters, or wake sleeping tasks later. At this stage, the timer should be kept simple. The handler should increment a tick counter, acknowledge the interrupt controller, and return. That is enough to prove that the kernel can receive recurring hardware interrupts.

The timer interrupt commonly arrives through IRQ0, which is mapped to vector 32 after PIC remapping. The IDT entry for the timer should already be installed before interrupts are enabled. The handler must use the extern

“x86-interrupt” calling convention because the CPU enters it through the IDT, not through an ordinary function call.

A first timer handler can increment a global atomic counter. An atomic counter is useful because interrupt handlers can run asynchronously relative to normal code. A plain mutable static would require unsafe access and would be easy to misuse. An atomic integer gives safe operations for simple counter updates.

Rust

use core::sync::atomic::{AtomicU64, Ordering};
use x86_64::structures::idt::InterruptStackFrame;
static TIMER_TICKS: AtomicU64 = AtomicU64::new(0);
pub fn ticks() -> u64 {
TIMER_TICKS.load(Ordering::Relaxed)
}
extern "x86-interrupt" fn timer_interrupt_handler(_stack_frame: InterruptStackFrame) {
TIMER_TICKS.fetch_add(1, Ordering::Relaxed);
unsafe {
crate::interrupts::PICS
.lock()
.notify_end_of_interrupt(crate::interrupts::InterruptIndex::Timer.as_u8());
}
}

The relaxed ordering is enough for a simple tick counter where the only requirement is atomicity of the increment and read. The counter is not being used here to synchronize access to other memory. If timer ticks later become part of scheduling or wake-up logic, the memory-ordering requirements may change. For now, Relaxed keeps the intent clear: this is a counter, not a lock.

This handler does not print every tick. That is intentional. Timer interrupts can fire frequently. Printing from each one is slow and can cause reentrancy or lock problems. It also makes the serial output hard to use. If you need

proof that ticks are arriving, print from normal code by periodically reading the counter, or print only every certain number of ticks.

pub fn print_timer_status() {
let current = ticks();
serial_println!("timer ticks: {}", current);
}

This function can be called from a shell command, a test loop, or a controlled diagnostic path. It keeps the interrupt handler short and moves output into normal kernel context.

A timer interrupt is not the same as accurate timekeeping. The early tick counter counts interrupts, not real time in a trustworthy sense. To convert ticks into seconds, the kernel must know the timer frequency. With legacy PIT configuration, the frequency depends on how the PIT divisor is programmed. If the boot environment or emulator leaves the timer in a default state, you may receive interrupts, but you should not assume the rate without configuring it or measuring it. For early kernel work, a monotonically increasing tick count is enough.

The Programmable Interval Timer can be programmed through I/O ports. The classic PIT input frequency is divided by a 16-bit divisor to produce periodic interrupts on IRQ0. A simple configuration can set the PIT to periodic square-wave mode and select a divisor for an approximate frequency. This is hardware programming and should be isolated behind a timer module.

use x86_64::instructions::port::Port;
const PIT_COMMAND_PORT: u16 = 0x43;
const PIT_CHANNEL_0_PORT: u16 = 0x40;
const PIT_BASE_FREQUENCY: u32 = 1_193_182;
pub fn configure_pit(frequency_hz: u32) {
let divisor = PIT_BASE_FREQUENCY / frequency_hz;

assert!(divisor > 0 && divisor <= u16::MAX as u32);

let divisor = divisor as u16; let low = (divisor & 0xff) as u8; let high = (divisor >> 8) as u8;

unsafe { let mut command: Port = Port::new(PIT_COMMAND_PORT); let mut channel_0: Port = Port::new(PIT_CHANNEL_0_PORT);

command.write(0x36);
channel_0.write(low);
channel_0.write(high);

}

This function writes to the PIT command and channel ports. The command byte selects channel 0, low-byte then high-byte access, and a periodic operating mode. The divisor controls the approximate rate. This is unsafe at the port level because the kernel is directly programming hardware. The function itself is safe to call only if the platform provides this PIT compatible behavior and the PIC timer line is routed as expected. In a teaching kernel under QEMU, this is a reasonable early path.

The initialization function can configure the timer before enabling interrupts. The IDT and PIC should already be ready.

Rust

pub fn init_timer() { configure_pit(100); serial_println!(“timer configured”); }

A 100 Hz timer gives one tick every 10 milliseconds in the intended configuration. This is a useful early rate because it is frequent enough to show progress but not so frequent that it overwhelms the kernel. The exact rate does not need to be perfect at this stage. Later timekeeping should use more precise hardware and calibration.

The timer handler should also be careful with lock usage. If it tries to acquire a lock already held by interrupted code, it can deadlock. This is why the

handler shown earlier only increments an atomic and acknowledges the PIC. Atomic increments are short, do not allocate, and do not require a heap lock. The EOI path locks the PIC object, but this is a small critical section. Avoid printing from inside the timer handler because printing often uses locks around serial or console writers.

If you want periodic diagnostic output, use a separate function called from the main loop. The main loop can read the tick count and print when it changes by a chosen amount.

pub fn run_timer_demo() -> ! {
let mut last_printed = 0;
loop {
let current = ticks();
if current >= last_printed + 100 {
last_printed = current;
serial_println!("timer ticks: {}", current);
}
x86_64::instructions::hlt();
}
}

This loop prints once every 100 ticks, which is about once per second if the timer is configured to 100 Hz. The hlt instruction lets the CPU wait for the next interrupt instead of spinning continuously. When a timer interrupt arrives, the CPU wakes, the handler increments the counter and acknowledges the PIC, then the loop continues and checks whether it is time to print.

This pattern is useful because it separates interrupt-time work from normal-time work. The interrupt handler records the event. The main loop reports it. Later, a scheduler can use the timer interrupt to switch tasks or update sleep queues, but the same principle remains: do the minimum in the handler and defer larger work.

The tick counter should not be mistaken for a complete clock. It can overflow eventually, though a 64-bit counter at common tick rates lasts a very long time. It can drift if the timer frequency is not exact. It may pause when interrupts are disabled. It may not correspond to wall-clock time. None of that prevents it from being useful for early kernel development. It gives you a heartbeat. If ticks increase, hardware interrupts are being delivered, the IDT timer entry works, the PIC is acknowledged, and CPU interrupts are enabled.

9.3: Reading Keyboard Scancodes and Building an Input Buffer

Section titled “9.3: Reading Keyboard Scancodes and Building an Input Buffer”

Keyboard input begins with scancodes, not characters. When a key is pressed or released, the keyboard controller reports one or more bytes. These bytes describe key events at a lower level than text. The same key can produce a press code and a release code. Some keys use multi-byte sequences. Modifier keys such as Shift and Control affect how later scancodes should be interpreted. Turning scancodes into characters is separate step from reading them.

On a basic PC-compatible setup, keyboard data can be read from I/O port 0x60. The keyboard interrupt arrives on IRQ1, which is vector 33 after the PIC is remapped to start at vector 32. The handler must read the scancode, store it somewhere, send EOI to the PIC, and return. It should not run a full shell parser or perform complex text processing inside interrupt context. A fixed-size input buffer is the right early design.

The simplest keyboard handler reads one byte and prints it. This confirms that the interrupt fires and that the data port can be read.

use x86_64::instructions::port::Port;
use x86_64::structures::idt::InterruptStackFrame;
extern "x86-interrupt" fn
keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) {
let mut port = Port::<u8>::new(0x60);
let scancode: u8 = unsafe {
port.read()
};
serial_println!("keyboard scancode: {:#x}", scancode);
unsafe {
crate::interrupts::PICS
.lock()
.notify_end_of_interrupt(crate::interrupts::InterruptIndex::Keyboard.as_u8());
}

This is useful for a first test, but it is not a good final handler. Printing inside the handler is slow and can interact badly with locks. It also turns every key event into serial noise. The better design is to place scancodes into a small buffer and process them later outside interrupt context.

A fixed-size ring buffer is well suited for early keyboard input. It does not allocate. It can store a bounded number of scancodes. It has clear behavior when full. For a simple single-core kernel, a lock-protected ring buffer is enough. The keyboard interrupt handler pushes scancodes into it, and normal code pops scancodes out for decoding.

pub struct ScancodeBuffer {
data: [u8; 256],
read_index: usize,
write_index: usize,
full: bool,
}
impl ScancodeBuffer {
pub const fn new() -> Self {
Self {
data: [0; 256],
read_index: 0,
write_index: 0,
full: false,
}
}
pub fn push(&mut self, value: u8) -> Result<(), ()> {
if self.full {
return Err(());
}
self.data[self.write_index] = value;
self.write_index = (self.write_index + 1) % self.data.len();
if self.write_index == self.read_index {
self.full = true;
}
Ok(())
}
pub fn pop(&mut self) -> Option<u8> {
if !self.full && self.read_index == self.write_index {
return None;
}
let value = self.data[self.read_index];
self.read_index = (self.read_index + 1) % self.data.len();
self.full = false;
Some(value)
}

This buffer stores raw bytes. It does not decode keys. That separation is important. Interrupt-time code should record the hardware event. Normal kernel code can later translate scancodes into characters, handle modifiers, and feed a shell or input subsystem. Keeping the buffer raw also makes debugging easier because you can print the scancodes later if decoding behaves incorrectly.

The buffer can be placed behind an interrupt-safe lock. Since the keyboard interrupt handler and normal code may both access it, access must be synchronized. On a single-core early kernel, disabling interrupts while holding the lock prevents an interrupt from trying to acquire the same lock while normal code already holds it.

Rust

use spin::Mutex;

use x86_64::instructions::interrupts;

static SCANCODE_BUFFER: Mutex = Mutex::new(ScancodeBuffer::new());

pub fn push_scancode(scancode: u8) { interrupts::without_interrupts(|| { let _ = SCANCODE_BUFFER.lock().push(scancode); }); }

pub fn pop_scancode() -> Option { interrupts::without_interrupts(|| { SCANCODE_BUFFER.lock().pop() }) }

This code drops scancodes when the buffer is full by ignoring the error from push. For a first kernel, that behavior is acceptable because it avoids blocking inside the interrupt handler. Later, the kernel can count dropped scancodes, increase the buffer size, or wake a task when input arrives. The important point is that the interrupt handler must not wait for buffer space.

The keyboard interrupt handler can now read the scancode and push it into the buffer. It should acknowledge the PIC afterward.

extern "x86-interrupt" fn
keyboard_interrupt_handler(_stack_frame: InterruptStackFrame) {
let mut port = Port::<u8>::new(0x60);
let scancode: u8 = unsafe {
port.read()
};
crate::keyboard::push_scancode(scancode);
unsafe {
crate::interrupts::PICS
.lock()
.notify_end_of_interrupt(crate::interrupts::InterruptIndex::Keyboard.as_u8());
}
}

This handler is short. It reads from the device, stores the byte, acknowledges the interrupt, and returns. It does not allocate. It does not parse commands. It does not print. This is the shape you want for early interrupt-driven input.

Processing scancodes can happen in the main loop or a shell input routine. A first decoder can handle only a small subset of scancodes, such as letters and Enter. That is enough to prove the buffer design. A complete keyboard decoder is more involved because it must handle release events, Shift, Caps Lock, extended scancodes, and keyboard layouts.

Rust

pub fn scancode_to_ascii(scancode: u8) -> Option<u8> {
match scancode {
0x02 => Some(b'1'),
0x03 => Some(b'2'),
0x04 => Some(b'3'),
0x05 => Some(b'4'),
0x06 => Some(b'5'),
0x07 => Some(b'6'),
0x08 => Some(b'7'),
0x09 => Some(b'8'),
0x0a => Some(b'9'),
0x0b => Some(b'0'),
0x10 => Some(b'q'),
0x11 => Some(b'w'),
0x12 => Some(b'e'),
0x13 => Some(b'r'),
0x14 => Some(b't'),
0x15 => Some(b'y'),
0x16 => Some(b'u'),
0x17 => Some(b'i'),
0x18 => Some(b'o'),
0x19 => Some(b'p'),
0x1c => Some(b'\n'),
0x39 => Some(b' '),
_ => None,
}
}

This decoder is intentionally limited. It handles selected press scancodes only and ignores release scancodes. That is enough for early testing, but it is not a real keyboard layout implementation. Release scancodes commonly

have the high bit set for simple set 1 codes, so a complete decoder would track key-up events and modifier state.

A processing function can drain the buffer and print decoded characters.

Rust

pub fn process_keyboard_input() {
while let Some(scancode) = pop_scancode() {
if let Some(byte) = scancode_to_ascii(scancode) {
match byte {
b'\n' => {
serial_println!();
screen_println!();
}
byte => {
serial_print!("{}", byte as char);
screen_print!("{}", byte as char);
}
}
}
}
}

This code belongs outside the interrupt handler. It can be called from the main loop. It drains pending scancodes, decodes the ones it understands, and prints characters to serial and screen. Later, this same path can feed a command-line buffer rather than printing immediately.

A main loop can combine hlt with input processing. One common pattern is to process any pending input, then halt until the next interrupt wakes the CPU. When a keyboard interrupt arrives, the handler pushes a scancode and returns. The CPU then resumes the loop, which processes the buffered input.

Rust

pub fn kernel_loop() -> ! {
loop {
crate::keyboard::process_keyboard_input();
x86_64::instructions::hlt();
}
}

This loop is simple and efficient for an early kernel. It avoids busy-waiting while still responding to input. The timer interrupt will also wake the CPU, so the loop may run even when no keyboard input is pending. That is fine. The processing function returns quickly when the buffer is empty.

The input buffer gives the kernel a clean boundary between hardware events and text processing. The interrupt handler handles hardware. The buffer stores raw events. The processing code turns events into characters. The shell can later turn characters into commands. This layered design prevents the keyboard interrupt handler from becoming a command interpreter, which would be fragile and hard to debug.

9.4: Working with Port I/O, MMIO, and Volatile Access

Section titled “9.4: Working with Port I/O, MMIO, and Volatile Access”

Hardware access in a kernel happens through mechanisms that ordinary application code usually never sees. On x86_64, simple legacy devices often use port I/O. Other devices expose memory-mapped registers, where reading and writing certain physical or virtual addresses communicates with hardware. Both styles require care because the compiler and CPU cannot treat device access exactly like ordinary memory access.

Port I/O uses special CPU instructions to read from and write to I/O ports. The serial port, PIC, PIT, and keyboard controller examples all use port I/O. A port number is not a memory address. It belongs to a separate I/O space accessed through instructions such as in and out. Rust does not make these operations safe because using the wrong port, wrong width, or wrong timing can affect hardware state unpredictably.

A small port wrapper can make this access more structured. The wrapper stores a port number and provides typed read and write methods for byte-sized access.

Rust

pub struct Port8 {
port: u16,
}
impl Port8 {
pub const fn new(port: u16) -> Self {
Self { port }
}
pub unsafe fn read(&self) -> u8 {
let value: u8;
unsafe {
core::arch::asm!(
"in al, dx",
out("al") value,
in("dx") self.port,
options(nomem, nostack, preserves_flags)
);
}
value
}
pub unsafe fn write(&self, value: u8) {
unsafe {
core::arch::asm!(
"out dx, al",
in("dx") self.port,
in("al") value,
options(nomem, nostack, preserves_flags)
);
}
}
}

This type does not make port I/O safe by itself. The methods are still unsafe. The benefit is that raw assembly is isolated in one place. The serial driver, keyboard driver, PIC code, and PIT code can use the wrapper rather than each writing their own assembly blocks. This reduces duplication and makes hardware access easier to review.

A device-specific wrapper can make the public interface safer by fixing the port numbers and controlling the operations. For example, a keyboard data-port wrapper can expose a read_scancode function. The function can still be unsafe internally, but the caller no longer chooses arbitrary ports.

pub struct KeyboardController {

data_port: Port8, }

impl KeyboardController { pub const fn new() -> Self { Self { data_port: Port8::new(0x60), } }

pub fn read_scancode(&self) -> u8 {
unsafe {
self.data_port.read()
}
}

}

This function is safe only if the kernel’s hardware model guarantees that reading the data port in the keyboard interrupt handler is valid. In a stricter design, it could remain unsafe. In an early kernel, wrapping the port behind a keyboard controller type is already a step toward better structure. The rest of the kernel does not need to know the numeric port.

Memory-mapped I/O is different. A device exposes registers through memory addresses. Reading or writing those addresses communicates with the device. The address may come from firmware tables, PCI configuration, a bootloader handoff, or architecture documentation. MMIO must use volatile operations because the compiler must not remove, combine, or reorder the access as if it were ordinary memory. A device register write matters even if no Rust variable later reads the value. A device register read matters even if the same address was read before.

A basic volatile register wrapper can represent an MMIO register at a pointer.

use core::ptr;
pub struct VolatileRegister<T> {
address: *mut T,
}
<!-- page: 272 -->
rust
impl<T> VolatileRegister<T> {
pub const unsafe fn new(address: *mut T) -> Self {
Self { address }
}
pub fn read(&self) -> T
where
T: Copy,
{
unsafe {
ptr::read_volatile(self.address)
}
}
pub fn write(&self, value: T) {
unsafe {
ptr::write_volatile(self.address, value);
}
}
}

The constructor is unsafe because the caller must guarantee that the address is valid for the register type, properly aligned if required, mapped in the current page tables, and safe to access with volatile reads and writes. The read and write methods are safe here because the unsafe requirements are attached to construction. This is a common Rust pattern for hardware abstractions: make construction unsafe because it establishes the validity of the address, then make individual operations safe if the type enforces correct access rules.

This design should be used carefully. Not every register can be read safely. Some registers are write-only. Some have side effects on read. Some require specific access widths. Some must be modified with read-modify-write sequences. A more precise abstraction should create separate types for read-only, write-only, and read-write registers. That prevents code from reading a register that should never be read or writing one that should be read-only.

use core::ptr;
pub struct ReadOnlyRegister<T> {

address: *const T,

pub struct WriteOnlyRegister { address: *mut T, }

pub struct ReadWriteRegister { address: *mut T, }

impl ReadOnlyRegister { pub const unsafe fn new(address: *const T) -> Self { Self { address } }

pub fn read(&self) -> T
where
T: Copy,
{
unsafe {
ptr::read_volatile(self.address)
}
}

}

impl WriteOnlyRegister { pub const unsafe fn new(address: *mut T) -> Self { Self { address } }

pub fn write(&self, value: T) {
unsafe {
ptr::write_volatile(self.address, value);
}
}

}

impl ReadWriteRegister { pub const unsafe fn new(address: *mut T) -> Self { Self { address } }

pub fn read(&self) -> T
where
T: Copy,
{
unsafe {
ptr::read_volatile(self.address)
}
}

}

pub fn write(&self, value: T) { unsafe { ptr::write_volatile(self.address, value); } }

This version encodes register access policy in the type system. If a device register is write-only, code using a WriteOnlyRegister cannot accidentally call read. If a register is read-only, it cannot accidentally be written through that wrapper. The underlying access is still volatile and still depends on a valid MMIO address, but the public interface prevents some categories of misuse.

The framebuffer is a familiar MMIO-like example in early kernel work. It is a memory region where writing bytes changes pixels on screen. The kernel should not write to it through ordinary memory operations because the compiler may optimize ordinary stores in ways that do not match device expectations. The framebuffer writer should use volatile writes and respect stride, pixel format, and bounds.

Rust

use core::ptr;

pub enum PixelFormat { Rgb, Bgr, }

pub struct Framebuffer { address: *mut u8, width: usize, height: usize, stride: usize, bytes_per_pixel: usize, pixel_format: PixelFormat, }

impl Framebuffer { pub unsafe fn new( address: *mut u8,

width: usize, height: usize, stride: usize, bytes_per_pixel: usize, pixel_format: PixelFormat, ) -> Self { Self { address, width, height, stride, bytes_per_pixel, pixel_format, } }

pub fn write_pixel(&mut self, x: usize, y: usize, red: u8, green: u8, blue: u8) { if x >= self.width || y >= self.height { return; }

if self.bytes_per_pixel < 3 { return; }

let offset = y * self.stride + x * self.bytes_per_pixel;

unsafe { match self.pixel_format { PixelFormat::Rgb => { ptr::write_volatile(self.address.add(offset), red); ptr::write_volatile(self.address.add(offset + 1), green); ptr::write_volatile(self.address.add(offset + 2), blue); } PixelFormat::Bgr => { ptr::write_volatile(self.address.add(offset), blue); ptr::write_volatile(self.address.add(offset + 1), green); ptr::write_volatile(self.address.add(offset + 2), red); } } } }

The constructor is unsafe because it trusts the framebuffer address and metadata. The write_pixel method checks bounds and pixel size before writing. That does not make the framebuffer universally safe, but it prevents common mistakes such as writing outside the visible region or assuming the wrong pixel size. The volatile writes are contained inside the driver.

Port I/O and MMIO should be surrounded by clear ownership rules. A port should have one logical driver. A device’s register block should not be accessed through unrelated raw pointers in multiple modules. If two parts of the kernel write to the same device without coordination, the hardware state can become inconsistent. Rust’s ownership model is helpful when you design wrappers that represent device ownership. It is less helpful if every module can cast integers to pointers and write anywhere.

A simple device wrapper can own its ports and provide a focused interface. The serial device is a good example.

pub struct SerialPort {
data: Port8,
interrupt_enable: Port8,
line_control: Port8,
fifo_control: Port8,
modem_control: Port8,
}
impl SerialPort {
pub const fn new(base: u16) -> Self {
Self {
data: Port8::new(base),
interrupt_enable: Port8::new(base + 1),
line_control: Port8::new(base + 3),
fifo_control: Port8::new(base + 2),
modem_control: Port8::new(base + 4),
}
}
pub fn init(&self) {
unsafe {
self.interrupt_enable.write(0x00);
self.line_control.write(0x80);
self.data.write(0x03);
self.interrupt_enable.write(0x00);
}
}
}
self.line_control.write(0x03);
self.fifo_control.write(0xc7);
self.modem_control.write(0x0b);
}
pub fn write_byte(&self, byte: u8) {
unsafe {
self.data.write(byte);
}
}

This wrapper does not expose arbitrary port writes. It gives serial-specific operations. That makes the rest of the kernel cleaner and reduces the risk of writing to the wrong serial register. It also gives one place to improve the driver later, such as checking line status before writing bytes.

Volatile access should not be overused for ordinary memory. It is for operations that must happen exactly as memory operations because of external observation, such as device registers or diagnostic probes. It is not a replacement for atomics, locks, or correct aliasing. If two CPU contexts share ordinary memory, use synchronization. If a value is modified by an interrupt handler and read by normal code, use atomics or locks. If a memory location is a hardware register, use volatile access. Each tool solves a different problem.

Atomics communicate between CPU contexts. Volatile communicates with memory-mapped side effects. Locks protect structured shared state. Unsafe raw pointers access memory outside Rust’s usual guarantees. Confusing these tools leads to weak designs. For example, reading a tick counter with volatile access would not provide the same synchronization semantics as an atomic. Writing an MMIO register with an atomic would not necessarily express the required device access semantics. Use the right mechanism for the reason you need it.

Hardware access also needs mapping policy. MMIO addresses must be mapped into virtual memory before the kernel can use them as pointers. The mapping flags may need to disable ordinary caching or use device-appropriate caching behavior, depending on the hardware and paging

support. Treating device registers as cached normal memory can produce incorrect behavior because the CPU may combine, delay, or reorder accesses in ways the device does not expect. Early kernel examples may run under QEMU with forgiving behavior, but the design should not assume all hardware behaves like ordinary RAM.

The practical rule is to isolate every hardware boundary. Port I/O belongs in port wrappers and drivers. MMIO belongs in register wrappers and device abstractions. Volatile access belongs at the exact point where device memory is read or written. Interrupt handlers should do little work and pass data into buffers or counters. Shared state touched by interrupts should use atomics or interrupt-safe locks. The result is a kernel that can talk to hardware without letting hardware-specific danger leak into every module.

By the end of this stage, the kernel can receive hardware interrupts, count timer ticks, read keyboard scancodes, and interact with simple hardware through port I/O and volatile memory access. This is a major shift in capability. The kernel is no longer only proving that it can boot and manage memory. It is responding to devices. The next challenge is to organize those capabilities into kernel services, tests, and a debugging workflow that can support larger features without losing control.