acompiled

The catalog contains seeded project examples. Your workspace stores your own projects and conversations.

kestrel-os/kestrel

Public
Star8

A small x86-64 kernel. Stage 0 goes from real mode to long mode inside the boot sector.

History
86 lines·2.5 KB·NASM Raw Blame
1; boot.asm — Kestrel stage 0: from real mode to long mode in one sector.
2;
3; The BIOS loads this sector at 0x7C00 and jumps to it in 16-bit real mode.
4; We enable A20, identity-map the first 2 MiB with a single huge page, switch
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.
7;
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
14PML4 equ 0x1000 ; page tables live in free low memory
15PDPT equ 0x2000
16PD equ 0x3000
17PRESENT_WRITABLE equ 0x03
18HUGE equ 0x80
20start:
21 cli
22 xor ax, ax
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
31 and al, 0xFE ; bit 0 would reset the machine
32 out 0x92, al
34 mov di, PML4 ; clear three 4 KiB tables
35 mov cx, 3 * 4096 / 2
36 xor ax, ax
37 rep stosw
39 mov word [PDPT], PD | PRESENT_WRITABLE
40 mov word [PD], HUGE | PRESENT_WRITABLE ; 0..2 MiB, identity
42 mov eax, 0b10100000 ; CR4.PAE | CR4.PGE
43 mov cr4, eax
44 mov edx, PML4
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
54 jmp gdt.code:long_mode ; far jump loads the 64-bit code segment
56 bits 64
57long_mode:
58 mov ax, gdt.data
59 mov ds, ax
60 mov es, ax
61 mov ss, ax
62 mov rsi, banner
63 mov edi, 0xB8000 + (12 * 80 + 36) * 2 ; row 12, centred
64 mov ah, 0x0E ; amber on black
65.print: lodsb
66 test al, al
68 stosw
70.halt: hlt
71 jmp .halt
73banner: db "kestrel", 0
75 align 8
76gdt: dq 0
77.code: equ $ - gdt
78 dq 0x00AF9A000000FFFF ; 64-bit code, ring 0
79.data: equ $ - gdt
80 dq 0x00CF92000000FFFF ; data, ring 0
81.pointer:
82 dw $ - gdt - 1
83 dd gdt
85 times 510 - ($ - $$) db 0
86 dw 0xAA55 ; boot signature