Set Up a Global Descriptor Table (GDT) in Your Kernel
Build your own x86 GDT in C: descriptor layout, kernel and user segments, a TSS slot, lgdt and segment register reloads, and the 64-bit changes.

When a bootloader hands you control, the CPU is using a GDT that belongs to the bootloader: it is somewhere in the bootloader's memory, you do not know where, and you do not know what is in it beyond the minimum the specification promises. The moment your kernel reuses that memory, or wants a user-mode segment, the table must be yours. Setting up your own Global Descriptor Table is the first piece of CPU state a kernel takes over, and it is a short job that is easy to get subtly wrong. This post builds one in C for a 32-bit kernel: the exact layout of an eight-byte descriptor, the five segments plus a task state segment that a kernel with user mode needs, the assembly that loads the table and reloads every segment register, and the changes for 64-bit mode. It uses the kernel structure from the hobby OS guide, and the background on why segments still exist is in segmentation versus paging.
The descriptor
A segment descriptor is eight bytes with fields laid out in a way that reflects its history. The 80286 defined a 24-bit base and a 16-bit limit, and the 80386 extended them by adding bits in the formerly reserved top word, so the base and limit are each split into non-contiguous pieces.
| Byte | Content |
|---|---|
| 0 to 1 | Limit bits 0 to 15 |
| 2 to 3 | Base bits 0 to 15 |
| 4 | Base bits 16 to 23 |
| 5 | Access byte |
| 6 | Limit bits 16 to 19 (low nibble) and flags (high nibble) |
| 7 | Base bits 24 to 31 |
The access byte has these bits, from the top: P, present; DPL, two bits for the privilege level 0 to 3; S, set for a code or data segment and clear for a system segment such as a TSS; E, executable, set for code; DC, direction or conforming; RW, readable for code or writable for data; A, accessed, which the CPU sets. The flags nibble has G, granularity: when set, the limit counts 4 KiB units instead of bytes; DB, the size bit, set for 32-bit segments; and L, long mode, for 64-bit code.
The values for a flat kernel come from these definitions. Kernel code is present, privilege 0, a code or data type, executable and readable: 1 00 1 1 0 1 0 = 0x9A. Kernel data drops executable and is writable: 0x92. User segments are the same at privilege 3, which sets the DPL bits to 11: 0xFA for code and 0xF2 for data. The flags nibble 0xC for all four, granularity and 32-bit, together with the limit's top nibble 0xF, gives the byte 0xCF, with limit 0xFFFFF in 4 KiB units covering 4 GiB.
The C structures and a setter
Because the layout is a hardware format, the structures must be packed:
#ifndef GDT_H
#define GDT_H
#include <stdint.h>
struct gdt_entry {
uint16_t limit_low;
uint16_t base_low;
uint8_t base_mid;
uint8_t access;
uint8_t limit_flags; /* limit bits 16-19, then flags */
uint8_t base_high;
} __attribute__((packed));
struct gdt_ptr {
uint16_t limit;
uint32_t base;
} __attribute__((packed));
void gdt_init(void);
void tss_set_kernel_stack(uint32_t esp0);
#endifThe setter packs the pieces of a base, limit, access byte and flags into one entry:
#include "gdt.h"
#define GDT_ENTRIES 6
static struct gdt_entry gdt[GDT_ENTRIES];
static struct gdt_ptr gdt_pointer;
static void gdt_set(int i, uint32_t base, uint32_t limit,
uint8_t access, uint8_t flags)
{
gdt[i].limit_low = limit & 0xFFFF;
gdt[i].base_low = base & 0xFFFF;
gdt[i].base_mid = (base >> 16) & 0xFF;
gdt[i].access = access;
gdt[i].limit_flags = ((limit >> 16) & 0x0F) | (flags & 0xF0);
gdt[i].base_high = (base >> 24) & 0xFF;
}The flags argument is passed in the high nibble, so the function masks it into limit_flags with 0xF0, and the limit's bits 16 to 19 occupy the low nibble. Calling it with flags 0xC0 and a limit of 0xFFFFF produces the byte 0xCF.
The task state segment
A kernel that runs user code needs a TSS, even if it never uses hardware task switching. When an interrupt or system call arrives from privilege level 3, the CPU switches to a kernel stack, and it learns the address of that stack from the TSS fields ss0 and esp0. Without them the CPU cannot enter the kernel safely. In 32-bit mode the structure is 104 bytes:
struct tss {
uint32_t prev_tss;
uint32_t esp0, ss0;
uint32_t esp1, ss1;
uint32_t esp2, ss2;
uint32_t cr3, eip, eflags;
uint32_t eax, ecx, edx, ebx, esp, ebp, esi, edi;
uint32_t es, cs, ss, ds, fs, gs;
uint32_t ldt;
uint16_t trap, iomap_base;
} __attribute__((packed));
static struct tss tss;Only ss0 and esp0 matter here: they are the kernel data segment selector and the top of the kernel stack to use when entering from user mode. The scheduler updates esp0 on every context switch to point at the incoming task's kernel stack:
void tss_set_kernel_stack(uint32_t esp0)
{
tss.esp0 = esp0;
}Building the table
Six entries: null, kernel code, kernel data, user code, user data and the TSS descriptor. The TSS is a system descriptor, with the S bit clear and the type field 9, an available 32-bit TSS, giving access byte 0x89.
extern void gdt_flush(uint32_t gdt_ptr_address);
extern void tss_flush(void);
void gdt_init(void)
{
gdt_pointer.limit = sizeof(gdt) - 1;
gdt_pointer.base = (uint32_t)&gdt[0];
gdt_set(0, 0, 0, 0, 0); /* 0x00 null */
gdt_set(1, 0, 0xFFFFF, 0x9A, 0xC0); /* 0x08 kernel code */
gdt_set(2, 0, 0xFFFFF, 0x92, 0xC0); /* 0x10 kernel data */
gdt_set(3, 0, 0xFFFFF, 0xFA, 0xC0); /* 0x18 user code */
gdt_set(4, 0, 0xFFFFF, 0xF2, 0xC0); /* 0x20 user data */
tss.ss0 = 0x10; /* kernel data selector */
tss.esp0 = 0; /* set before entering user mode */
tss.iomap_base = sizeof(tss); /* no I/O permission bitmap */
gdt_set(5, (uint32_t)&tss, sizeof(tss) - 1, 0x89, 0x00); /* 0x28 TSS */
gdt_flush((uint32_t)&gdt_pointer);
tss_flush();
}The selector for entry i is i * 8, so the kernel code selector is 0x08, kernel data 0x10, user code 0x18, user data 0x20 and the TSS 0x28. When user code uses its selectors, the low two bits carry the requested privilege level, so the user selectors in use are 0x18 | 3 = 0x1B and 0x20 | 3 = 0x23. The TSS limit is its size minus one, with byte granularity, since the flags are zero. Setting iomap_base to the TSS size, past the end, tells the CPU there is no I/O permission bitmap, so user-mode port access is denied.
To verify the table, print the entries as 64-bit values. The raw values are determined by the arithmetic above, and for the first four real entries they are:
gdt[0] = 0x0000000000000000
gdt[1] = 0x00CF9A000000FFFF
gdt[2] = 0x00CF92000000FFFF
gdt[3] = 0x00CFFA000000FFFF
gdt[4] = 0x00CFF2000000FFFFIf your printed values differ, the packing is wrong; common causes are a missing packed attribute, which pads the structure, and passing the flags in the low nibble.
Loading it and reloading the segment registers
Loading the table's address with lgdt does not change anything the CPU is currently using. Each segment register holds a hidden cache of the descriptor it was loaded from, and that cache stays in force until you reload the register. So after lgdt you must reload them all, with the code segment needing a far jump or return because it cannot be loaded by a mov.
.global gdt_flush
.type gdt_flush, @function
gdt_flush:
mov 4(%esp), %eax
lgdt (%eax)
mov $0x10, %ax
mov %ax, %ds
mov %ax, %es
mov %ax, %fs
mov %ax, %gs
mov %ax, %ss
ljmp $0x08, $.reload_cs
.reload_cs:
ret
.global tss_flush
.type tss_flush, @function
tss_flush:
mov $0x28, %ax
ltr %ax
retThe function takes the address of the gdt_ptr as its argument on the stack, loads it, reloads the five data segment registers with the kernel data selector 0x10, and uses ljmp $0x08, $.reload_cs to load CS with the kernel code selector. The label after the jump is simply the next instruction, since the jump exists only for its side effect. tss_flush executes ltr with the TSS selector, which marks the descriptor busy and tells the CPU where the TSS is. ltr must not be executed before the descriptor exists, and it faults if the descriptor is not an available TSS.
Call gdt_init() early in kernel_main, before the IDT is built, because every IDT gate names a code selector and that selector must exist in your table: the one you load, not the bootloader's.
64-bit differences
In long mode the same ideas apply with these changes. The code descriptor has the L flag set and DB clear: flags 0xA0 and access 0x9A, so the quadword is 0x00AF9A000000FFFF. The base and limit are ignored for code and data. The TSS descriptor is 16 bytes, to hold a 64-bit base, so it takes two table slots, and the TSS itself holds rsp0 to rsp2 and the seven interrupt stack table pointers, as covered in setting up the TSS and Interrupt Stack Table. The pointer given to lgdt is ten bytes, a 16-bit limit and a 64-bit base. And reloading CS is done with a far return, pushing the selector and the target address and executing lretq, because there is no 64-bit far jump with an immediate.
What goes wrong
A kernel that triple faults right after gdt_flush has usually a selector that does not exist in the new table, a missing packed that shifts the layout, or a wrong limit in the pointer. The CPU reports this as a general protection fault, with the error code containing the selector index. A kernel that survives the flush but faults at the first interrupt has an IDT gate whose selector was the bootloader's value, since the code selector in the new table may differ. A user program that faults at its first instruction usually has a user selector without the requested privilege level 3 in its low bits.
Where this does not fit
A flat GDT with these segments is the right answer for essentially every protected-mode kernel. If you boot with Limine or another 64-bit protocol, the bootloader leaves a usable GDT, but you should still replace it, because it lives in bootloader memory that may be reclaimed. Hardware task switching through TSS descriptors, which the 32-bit architecture supports, is not used by any mainstream kernel, and is not available in long mode. And a design with very different needs, such as a microkernel using segments for isolation on 32-bit hardware, might use more than the six entries here.


