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·5 commits across 81 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
5; on PAE, long mode and paging in one step, and land in 64-bit code.
7; nasm -f bin boot.asm -o boot.bin
8; qemu-system-x86_64 -drive format=raw,file=boot.bin
9
10 bits 16
11 org 0x7C00
12
Identity-map the first 2 MiB with one huge pageAug 8 13PML4 equ 0x1000 ; page tables live in free low memory
14PDPT equ 0x2000
15PD equ 0x3000
16PRESENT_WRITABLE equ 0x03
17HUGE equ 0x80
18
20 cli
Fast A20 through port 0x92Aug 1 21 xor ax, ax
22 mov ds, ax
23 mov es, ax
24 mov ss, ax
25 mov sp, 0x7C00
26 cld
27
28 in al, 0x92 ; fast A20 gate
29 or al, 2
Keep bit 0 of port 0x92 clearAug 16 30 and al, 0xFE ; bit 0 would reset the machine
Fast A20 through port 0x92Aug 1 31 out 0x92, al
32
Identity-map the first 2 MiB with one huge pageAug 8 33 mov di, PML4 ; clear the PML4
34 mov cx, 4096 / 2
35 xor ax, ax
36 rep stosw
37 mov di, PDPT ; clear the PDPT
38 mov cx, 4096 / 2
39 rep stosw
40 mov di, PD ; clear the PD
41 mov cx, 4096 / 2
42 rep stosw
43 mov word [PML4], PDPT | PRESENT_WRITABLE
44 mov word [PDPT], PD | PRESENT_WRITABLE
45 mov word [PD], HUGE | PRESENT_WRITABLE ; 0..2 MiB, identity
46
Real mode straight to long modeAug 27 47 mov eax, 0b10100000 ; CR4.PAE | CR4.PGE
48 mov cr4, eax
49 mov edx, PML4
50 mov cr3, edx
51 mov ecx, 0xC0000080 ; EFER
52 rdmsr
53 or eax, 1 << 8 ; EFER.LME
54 wrmsr
55 mov ebx, cr0
56 or ebx, 0x80000001 ; CR0.PG | CR0.PE, together
57 mov cr0, ebx
58 lgdt [gdt.pointer]
59 jmp gdt.code:long_mode ; far jump loads the 64-bit code segment
60
61 bits 64
62long_mode:
63 mov ax, gdt.data
64 mov ds, ax
65 mov es, ax
66 mov ss, ax
68 jmp .halt
69
71gdt: dq 0
72.code: equ $ - gdt
73 dq 0x00AF9A000000FFFF ; 64-bit code, ring 0
74.data: equ $ - gdt
75 dq 0x00CF92000000FFFF ; data, ring 0
76.pointer:
77 dw $ - gdt - 1
78 dd gdt
79
Boot sector skeleton and signatureJul 23 80 times 510 - ($ - $$) db 0
81 dw 0xAA55 ; boot signature