~ecs/k

ref: 354b6b991e68fe3ab6bdb0ff42f3261064ba6b21 k/boot.S -rw-r--r-- 2.0 KiB
354b6b99 — Eyal Sawady Initial commit 9 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
; Set up page table, run kmain

%define PTE_P 0x1
%define PTE_W 0x2
%define PTE_U 0x4
%define PTE_PS 0x80
%define CONSOLE_ADDR 0xB8000
%define CR4_PSE 0x10
%define CR4_PAE 0x20
%define MSR_IA32_EFER 0xC0000080
%define IA32_EFER_LME 0x100
%define IA32_EFER_NXE 0x800
%define IA32_EFER_SCE 0x1
%define CR0_PE 0x1
%define CR0_WP 0x10000
%define CR0_PG 0x80000000
%define BOOT_CS 0x8

%define BOOT_PAGETABLE 0x1000

bits 16
section .text

global start
extern kmain

start:
	cli
	cld

	mov sp, start

	mov esi, 0

	; BIOS magic
	mov ax, 0xEC00
	mov dx, 2
	int 0x15

	; Page table magic
	mov edi, 0x1000
	mov cr3, edi
	xor eax, eax
	mov ecx, 4096
	rep stosd
	mov edi, cr3

	mov dword [edi], 0x2000 + PTE_P + PTE_W
	add edi, 0x1000
	mov dword [edi], 0x3000 + PTE_P + PTE_W
	add edi, 0x1000
	mov dword [edi], 0x4000 + PTE_P + PTE_W
	add edi, 0x1000

	mov ebx, PTE_P + PTE_W
	mov ecx, 512

.setentry:
	mov dword [edi], ebx
	add ebx, 0x1000
	add edi, 8
	loop .setentry

	; Enable PAE
	mov eax, cr4
	or eax, 1 << 5
	mov cr4, eax

	; Protected mode
	mov ecx, 0xC0000080
	rdmsr
	or eax, 1 << 8
	wrmsr

	mov eax, cr0
	or eax, 1 << 31 | 1 << 0
	mov cr0, eax

	lgdt [gdt.pointer]
	jmp gdt.code:.64bit

	bits 64
.64bit

	mov rsi, 0

	mov byte [rsi + CONSOLE_ADDR + 10], 'k'

; Write to the screen once we're done initializing, for testing purposes
	mov rax, 0
.loop:
	mov byte [rax + CONSOLE_ADDR], 'k'
	mov byte [rax + CONSOLE_ADDR + 1], 0x7
	add rax, 2
	cmp rax, (96 * 64 * 2)
	jl .loop

	call kmain

	hlt

align 16
gdt:
.null:	equ $ - gdt
	; Low limit
	dw 0xFFFF
	; Low base
	dw 0
	; Middle base
	db 0
	; Access
	db 0
	; Granularity
	db 1
	; High base
	db 0
.code:	equ $ - gdt
	; Low limit
	dw 0
	; Low base
	dw 0
	; Middle base
	db 0
	; Access (exec/read)
	db 10011010b
	; Granularity, 64-bit flag, limit19:16
	db 10101111b
	; High base
	db 0
.data:	equ $ - gdt
	; Low limit
	dw 0
	; Low base
	dw 0
	; Middle base
	db 0
	; Access (read/write)
	db 10010010b
	; Granularity
	db 00000000b
	; High base
	db 0
.pointer:
	; Limit
	dw $ - gdt - 1
	; Base
	dq gdt