diff --git a/src/kernel/boot/boot.S b/src/kernel/boot/boot.S index 9df8fd3..1b7aef2 100644 --- a/src/kernel/boot/boot.S +++ b/src/kernel/boot/boot.S @@ -1,7 +1,57 @@ +#include + .intel_syntax noprefix + + +.section .bss +.align PAGE_SIZE +.skip PAGE_SIZE +BootStack: + .section .text -.global _start .code32 + +.global _start _start: -cli -jmp $ \ No newline at end of file + + cli + + // Temporary stack for booting + mov esp, offset BootStack + + // Enable Page Address Extension + mov eax, cr4 + or eax, 1<<5 + mov cr4, eax + + // Load Page Table (defined in boot/boot_PT.S) + mov eax, offset BootP4 + mov cr3, eax + + // Enable Long Mode + mov ecx, 0xC0000080 + rdmsr + or eax, 1<<8 + wrmsr + + // Enable paging + mov eax, cr0 + or eax, 1<<31 + mov cr0, eax + + // Load GDT (defined in cpu/gdt.c) + lgdt [GDTp] + + // Jump into long mode + jmp 0x8:long_mode_start + +.code64 +long_mode_start: + + // Clear out selectors + mov eax, 0x0 + mov ss, eax + mov ds, eax + mov es, eax + + jmp $ \ No newline at end of file diff --git a/src/kernel/boot/boot_PT.S b/src/kernel/boot/boot_PT.S new file mode 100644 index 0000000..d486919 --- /dev/null +++ b/src/kernel/boot/boot_PT.S @@ -0,0 +1,28 @@ +#include +.intel_syntax noprefix + +.section .data +.align PAGE_SIZE +.global BootP4 + +BootP4: + .quad offset BootP3 + (PAGE_PRESENT | PAGE_WRITE) + .rept ENTRIES_PER_PT - 1 + .quad 0 + .endr +BootP3: + .quad offset BootP2 + (PAGE_PRESENT | PAGE_WRITE) + .rept ENTRIES_PER_PT - 1 + .quad 0 + .endr +BootP2: + .quad offset BootP1 + (PAGE_PRESENT | PAGE_WRITE) + .rept ENTRIES_PER_PT - 1 + .quad 0 + .endr +BootP1: + .set i, 0 + .rept ENTRIES_PER_PT + .quad (i << 12) + (PAGE_PRESENT | PAGE_WRITE) + .set i, (i+1) + .endr \ No newline at end of file diff --git a/src/kernel/cpu/gdt.c b/src/kernel/cpu/gdt.c new file mode 100644 index 0000000..9e18ead --- /dev/null +++ b/src/kernel/cpu/gdt.c @@ -0,0 +1,25 @@ +#include + +#define GDT_CODE (3<<11) +#define GDT_DPL(lvl) ((lvl)<<13) +#define GDT_PRESENT (1<<15) +#define GDT_LONG (1<<21) + +struct gdt +{ + uint32_t _; + uint32_t flags; +}__attribute__((packed)); + +struct gdtp +{ + uint16_t len; + struct gdt *gdt; +}__attribute__((packed)); + +struct gdt BootGDT[] = { + {0, 0}, + {0, GDT_PRESENT | GDT_DPL(0) | GDT_CODE | GDT_LONG} +}; + +struct gdtp GDTp = {2*8-1, BootGDT}; \ No newline at end of file diff --git a/src/kernel/include/memory.h b/src/kernel/include/memory.h new file mode 100644 index 0000000..5beeea1 --- /dev/null +++ b/src/kernel/include/memory.h @@ -0,0 +1,8 @@ +#pragma once + +#define PAGE_SIZE 0x1000 + +#define PAGE_PRESENT 0x001 +#define PAGE_WRITE 0x002 + +#define ENTRIES_PER_PT 512 \ No newline at end of file