From 6058a5c8d13796dda4180ec5bd3e2edb61e74312 Mon Sep 17 00:00:00 2001 From: Ian Moffett Date: Sun, 21 Dec 2025 19:26:23 -0500 Subject: mos/x86_64: cpu: Load our own GDT We rely on our own global descriptor table so that we may use a task-state-segment to keep track of kernel stacks as well as having CPL 3 selectors available for user processes. Signed-off-by: Ian Moffett --- mos/sys/arch/x86_64/cpu/gdt.S | 85 ++++++++++++++++++++++++++++++++++++++++ mos/sys/arch/x86_64/cpu/locore.S | 5 +++ 2 files changed, 90 insertions(+) create mode 100644 mos/sys/arch/x86_64/cpu/gdt.S diff --git a/mos/sys/arch/x86_64/cpu/gdt.S b/mos/sys/arch/x86_64/cpu/gdt.S new file mode 100644 index 0000000..9bdbc55 --- /dev/null +++ b/mos/sys/arch/x86_64/cpu/gdt.S @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2025, Ian Moffett. + * Provided under the BSD-3 clause. + */ + + .text + .globl md_gdt_load +md_gdt_load: + /* + * [RDI]: GDTR + */ + push %r12 + push %r13 + push %r14 + push %r15 + push %rbx + push %rbp + + lgdt (%rdi) /* Load our own GDT */ + push $0x08 /* Kernel CS */ + lea 1f(%rip), %rbx /* Drop point */ + push %rbx /* RIP */ + lretq /* Flush prefetch + reload CS */ +1: mov $0x10, %ax /* Kernel DS */ + mov %ax, %ds + mov %ax, %es + mov %ax, %ss + mov %ax, %fs + xor %ax, %ax + mov %ax, %gs + + pop %rbp + pop %rbx + pop %r15 + pop %r14 + pop %r13 + pop %r12 + retq + + .section .data + .globl g_GDT +g_GDT: +.NULL: + .word 0x0000 + .word 0x0000 + .byte 0x00 + .byte 0b00000000 + .byte 0b00000000 + .byte 0x00 +.CODE: + .word 0x0000 + .word 0x0000 + .byte 0x00 + .byte 0b10011010 + .byte 0b00100000 + .byte 0x00 +.DATA: + .word 0x0000 + .word 0x0000 + .byte 0x00 + .byte 0b10010010 + .byte 0b00000000 + .byte 0x00 +.UCODE: + .word 0x0000 + .word 0x0000 + .byte 0x00 + .byte 0b11111010 + .byte 0b10101111 + .byte 0x00 +.UDATA: + .word 0x0000 + .word 0x0000 + .byte 0x00 + .byte 0b11110010 + .byte 0b00000000 + .byte 0x00 +.TSS: + .quad 0x00 + .quad 0x00 + + .globl g_GDTR +g_GDTR: + .word g_GDTR - g_GDT + .quad g_GDT diff --git a/mos/sys/arch/x86_64/cpu/locore.S b/mos/sys/arch/x86_64/cpu/locore.S index d96170b..5fdd741 100644 --- a/mos/sys/arch/x86_64/cpu/locore.S +++ b/mos/sys/arch/x86_64/cpu/locore.S @@ -6,10 +6,15 @@ .text .globl _start .globl kern_main + .extern md_gdt_load + .extern g_GDTR _start: cli cld + lea g_GDTR(%rip), %rdi /* BSP GDTR base */ + call md_gdt_load /* Load it */ + xor %rbp, %rbp /* Terminate callstack */ call kern_main /* Call kernel main */ -- cgit v1.2.3