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.

Code
Blame·6 commits across 92 linesoldernewer
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
10
11 bits 16
12 org 0x7C00
13
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
19
21 cli
Fast A20 through port 0x92Aug 1 22 xor ax, ax
23 mov ds, ax
24 mov es, ax
25 mov ss, ax
26 mov sp, 0x7C00
27 cld
28
29 in al, 0x92 ; fast A20 gate
30 or al, 2
Keep bit 0 of port 0x92 clearAug 16 31 and al, 0xFE ; bit 0 would reset the machine
Fast A20 through port 0x92Aug 1 32 out 0x92, al
33
Identity-map the first 2 MiB with one huge pageAug 8 34 mov di, PML4 ; clear the PML4
35 mov cx, 4096 / 2
36 xor ax, ax
37 rep stosw
38 mov di, PDPT ; clear the PDPT
39 mov cx, 4096 / 2
40 rep stosw
41 mov di, PD ; clear the PD
42 mov cx, 4096 / 2
43 rep stosw
44 mov word [PML4], PDPT | PRESENT_WRITABLE
45 mov word [PDPT], PD | PRESENT_WRITABLE
46 mov word [PD], HUGE | PRESENT_WRITABLE ; 0..2 MiB, identity
47
Real mode straight to long modeAug 27 48 mov eax, 0b10100000 ; CR4.PAE | CR4.PGE
49 mov cr4, eax
50 mov edx, PML4
51 mov cr3, edx
52 mov ecx, 0xC0000080 ; EFER
53 rdmsr
54 or eax, 1 << 8 ; EFER.LME
55 wrmsr
56 mov ebx, cr0
57 or ebx, 0x80000001 ; CR0.PG | CR0.PE, together
58 mov cr0, ebx
59 lgdt [gdt.pointer]
60 jmp gdt.code:long_mode ; far jump loads the 64-bit code segment
61
62 bits 64
63long_mode:
64 mov ax, gdt.data
65 mov ds, ax
66 mov es, ax
67 mov ss, ax
69 mov edi, 0xB8000 + (12 * 80 + 36) * 2 ; row 12, centred
70 mov ah, 0x07 ; light grey on black
71.print: lodsb
72 test al, al
73 jz .halt
74 stosw
75 jmp .print
77 jmp .halt
78
Print the banner from 64-bit codeSep 5 79banner: db "kestrel", 0
80
82gdt: dq 0
83.code: equ $ - gdt
84 dq 0x00AF9A000000FFFF ; 64-bit code, ring 0
85.data: equ $ - gdt
86 dq 0x00CF92000000FFFF ; data, ring 0
87.pointer:
88 dw $ - gdt - 1
89 dd gdt
90
Boot sector skeleton and signatureJul 23 91 times 510 - ($ - $$) db 0
92 dw 0xAA55 ; boot signature