; boot.asm — Kestrel stage 0: from real mode to long mode in one sector. ; ; The BIOS loads this sector at 0x7C00 and jumps to it in 16-bit real mode. ; We enable A20, identity-map the first 2 MiB with a single huge page, switch ; on PAE, long mode and paging in one step, and land in 64-bit code. ; ; nasm -f bin boot.asm -o boot.bin ; qemu-system-x86_64 -drive format=raw,file=boot.bin bits 16 org 0x7C00 PML4 equ 0x1000 ; page tables live in free low memory PDPT equ 0x2000 PD equ 0x3000 PRESENT_WRITABLE equ 0x03 HUGE equ 0x80 start: cli xor ax, ax mov ds, ax mov es, ax mov ss, ax mov sp, 0x7C00 cld in al, 0x92 ; fast A20 gate or al, 2 and al, 0xFE ; bit 0 would reset the machine out 0x92, al mov di, PML4 ; clear the PML4 mov cx, 4096 / 2 xor ax, ax rep stosw mov di, PDPT ; clear the PDPT mov cx, 4096 / 2 rep stosw mov di, PD ; clear the PD mov cx, 4096 / 2 rep stosw mov word [PML4], PDPT | PRESENT_WRITABLE mov word [PDPT], PD | PRESENT_WRITABLE mov word [PD], HUGE | PRESENT_WRITABLE ; 0..2 MiB, identity mov eax, 0b10100000 ; CR4.PAE | CR4.PGE mov cr4, eax mov edx, PML4 mov cr3, edx mov ecx, 0xC0000080 ; EFER rdmsr or eax, 1 << 8 ; EFER.LME wrmsr mov ebx, cr0 or ebx, 0x80000001 ; CR0.PG | CR0.PE, together mov cr0, ebx lgdt [gdt.pointer] jmp gdt.code:long_mode ; far jump loads the 64-bit code segment bits 64 long_mode: mov ax, gdt.data mov ds, ax mov es, ax mov ss, ax .halt: hlt jmp .halt align 8 gdt: dq 0 .code: equ $ - gdt dq 0x00AF9A000000FFFF ; 64-bit code, ring 0 .data: equ $ - gdt dq 0x00CF92000000FFFF ; data, ring 0 .pointer: dw $ - gdt - 1 dd gdt times 510 - ($ - $$) db 0 dw 0xAA55 ; boot signature