A small x86-64 kernel. Stage 0 goes from real mode to long mode inside the boot sector.
Real mode straight to long modeAug 27
1; boot.asm — Kestrel stage 0: from real mode to long mode in one sector.
3; The BIOS loads this sector at 0x7C00 and jumps to it in 16-bit real mode.
Real mode straight to long modeAug 27
4; We enable A20, identity-map the first 2 MiB with a single huge page, switch
Print the banner from 64-bit codeSep 5
5; on PAE, long mode and paging in one step, and land in 64-bit code that
6; writes the banner straight into VGA text memory.
8; nasm -f bin boot.asm -o boot.bin
9; qemu-system-x86_64 -drive format=raw,file=boot.bin
11 bits 16
12 org 0x7C00
Identity-map the first 2 MiB with one huge pageAug 8
14PML4 equ 0x1000 ; page tables live in free low memory
15PDPT equ 0x2000
16PD equ 0x3000
17PRESENT_WRITABLE equ 0x03
18HUGE equ 0x80
21 cli
23 mov ds, ax
24 mov es, ax
25 mov ss, ax
26 mov sp, 0x7C00
27 cld
29 in al, 0x92 ; fast A20 gate
30 or al, 2
Share one zeroing loop for all three tables: -16 bytesSep 12
34 mov di, PML4 ; clear three 4 KiB tables
35 mov cx, 3 * 4096 / 2
37 rep stosw
38 mov word [PML4], PDPT | PRESENT_WRITABLE
39 mov word [PDPT], PD | PRESENT_WRITABLE
40 mov word [PD], HUGE | PRESENT_WRITABLE ; 0..2 MiB, identity
43 mov cr4, eax
45 mov cr3, edx
46 mov ecx, 0xC0000080 ; EFER
47 rdmsr
48 or eax, 1 << 8 ; EFER.LME
49 wrmsr
50 mov ebx, cr0
51 or ebx, 0x80000001 ; CR0.PG | CR0.PE, together
52 mov cr0, ebx
53 lgdt [gdt.pointer]
56 bits 64
57long_mode:
59 mov ds, ax
60 mov es, ax
61 mov ss, ax
63 mov edi, 0xB8000 + (12 * 80 + 36) * 2 ; row 12, centred
66 test al, al
68 stosw
76gdt: dq 0
78 dq 0x00AF9A000000FFFF ; 64-bit code, ring 0
80 dq 0x00CF92000000FFFF ; data, ring 0
81.pointer:
86 dw 0xAA55 ; boot signature