;Based on the OSDev Wiki code

global boot
;extern main        ; Allow main() to be called from the assembly code
;extern start_ctors, end_ctors, start_dtors, end_dtors

BITS 32

MODULEALIGN        equ        1<<0
MEMINFO            equ        1<<1
FLAGS              equ        MODULEALIGN | MEMINFO
MAGIC              equ        0x1BADB002
CHECKSUM           equ        -(MAGIC + FLAGS)

PML4SIZE equ 512 * 8; 4 64-bit ints
PAGEDIRSIZE equ 512 * 8
PAGETABLESIZE equ 512 * 8
PAGESIZE equ 4096

BOOT32MAPSIZE equ 512 * PAGESIZE

section .text      ; Next is the Grub Multiboot Header

align PAGESIZE
multiboot_header:
       dd MAGIC
       dd FLAGS
       dd CHECKSUM

STACKSIZE equ 0x4000

boot:
	call set_gdt

	mov esp, STACKSIZE+stack

	push eax
	push ebx

	call init_paging

	;eax, ebx are already on the stack.
	;call main

set_gdt:
	lgdt [gdtr]
	jmp 0x08:flush_gdt
	flush_gdt:
		mov bx, 0x10
		mov ds, bx
		mov es, bx
		mov fs, bx
		mov gs, bx
		mov ss, bx
		ret

init_paging:
	;Set up basic structure
	;To do: consolidate movs?
	mov eax, page_dir
	or eax, 3
	mov [page_pml4], eax
	mov eax, page_table
	or eax, 3
	mov [page_dir], eax

	;Identity map
	mov ecx, BOOT32MAPSIZE - PAGESIZE
	mov edi, page_table + PAGETABLESIZE - 8
	map_identity:
		mov eax, ecx
		or eax, 3
		mov [edi], eax
		sub edi, 8
		sub ecx, PAGESIZE
		jnz map_identity
		mov eax, ecx
		or eax, 3
		mov [edi], eax

	;Enable PAE and paging
	cli
	mov eax, cr4
	or eax, 1 << 5
	mov cr4, eax
	mov eax, page_pml4
	mov cr3, eax
	mov eax, cr0
	or eax, 1 << 31
	;mov cr0, eax

	stop:
		hlt
		jmp stop

	ret

;;----;;
;;Data;;
;;----;;

section .data
align PAGESIZE

gdtr:
	dw gdt_end - gdt - 1 ; size of the GDT
	dd gdt ; linear address of GDT

gdt:
	dd 0, 0
	db 0xFF, 0xFF, 0, 0, 0, 0x9A, 0xC0 | 0xF, 0
	db 0xFF, 0xFF, 0, 0, 0, 0x92, 0xC0 | 0xF, 0
gdt_end:

section .bss
align PAGESIZE

stack:
	resb STACKSIZE

page_dir:
	resb PAGEDIRSIZE

page_table:
	resb PAGETABLESIZE

page_pml4:
	resb PML4SIZE
