The Complete Guide to Interrupts, Memory and Paging for OS Developers
A complete x86-64 kernel core: GDT, IDT, exceptions, PIC and APIC interrupts, timers, a frame allocator, four-level paging, page faults, a heap and PCI.

A kernel that boots and prints text is a program. A kernel that handles interrupts, owns its memory and controls the page tables is an operating system, because those three things are the whole job of the hardware-facing half of one. Interrupts are how the machine tells the kernel that something happened: a key was pressed, a timer expired, a program divided by zero. Memory management is how the kernel decides who may use which bytes of RAM. Paging is the mechanism the CPU gives it to enforce that decision on every single access. Everything above them, processes, system calls, file systems, drivers, is built from these. This guide takes the x86-64 core of that in the order a working kernel needs it: the descriptor tables, the interrupt machinery for exceptions and hardware interrupts, the timers and the keyboard, a physical memory manager, the four-level page tables, page fault handling, a kernel heap and a first look at PCI. Every section carries code for a freestanding kernel in C and assembly, and every section points to the post that treats its topic at full length.
The guide assumes a 64-bit kernel booted by a loader that leaves you in long mode, as in the post on booting with the Limine protocol, or one you entered yourself, as in entering 64-bit long mode. It uses GCC 15 with the flags from why kernels need these compiler flags, and QEMU 9 for running. If you are starting from nothing, begin with the guide to writing a hobby operating system and return here when you can print from a 64-bit kmain.
The order of work, and why
These pieces depend on each other in a particular way, and the dependencies decide the order.
The interrupt table has to exist before anything can go wrong safely, because any exception without a handler ends in a triple fault and a reset. The table in turn needs a code selector, which means your own GDT. So the descriptor tables come first. Hardware interrupts cannot be enabled until the controller is programmed and the handlers installed, so the interrupt controller and the timer come next. Memory management has to precede paging, because page tables are made of memory that someone must allocate, and a paging system needs the page fault handler from the first section to exist or its mistakes become silent resets. The heap sits on top of both. PCI enumeration touches none of these directly, but it needs a place to put its results and, later, memory-mapped device registers that need paging control.
So the working order is: GDT, IDT and exceptions, interrupt controller, timer, physical memory, paging, page faults, heap, devices. A project that builds them in this order can test each with printed output before relying on it.
The descriptor tables in long mode
The GDT
In 64-bit mode, segmentation is nearly disabled: the bases and limits of the code and data segments are ignored. But the CPU still reads the segment registers and the descriptor table for the privilege level in CS, for the L bit that selects 64-bit code, and for the task state segment. The post on segmentation versus paging explains why this is the right division, and the post on setting up a GDT shows the 32-bit layout in detail.
A minimal 64-bit table has a null descriptor, kernel code, kernel data, user data, user code and a 16-byte TSS descriptor. User data comes before user code, in this order, because the syscall and sysret instructions derive both user selectors from one base value in the STAR register with fixed offsets. As raw quadwords:
static uint64_t gdt[] = {
0x0000000000000000, /* 0x00 null */
0x00AF9A000000FFFF, /* 0x08 kernel code: L=1, DPL 0 */
0x00CF92000000FFFF, /* 0x10 kernel data */
0x00CFF2000000FFFF, /* 0x18 user data, DPL 3 */
0x00AFFA000000FFFF, /* 0x20 user code, L=1, DPL 3 */
0, 0, /* 0x28 TSS descriptor, 16 bytes, filled at run time */
};The access byte 0x9A makes a present, ring 0, executable, readable code segment, and 0xFA is the same at ring 3; the flags nibble 0xA in the code entries sets granularity and the L bit and leaves DB clear, which is the combination that means 64-bit code. Loading the table needs a ten-byte pointer and a far return to reload CS:
.global gdt_load
gdt_load: /* rdi = pointer to {u16 limit; u64 base} */
lgdt (%rdi)
mov $0x10, %ax
mov %ax, %ds
mov %ax, %es
mov %ax, %ss
xor %ax, %ax
mov %ax, %fs
mov %ax, %gs
pop %rax /* return address */
push $0x08 /* new CS */
push %rax /* new RIP */
lretqThe trick at the end builds a far-return frame: pop the return address, push the code selector and then the address, and lretq pops both, loading CS and jumping to the caller's continuation. There is no 64-bit ljmp with an immediate, so this is the usual idiom.
The TSS and the Interrupt Stack Table
The 64-bit task state segment has nothing to do with hardware task switching, which does not exist in long mode. It holds three stack pointers for privilege transitions, rsp0 to rsp2, seven alternate stack pointers called the Interrupt Stack Table, ist1 to ist7, and an I/O permission bitmap offset. rsp0 is the stack the CPU switches to when an interrupt or system call arrives from user mode. An IDT gate can select an ist entry, and when it does, the CPU switches to that stack unconditionally on entry. That is what makes a double fault survivable: if the fault was caused by a bad kernel stack, a handler running on the same stack would fault again, so the double fault handler gets its own. The post on setting up the TSS and Interrupt Stack Table builds it, and the key steps are allocating a stack, storing its top in ist1, writing the TSS descriptor into the GDT and executing ltr.
Interrupts and exceptions
What the CPU does
An interrupt is an event that makes the CPU stop what it is doing, save a little state and run a handler. There are three sources. Exceptions come from the CPU itself when an instruction cannot complete: vector 0 is a divide error, 6 an invalid opcode, 8 a double fault, 13 a general protection fault, 14 a page fault. Hardware interrupts come from devices through an interrupt controller. Software interrupts come from the int n instruction. All are identified by a vector from 0 to 255 that indexes the Interrupt Descriptor Table.
In 64-bit mode the CPU's entry sequence is uniform. It aligns the stack pointer to 16 bytes, then pushes SS, RSP, RFLAGS, CS and RIP, in that order, whether or not the privilege level changed. For the exceptions that define one, it pushes an error code last. Then it loads CS:RIP from the gate and starts running. Your handler returns with iretq, which pops the same five values.
The 64-bit gate
An IDT entry is 16 bytes. The handler address is split into three pieces, there is a code selector, a 3-bit field selecting an IST stack and a type and attribute byte.
struct idt_entry {
uint16_t offset_low;
uint16_t selector;
uint8_t ist; /* bits 0-2: IST index, 0 = do not switch */
uint8_t type_attr; /* 0x8E: present, DPL 0, 64-bit interrupt gate */
uint16_t offset_mid;
uint32_t offset_high;
uint32_t zero;
} __attribute__((packed));
struct idt_ptr {
uint16_t limit;
uint64_t base;
} __attribute__((packed));
static struct idt_entry idt[256];
static void idt_set(int vec, void *handler, uint8_t ist)
{
uint64_t a = (uint64_t)handler;
idt[vec].offset_low = a & 0xFFFF;
idt[vec].selector = 0x08;
idt[vec].ist = ist;
idt[vec].type_attr = 0x8E;
idt[vec].offset_mid = (a >> 16) & 0xFFFF;
idt[vec].offset_high = (uint32_t)(a >> 32);
idt[vec].zero = 0;
}The 0x8E byte makes an interrupt gate, which clears IF on entry so the handler is not interrupted by maskable interrupts. A trap gate, 0x8F, leaves IF alone and is used for system calls and breakpoints that should not mask interrupts. The 32-bit version of this table and the first test of it are in the post on setting up an IDT and exception handlers, which is the foundation for the code below.
Stubs and the common handler
Exceptions 8, 10 to 14, 17, 21, 29 and 30 push an error code, and the others do not. The usual remedy is a stub per vector that pushes a dummy zero where the CPU did not, then pushes the vector number, so the stack layout is identical for the common routine. In 64-bit mode there is no pushad, so the common routine saves each register:
.macro ISR_NOERR n
.global isr\n
isr\n:
pushq $0
pushq $\n
jmp isr_common
.endm
.macro ISR_ERR n
.global isr\n
isr\n:
pushq $\n
jmp isr_common
.endm
isr_common:
push %rax
push %rbx
push %rcx
push %rdx
push %rsi
push %rdi
push %rbp
push %r8
push %r9
push %r10
push %r11
push %r12
push %r13
push %r14
push %r15
mov %rsp, %rdi /* first argument: pointer to saved registers */
call interrupt_handler
pop %r15
pop %r14
pop %r13
pop %r12
pop %r11
pop %r10
pop %r9
pop %r8
pop %rbp
pop %rdi
pop %rsi
pop %rdx
pop %rcx
pop %rbx
pop %rax
add $16, %rsp /* drop vector and error code */
iretqThe stack arithmetic matters. After the CPU's five-word frame, an optional error code and the stub's pushes, the common routine pushes fifteen registers. The sequence leaves the stack 16-byte aligned at the call, which the System V ABI requires for compiled code to be safe, because the CPU aligned the stack on entry and the number of pushed words works out to an even count including the dummy. If you add or remove a push, check the alignment, since a misaligned stack causes faults in code that uses aligned vector instructions, which a kernel built with -mno-sse does not emit, but any library code might.
The C side mirrors the layout, with the last-pushed register first in memory:
struct interrupt_frame {
uint64_t r15, r14, r13, r12, r11, r10, r9, r8;
uint64_t rbp, rdi, rsi, rdx, rcx, rbx, rax;
uint64_t vector, error_code;
uint64_t rip, cs, rflags, rsp, ss;
};
void interrupt_handler(struct interrupt_frame *f)
{
if (f->vector < 32) {
exception(f); /* print state and halt, or recover */
} else {
irq_dispatch(f);
}
}A divide-by-zero test, volatile int z = 0; volatile int r = 1 / z;, should print the vector, the faulting rip and the error code, and halt. If the machine resets instead, run QEMU with -d int,cpu_reset -no-reboot, as described in the post on debugging with QEMU and gdb, and read the log.
Hardware interrupts
The legacy PIC
A classic PC routes device interrupts through a pair of 8259 Programmable Interrupt Controllers. The firmware maps their lines to vectors 8 to 15, which collide with the exception range, so a kernel remaps them to vectors 32 and above before enabling interrupts. The remap is a four-word initialization sequence sent to the command and data ports of each chip, at 0x20 and 0x21 for the master and 0xA0 and 0xA1 for the slave:
#define PIC1_CMD 0x20
#define PIC1_DATA 0x21
#define PIC2_CMD 0xA0
#define PIC2_DATA 0xA1
void pic_remap(void)
{
outb(PIC1_CMD, 0x11); outb(PIC2_CMD, 0x11); /* ICW1: init, expect ICW4 */
outb(PIC1_DATA, 0x20); outb(PIC2_DATA, 0x28); /* ICW2: vector offsets 32, 40 */
outb(PIC1_DATA, 0x04); outb(PIC2_DATA, 0x02); /* ICW3: slave on IRQ2 */
outb(PIC1_DATA, 0x01); outb(PIC2_DATA, 0x01); /* ICW4: 8086 mode */
outb(PIC1_DATA, 0xFF); outb(PIC2_DATA, 0xFF); /* mask every line for now */
}After the remap, IRQ 0 is vector 32, IRQ 1 is vector 33 and so on. A handler must tell the controller it is finished by writing 0x20 to the command port of the master, and also to the slave's for IRQs 8 to 15, or no further interrupt on that chip is delivered. The post on remapping the 8259 PIC covers masking, spurious interrupts and the end-of-interrupt rules in full.
The APIC
Modern systems, and every multi-core machine, use the Advanced Programmable Interrupt Controller, which has a local unit per CPU and an I/O unit that receives device lines and routes them to CPUs. A 64-bit kernel that wants more than one core, or that boots through UEFI where legacy assumptions are weaker, uses it, and disables the PIC by masking every line.
The local APIC's registers are memory-mapped at an address in the IA32_APIC_BASE model-specific register, number 0x1B, normally 0xFEE00000. It must be mapped uncached, because reads and writes of device registers must not be cached or reordered. The registers you need first are at these offsets:
| Offset | Register | Use |
|---|---|---|
0x20 | ID | This CPU's APIC ID |
0xB0 | EOI | Write 0 to acknowledge an interrupt |
0xF0 | Spurious vector | Bit 8 software-enables the APIC; low byte is the spurious vector |
0x320 | LVT timer | Vector, mode and mask for the APIC timer |
0x380 | Initial count | Timer start value |
0x390 | Current count | Timer value |
0x3E0 | Divide configuration | Timer clock divider |
Enabling it is a single write of the spurious vector register with bit 8 set and a vector such as 0xFF. External devices, the keyboard and others, then need routing through the I/O APIC, whose registers are accessed through an index and data pair at its base, normally 0xFEC00000: each redirection table entry, 64 bits, names the vector, the delivery mode and the destination CPU. The post on programming the local APIC and I/O APIC covers discovery through the ACPI MADT table and the redirection entries.
Timekeeping
A timer interrupt is the heartbeat of a kernel: it provides the tick for the clock, the sleep functions and, later, preemption. Two timers matter on a PC.
The Programmable Interval Timer has a fixed 1,193,182 Hz input clock. You program channel 0 with a 16-bit divisor, and it fires IRQ 0 at the frequency 1,193,182 divided by the divisor. For about 100 interrupts a second the divisor is 11,931:
void pit_init(uint32_t hz)
{
uint16_t divisor = (uint16_t)(1193182 / hz);
outb(0x43, 0x36); /* channel 0, lo/hi byte, mode 3 */
outb(0x40, divisor & 0xFF);
outb(0x40, divisor >> 8);
}The local APIC timer is per CPU and much faster, but its clock frequency is not specified: it derives from the bus or core crystal clock and varies by machine. The standard approach is to calibrate it against the PIT: start the APIC timer counting down from its maximum, wait a known time using the PIT, read how far it went, and compute ticks per millisecond. The post on the PIT and APIC timer walks the calibration. The tick handler increments a global counter and sends the end-of-interrupt, and everything time-related in the kernel is built from that counter.
The keyboard
The PS/2 keyboard controller delivers scancodes at I/O port 0x60, with status at port 0x64, where bit 0 means a byte is waiting. Each key press sends a make code and each release a break code, which in scancode set 1 is the make code with bit 7 set. Pressing A sends 0x1E, releasing it sends 0x9E. The handler for IRQ 1, vector 33 after the remap, reads one byte from port 0x60, looks it up in a table to get a character and passes it on:
static const char scancode_to_ascii[0x80] = {
0, 27, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', '\b',
'\t', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n',
0, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'', '`',
0, '\\', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/', 0, '*',
0, ' ',
};
void keyboard_irq(void)
{
uint8_t sc = inb(0x60);
if (sc & 0x80)
return; /* a key release */
char c = scancode_to_ascii[sc];
if (c)
console_putc(c);
}The table covers the unshifted keys of a US layout. Modifiers, shift state and the extended 0xE0 prefix need a state machine, as in the post on handling keyboard input with a PS/2 driver. USB keyboards are not PS/2, though QEMU and most firmware emulate PS/2 for them until a USB driver takes over.
Physical memory
What is free
The bootloader tells you which memory exists. With Limine it is the memory map response, with Multiboot2 a tag, and in both cases it is a list of regions with a base, a length and a type. Only the usable regions may be handed out, and even they contain things you must not give away: the kernel image, the boot information, any modules and the page tables the bootloader built if you still use them. The post on parsing the memory map handed over by the bootloader covers the traps, among them overlapping entries, unsorted lists and the first megabyte, which kernels typically leave alone.
A bitmap allocator
The physical memory manager hands out 4 KiB frames. The simplest design is a bitmap with one bit per frame, 1 meaning used. A machine with 4 GiB has 1,048,576 frames, so a 128 KiB bitmap.
#define FRAME_SIZE 4096UL
static uint8_t *bitmap; /* reached through the higher-half direct map */
static uint64_t total_frames;
static uint64_t next_hint;
static inline void frame_set(uint64_t f) { bitmap[f / 8] |= (uint8_t)(1u << (f % 8)); }
static inline void frame_clear(uint64_t f) { bitmap[f / 8] &= (uint8_t)~(1u << (f % 8)); }
static inline int frame_used(uint64_t f) { return bitmap[f / 8] & (1u << (f % 8)); }
uint64_t pmm_alloc(void)
{
for (uint64_t n = 0; n < total_frames; n++) {
uint64_t f = (next_hint + n) % total_frames;
if (!frame_used(f)) {
frame_set(f);
next_hint = f + 1;
return f * FRAME_SIZE; /* physical address */
}
}
return 0; /* out of memory; frame 0 is never free */
}
void pmm_free(uint64_t phys)
{
frame_clear(phys / FRAME_SIZE);
}Initialization works in the opposite polarity: mark every frame used, then walk the usable regions and clear each frame in them, then mark the bitmap's own frames and the kernel image used again. Frame 0 stays reserved so that a returned 0 can mean failure. The next_hint makes the common case, allocating repeatedly, a short scan instead of a scan from the start every time. The full design with the initialization and the performance trade-offs is in writing a physical memory manager with a bitmap allocator.
The allocator returns physical addresses, but the kernel runs with paging on and cannot use a physical address directly. This is what the higher-half direct map is for: the bootloader mapped all of physical memory at a fixed offset, so phys + hhdm_offset is a valid virtual address for any frame, which is how the kernel zeroes a new page or fills a page table.
Paging
The structure
On x86-64, address translation walks four levels of tables, each a 4 KiB page of 512 eight-byte entries. A 48-bit virtual address divides into four 9-bit indexes and a 12-bit page offset:
#define PML4_INDEX(v) (((v) >> 39) & 0x1FF)
#define PDPT_INDEX(v) (((v) >> 30) & 0x1FF)
#define PD_INDEX(v) (((v) >> 21) & 0x1FF)
#define PT_INDEX(v) (((v) >> 12) & 0x1FF)CR3 holds the physical address of the top table, the PML4. Each entry in the first three levels points to a table in the next level; an entry in the last level maps a 4 KiB frame. A directory entry with the page size bit set maps 2 MiB directly, and a PDPT entry with it set maps 1 GiB, which is what the bootloader uses to map memory cheaply.
An entry packs a physical address in bits 12 to 51 and flags in the low and high bits:
| Bit | Name | Meaning |
|---|---|---|
| 0 | P | Present; if clear, any access faults |
| 1 | R/W | Writable; if clear, writes fault |
| 2 | U/S | User-accessible; if clear, only supervisor code |
| 3 | PWT | Write-through caching |
| 4 | PCD | Cache disable, required for device memory |
| 5 | A | Accessed, set by the CPU |
| 6 | D | Dirty, set on write, in the last level |
| 7 | PS | Page size, 2 MiB or 1 GiB |
| 8 | G | Global, survives a CR3 switch |
| 63 | NX | No execute, needs EFER.NXE |
The permission checks apply at every level and combine, so a page is writable only if all four entries say so. Kernels use this deliberately: the upper tables are permissive and the leaf entries carry the real restrictions.
Mapping a page
The central operation is mapping a virtual page to a physical frame, allocating intermediate tables as needed:
#define PTE_P (1ULL << 0)
#define PTE_RW (1ULL << 1)
#define PTE_US (1ULL << 2)
#define PTE_PCD (1ULL << 4)
#define PTE_NX (1ULL << 63)
#define PTE_ADDR_MASK 0x000FFFFFFFFFF000ULL
static uint64_t *table_at(uint64_t phys)
{
return (uint64_t *)(phys + hhdm_offset);
}
static uint64_t *next_table(uint64_t *table, uint64_t index, int create)
{
if (!(table[index] & PTE_P)) {
if (!create)
return NULL;
uint64_t frame = pmm_alloc();
if (!frame)
return NULL;
memset(table_at(frame), 0, FRAME_SIZE);
table[index] = frame | PTE_P | PTE_RW | PTE_US;
}
return table_at(table[index] & PTE_ADDR_MASK);
}
int map_page(uint64_t *pml4, uint64_t virt, uint64_t phys, uint64_t flags)
{
uint64_t *pdpt = next_table(pml4, PML4_INDEX(virt), 1);
if (!pdpt) return -1;
uint64_t *pd = next_table(pdpt, PDPT_INDEX(virt), 1);
if (!pd) return -1;
uint64_t *pt = next_table(pd, PD_INDEX(virt), 1);
if (!pt) return -1;
pt[PT_INDEX(virt)] = (phys & PTE_ADDR_MASK) | flags | PTE_P;
asm volatile ("invlpg (%0)" : : "r"(virt) : "memory");
return 0;
}next_table returns the table one level down, allocating and zeroing a frame when the entry is not present. The upper-level entries are given RW and US so that the leaf alone decides the effective permissions; a page the kernel wants hidden from user mode simply has the user bit clear in its leaf. The final write fills the leaf entry, and invlpg flushes the CPU's cached translation for that address, which matters whenever an existing mapping changes: the TLB may hold the old translation, and a stale entry is a silent bug. Mapping a brand new page that was never present needs no flush on most CPUs, but invalidating is cheap and safe.
A call such as map_page(pml4, 0x400000, frame, PTE_RW) maps a writable, supervisor-only page at that virtual address. Unmapping clears the entry and flushes the same way. Switching address spaces writes a different PML4 address to CR3, which flushes all non-global translations. The post on implementing paging and identity mapping takes the same structure in a boot-time setting, with identity mapping for the transition.
Three mappings a kernel has
A running 64-bit kernel typically has three views of memory. The kernel image is mapped in the higher half at the address in its linker script, as in writing a linker script for a higher-half kernel. All of physical memory is mapped at the direct-map offset, so any frame is reachable. And each user process, later, has its own lower-half mappings in its own tables, sharing the upper half so the kernel is present after a system call. The identity map used during boot is removed once the kernel is running in the higher half, so that a stray low pointer faults.
Page faults
A page fault, vector 14, is the CPU's report that a translation failed or a permission was violated. Two pieces of information say which. The faulting address is in the CR2 register, and the error code the CPU pushed describes the access:
| Bit | Value 1 means | Value 0 means |
|---|---|---|
| 0 | Protection violation on a present page | Page not present |
| 1 | The access was a write | The access was a read |
| 2 | The access came from user mode | From supervisor mode |
| 3 | A reserved bit was set in a table entry | Not that |
| 4 | The access was an instruction fetch | Not that |
The handler reads both and decides:
void page_fault(struct interrupt_frame *f)
{
uint64_t addr;
asm volatile ("mov %%cr2, %0" : "=r"(addr));
uint64_t e = f->error_code;
kprintf("PAGE FAULT at 0x%lx\n", addr);
kprintf(" %s, %s, %s%s\n",
(e & 1) ? "protection violation" : "page not present",
(e & 2) ? "write" : "read",
(e & 4) ? "user mode" : "kernel mode",
(e & 16) ? ", instruction fetch" : "");
kprintf(" rip=0x%lx\n", f->rip);
halt();
}A kernel dereference of a null pointer produces, for example:
PAGE FAULT at 0x0
page not present, read, kernel mode
rip=0xffffffff80004a1cThe addresses vary with your build, but the reading is the fixed skill: CR2 is where, the error code is why, and rip is who. Look the instruction up with addr2line -e kernel.elf 0xffffffff80004a1c. A kernel that does demand paging uses the same handler to recover: if the address belongs to a region the kernel has promised, it allocates a frame, maps it and returns, and the faulting instruction runs again. The post on debugging page faults using CR2 and the error code goes through the decoding and the common causes, including the double fault that results when the handler itself faults.
The kernel heap
Frames come in 4 KiB units, and a kernel needs allocations of 16, 100 and 5,000 bytes. A heap allocator, kmalloc, turns pages into arbitrary-sized blocks. The smallest useful design keeps a linked list of free blocks, each preceded by a header with its size and a free flag, and grows by mapping more pages when no block fits:
struct block {
size_t size;
int free;
struct block *next;
};
static struct block *heap_head;
void *kmalloc(size_t n)
{
n = (n + 15) & ~15UL; /* keep 16-byte alignment */
for (struct block *b = heap_head; b; b = b->next) {
if (b->free && b->size >= n) {
if (b->size >= n + sizeof(struct block) + 16) { /* split */
struct block *rest = (struct block *)((uint8_t *)(b + 1) + n);
rest->size = b->size - n - sizeof(struct block);
rest->free = 1;
rest->next = b->next;
b->size = n;
b->next = rest;
}
b->free = 0;
return b + 1;
}
}
return NULL; /* a full version maps more pages here and retries */
}
void kfree(void *p)
{
if (p)
((struct block *)p - 1)->free = 1; /* coalescing neighbours omitted */
}The sketch shows the structure, with splitting and a free flag. A real version adds coalescing of adjacent free blocks, which keeps the list from fragmenting, growth by mapping fresh pages with map_page, and a lock once there is more than one CPU. Allocators in production kernels use size-class caches, slabs, for speed and to avoid fragmentation, and the usual path for a hobby kernel is to start with this and replace it when the profile demands. The post on writing a kernel heap allocator builds the full one.
Finding devices: PCI
Real drivers begin with discovery. Most devices on a PC sit on the PCI bus, and every device exposes a configuration space of at least 256 bytes that identifies it. The legacy access method uses two I/O ports: write a 32-bit address to 0xCF8 and read the 32-bit result from 0xCFC. The address packs an enable bit, the bus, device and function numbers and a register offset:
static uint32_t pci_read32(uint8_t bus, uint8_t dev, uint8_t fn, uint8_t off)
{
uint32_t addr = (1u << 31) | ((uint32_t)bus << 16) | ((uint32_t)dev << 11)
| ((uint32_t)fn << 8) | (off & 0xFC);
outl(0xCF8, addr);
return inl(0xCFC);
}
void pci_scan(void)
{
for (int bus = 0; bus < 256; bus++)
for (int dev = 0; dev < 32; dev++) {
uint32_t id = pci_read32(bus, dev, 0, 0);
if ((id & 0xFFFF) == 0xFFFF)
continue; /* no device here */
int nfn = (pci_read32(bus, dev, 0, 0x0C) >> 16) & 0x80 ? 8 : 1;
for (int fn = 0; fn < nfn; fn++) {
id = pci_read32(bus, dev, fn, 0);
if ((id & 0xFFFF) == 0xFFFF)
continue;
uint32_t cls = pci_read32(bus, dev, fn, 0x08);
kprintf("%02x:%02x.%x %04x:%04x class %02x%02x\n",
bus, dev, fn, id & 0xFFFF, id >> 16,
cls >> 24, (cls >> 16) & 0xFF);
}
}
}A vendor ID of 0xFFFF means the slot is empty. Bit 7 of the header type byte at offset 0x0E says the device has several functions, and the expression reads the header type from the dword at offset 0x0C. On QEMU's default machine the scan prints something like:
00:00.0 8086:1237 class 0600
00:01.0 8086:7000 class 0601
00:01.1 8086:7010 class 0101
00:01.3 8086:7113 class 0680
00:02.0 1234:1111 class 0300
00:03.0 8086:100e class 0200These are the host bridge, the ISA bridge, the IDE controller, a power management function, the standard VGA adapter and an Intel network card, and the exact set depends on the QEMU version and machine type. The class 0200 identifies the network card, and its base address registers, at offsets 0x10 to 0x24, tell the driver where its registers live. The post on enumerating PCI devices from your hobby kernel continues from here, with base address decoding and the newer memory-mapped configuration access, which is required for PCI Express extended registers.
Putting the pieces in order
The sections above are independent tools, and the order in which kmain calls them is part of the design. A sequence that works, with the reason for each step, is the following:
void kmain(void)
{
serial_init(); /* output first: every later step can report */
gdt_init(); /* own the segment state before anything names it */
idt_init(); /* exceptions have handlers; mistakes become messages */
pmm_init(); /* frames from the bootloader's memory map */
vmm_init(); /* kernel page tables, the direct map, drop the boot map */
heap_init(); /* kmalloc and kfree on top of mapped pages */
pic_remap(); /* or apic_init() */
pit_init(100); /* the first interrupt source */
keyboard_init();
irq_unmask(0);
irq_unmask(1);
asm volatile ("sti"); /* interrupts on, last */
pci_scan();
for (;;)
asm volatile ("hlt"); /* sleep until the next interrupt */
}Three rules are embedded in that order. Output comes first, because a kernel that cannot report is a kernel you cannot debug. Handlers come before the sources of interrupts: an IRQ line is unmasked only after the handler for its vector is installed, and sti is the very last step of initialization, since an interrupt that arrives while a table is half built is a crash with no explanation. And the memory system comes before anything that allocates, so that the first kmalloc call finds a heap. The final loop uses hlt, which stops the CPU until an interrupt arrives, instead of spinning: a busy loop wastes power and, in QEMU, the host CPU.
A good first boot prints one line per step, so the log itself becomes the test:
serial: ready
gdt: loaded, 7 entries
idt: loaded, 256 gates
pmm: 127424 KiB usable, 31856 frames free
vmm: kernel mapped, direct map at 0xffff800000000000
heap: 1 MiB ready
pic: remapped to 32
pit: 100 HzThe counts will match your machine and your QEMU memory setting, and the point is the shape: each line is a claim that the step succeeded, in the order it ran. When something resets the machine, the last line printed names the culprit.
Protection in practice
The page table flags in the earlier table are only enforced when the right control bits are on, and a kernel that forgets them runs without the protection it thinks it has. Three switches matter, and each is a single bit.
The first is write protect. By default the supervisor, meaning kernel code, can write to any page, including pages marked read-only in the tables. Setting bit 16, WP, of CR0 makes the CPU honor the read-only flag for the kernel too. That is what makes it safe to map the kernel's code and constants read-only and have a stray write fault instead of corrupting them. It is also what copy-on-write needs: the kernel marks shared pages read-only, and the fault on a write is the signal to copy.
The second is no-execute. The NX bit, bit 63 of a table entry, is honored only if the NXE bit, bit 11, of the EFER model-specific register is set. With it on, the data and stack pages can be marked non-executable, and an instruction fetch from one raises a page fault with the instruction-fetch bit set in its error code. Code injection, where an attacker writes bytes into a buffer and jumps to them, stops working. Set it in the same sequence as the long mode bit, with rdmsr and wrmsr on 0xC0000080, and mark every data mapping with NX.
The third is supervisor mode access prevention and execution prevention, SMAP and SMEP, bits 21 and 20 of CR4 on CPUs that support them, which you test with cpuid function 7. SMEP makes the kernel fault if it tries to execute a page that is user-accessible, and SMAP makes it fault on a data access to a user page unless it deliberately sets the AC flag with stac around the access. Both close classes of bugs where a kernel is tricked into using a pointer from user space, and both are worth enabling as soon as user mode exists.
A kernel should check the result of enabling each, since a silent failure to enable looks exactly like success. After setting EFER.NXE, read EFER back and test the bit. Then write a deliberate test: map a page without execute permission, copy a ret instruction into it, call it and expect a page fault with the fetch bit set in the error code. A protection that has never been seen to fail is a protection nobody knows works.
The TLB, and why stale entries hurt
Every memory access would need four additional memory reads for the page walk if the CPU did it each time. It does not: it caches recent translations in the translation lookaside buffer, the TLB. The cache is invisible when the page tables are static, and it is a source of subtle bugs when they change, because the CPU does not watch memory for changes to the tables. If you change an entry that was already cached, the old translation keeps being used until something flushes it.
The tools are few. invlpg invalidates the translation for one virtual address on the current CPU and is the right instruction after changing or clearing one entry. Writing CR3, which happens on every address space switch, flushes all non-global translations. Entries with the global bit set, used for the kernel's own mappings, survive a CR3 write, which saves refilling them after each context switch, and are flushed by toggling CR4.PGE. Newer CPUs support process-context identifiers, PCID, which tag the TLB entries with an address-space number so a switch does not need to flush at all.
On a multiprocessor, all of this gets harder. invlpg affects only the CPU that executes it, so a kernel that unmaps a page that another CPU might have cached must send that CPU an inter-processor interrupt asking it to flush too, the TLB shootdown. Forgetting it is one of the hardest bugs in kernel development, since the other CPU keeps using a frame that has been freed and handed to someone else. A uniprocessor hobby kernel never meets this, which is a good reason to understand the single-core case first and notice what changes later.
Interrupts and locking
The last interaction worth stating is between interrupt handlers and the rest of the kernel. A handler runs in the middle of whatever code was executing, on that code's stack, and it may touch the same data. If the main code is inside kmalloc, with the free list half updated, and an interrupt handler calls kmalloc too, the list is corrupted. The rules that follow from this are simple to state and constantly violated.
Handlers must be short and must not block. They acknowledge the device, record what happened, set a flag or put a message in a queue, and return, leaving the work to code running with interrupts enabled; this is the split into a fast top half and deferred bottom half that every kernel adopts. Shared data between a handler and normal code is protected by disabling interrupts around the critical section on the current CPU, with cli and sti, or better, by saving the flags, disabling and restoring the previous state, so that nested use does not turn interrupts back on too early:
static inline unsigned long irq_save(void)
{
unsigned long flags;
asm volatile ("pushfq; pop %0; cli" : "=r"(flags) : : "memory");
return flags;
}
static inline void irq_restore(unsigned long flags)
{
asm volatile ("push %0; popfq" : : "r"(flags) : "memory", "cc");
}A critical section is then flags = irq_save(); ... ; irq_restore(flags);. On more than one CPU, disabling interrupts is not enough, since another CPU can touch the same data, so a spinlock is added, and the lock is taken with interrupts off to avoid the deadlock where a handler tries to take a lock its own interrupted code holds. The hobby-scale rule is to decide, for every global the kernel has, whether a handler can reach it, and to write that down next to the declaration.
Debugging the core
Each part of the core has a QEMU view that settles arguments quickly. For interrupts, -d int,cpu_reset -no-reboot -D qemu.log logs every exception and every reset with the vector, error code and registers. For paging, the monitor commands info mem and info tlb print the virtual memory mappings the current CR3 describes, which shows at a glance whether a page you mapped is there with the permissions you intended. info registers shows CR0, CR2, CR3, CR4 and EFER, and x/8gx on a physical address through xp shows raw table entries. And GDB's x/8i $pc after a fault shows the instruction. The habits that pay off: print every table you build once, before enabling it; keep the first exception handler as simple as possible, a print and a halt; and change one layer at a time, so that a new reset has one suspect.
Where this does not fit
The guide targets one architecture, one mode and a hobby scale. It covers a uniprocessor kernel: every structure here needs locking, per-CPU data and inter-processor interrupts before a second core is started. It uses 4-level paging with 4 KiB pages, while a production kernel also uses 2 MiB and 1 GiB pages where it can, 5-level paging on CPUs that offer it, and address space identifiers to avoid flushing the TLB on every switch. The allocators are the simplest that work: bitmap and linked list are correct, and slow beyond a modest memory size, and production systems use buddy allocators and slabs. The legacy PIC and PS/2 are included because every emulator offers them, and real machines may not, so a kernel meant for hardware uses the APIC, ACPI tables and USB. If your goal is to ship drivers for a real operating system, the Linux kernel module material is the practical road, and if it is a small embedded device, an RTOS replaces most of this work.


