This repository has been archived on 2024-06-25. You can view files and clone it, but cannot push or open issues or pull requests.
rockOS/kernel/arch/i386/boot/gdt.c

65 lines
2.3 KiB
C
Raw Normal View History

2022-07-21 21:59:23 +03:00
/**
* GDT section of rockOS
* Copyright (C) 2022 Furkan Mudanyali
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, _either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
2022-07-20 02:23:23 +03:00
#include <rockos/gdt.h>
2022-07-18 18:14:20 +03:00
#include <stdio.h>
#include <stdint.h>
2022-07-19 11:47:14 +03:00
static uint32_t tss[32];
static gdt_entry_t gdt[GDT_ENTRIES];
static gdtr_t gdtptr;
void gdt_set_descriptor(uint8_t vector, uint32_t base, uint32_t limit, uint8_t access, uint8_t flags) {
gdt[vector].base_low = base & 0xFFFF;
gdt[vector].base_mid = (base >> 16) & 0xFF;
gdt[vector].base_high = (base >> 24) & 0xFF;
2022-07-18 18:14:20 +03:00
2022-07-19 11:47:14 +03:00
gdt[vector].limit_low = limit & 0xFFFF;
gdt[vector].limit_hi_flags = (limit >> 16) & 0x0F;
gdt[vector].limit_hi_flags |= flags << 4;
2022-07-18 18:14:20 +03:00
2022-07-19 11:47:14 +03:00
gdt[vector].access = access;
2022-07-18 18:14:20 +03:00
}
void gdt_init(void) {
2022-07-19 11:47:14 +03:00
gdt_set_descriptor(0, 0, 0, 0, 0); // 0x0000 Null Descriptor
gdt_set_descriptor(1, 0, 0xFFFFF, 0x9A, 0xC); // 0x0008 Kernel Mode Code Segment
gdt_set_descriptor(2, 0, 0xFFFFF, 0x92, 0xC); // 0x0010 Kernel Mode Data Segment
gdt_set_descriptor(3, 0, 0xFFFFF, 0xFA, 0xC); // 0x0018 User Mode Code Segment
gdt_set_descriptor(4, 0, 0xFFFFF, 0xF2, 0xC); // 0x0020 User Mode Data Segment
gdt_set_descriptor(5, (uintptr_t)&tss[0], sizeof(tss), 0x89, 0); // 0x0028 Task State Segment
2022-07-18 18:14:20 +03:00
2022-07-19 11:47:14 +03:00
gdtptr.base = (uintptr_t)&gdt[0];
gdtptr.limit = sizeof(gdt_entry_t) * GDT_ENTRIES - 1;
2022-07-19 11:47:14 +03:00
__asm__ volatile("lgdt %0" : : "m"(gdtptr)); // Load new GDT
__asm__ volatile(
"jmp $0x0008, $fix_cs\n"
"fix_cs:\n"
2022-07-19 11:47:14 +03:00
"mov %cr0, %eax\n"
"or $1, %al\n" // set PE (Protection Enable) bit in CR0 (Control Register 0)
"mov %eax, %cr0\n"
"mov $0x0010, %ax\n"
"mov %ax, %ds\n"
"mov %ax, %es\n"
"mov %ax, %fs\n"
"mov %ax, %gs\n"
"mov %ax, %ss"
);
2022-07-18 18:14:20 +03:00
}