From 5e668f5e67579ba16974031955b9818f2272c055 Mon Sep 17 00:00:00 2001 From: Nigel Barink Date: Wed, 12 May 2021 23:03:00 +0100 Subject: [PATCH 001/115] Basics for an proper GDT and IDT --- Makefile | 6 +- src/kernel/arch/i386/boot.s | 381 +++++++++++++++++++++++++++++-- src/kernel/arch/i386/tty/kterm.c | 1 - src/kernel/arch/i386/tty/kterm.h | 1 + src/kernel/gdtc.cpp | 29 +++ src/kernel/gdtc.h | 20 ++ src/kernel/idt.cpp | 64 ++++++ src/kernel/idt.h | 70 ++++++ src/kernel/kernel.cpp | 39 +++- src/kernel/kernel.h | 5 +- 10 files changed, 590 insertions(+), 26 deletions(-) create mode 100644 src/kernel/gdtc.cpp create mode 100644 src/kernel/gdtc.h create mode 100644 src/kernel/idt.cpp create mode 100644 src/kernel/idt.h diff --git a/Makefile b/Makefile index 4611669..f329535 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/MMU.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/MMU.o $(BUILD_DIR)/idt.o SRC_DIR = src BUILD_DIR = build @@ -56,4 +56,6 @@ $(BUILD_DIR)/crtn.o: $(BUILD_DIR)/io.o: $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/MMU.o: - $(CPP) -c $(SRC_DIR)/kernel/MMU.cpp -o $(BUILD_DIR)/MMU.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file + $(CPP) -c $(SRC_DIR)/kernel/MMU.cpp -o $(BUILD_DIR)/MMU.o $(CFLAGS) -fno-exceptions -fno-rtti +$(BUILD_DIR)/idt.o: + $(CPP) -c $(SRC_DIR)/kernel/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file diff --git a/src/kernel/arch/i386/boot.s b/src/kernel/arch/i386/boot.s index 99fa270..91c47df 100644 --- a/src/kernel/arch/i386/boot.s +++ b/src/kernel/arch/i386/boot.s @@ -20,8 +20,12 @@ stack_bottom: .skip 16384 # 16 KiB stack_top: - - +.text +.globl idt_flush +idt_flush: + mov 4(%esp), %eax + lidt (%eax) + ret .text .globl enablePaging @@ -51,20 +55,369 @@ loadPageDirectory: .global _start .type _start, @function _start: - - - + /*Setup the stack pointer to point to the beginning of our stack */ + /* I believe its a hight address growing down to lower adress for the stack on x86*/ mov $stack_top, %esp - + call early_main + + load_gdt: + lgdt gdt + + # set the segment selecters + + movw $0x10, %ax + movw %ax, %ds + movw %ax, %es + movw %ax, %fs + movw %ax, %gs + movw %ax, %ss + ljmp $0x08, $flush + + flush: + #load idt + call init_idt + + # Try enable A20 + # mov $0x2401, %ax + # int $0x15 - call _init - call kernel_main - + # enable protected mode + mov %cr0, %eax + or $1, %eax + mov %eax, %cr0 - cli -1: hlt - jmp 1b - + + call kernel_main -.size _start, . - _start \ No newline at end of file + + cli + 1: hlt + jmp 1b + + + + + /* Tell processor to use our gdt*/ + gdt: + .word (gdt_end - gdt_start -1) # Size of the GDT in bytes minus 1 for math reasons + .int gdt_start # linear address of our GDT + + + + +.att_syntax + + +.size _start, . - _start + + +/* +* Interupt handlers +*/ + +.text +.macro irq_NoErrCode code:req + .globl irq\code + irq\code: + cli + pushb $0 + pushb \code + jmp irq_common +.endm + +.text +.macro irq_ErrCode code + .globl irq\code + irq\code: + cli + pushb \code + jmp irq_common +.endm + + + +.globl irq0 +irq0: + cli + push $0 + push $0 + jmp irq_common + +.globl irq1 +irq1: + cli + push $0 + push $1 + jmp irq_common + +.globl irq2 +irq2: + cli + push $0 + push $2 + jmp irq_common + +.globl irq3 +irq3: + cli + push $0 + push $3 + jmp irq_common + +.globl irq4 +irq4: + cli + push $0 + push $4 + jmp irq_common + +.globl irq5 +irq5: + cli + push $0 + push $5 + jmp irq_common + +.globl irq6 +irq6: + cli + push $0 + push $6 + jmp irq_common + +.globl irq7 +irq7: + cli + push $0 + push $7 + jmp irq_common + +.globl irq8 +irq8: + cli + push $0 + push $8 + jmp irq_common + +.globl irq9 +irq9: + cli + push $0 + push $9 + jmp irq_common + +.globl irq10 +irq10: + cli + push $0 + push $10 + jmp irq_common + +.globl irq11 +irq11: + cli + push $0 + push $11 + jmp irq_common + +.globl irq12 +irq12: + cli + push $0 + push $12 + jmp irq_common + +.globl irq13 +irq13: + cli + push $0 + push $13 + jmp irq_common + +.globl irq14 +irq14: + cli + push $0 + push $14 + jmp irq_common + +.globl irq15 +irq15: + cli + push $0 + push $15 + jmp irq_common + +.globl irq16 +irq16: + cli + push $0 + push $16 + jmp irq_common + +.globl irq17 +irq17: + cli + push $0 + push $17 + jmp irq_common + +.globl irq18 +irq18: + cli + push $0 + push $18 + jmp irq_common + +.globl irq19 +irq19: + cli + push $0 + push $19 + jmp irq_common + +.globl irq20 +irq20: + cli + push $0 + push $20 + jmp irq_common + +.globl irq21 +irq21: + cli + push $0 + push $21 + jmp irq_common + +.globl irq22 +irq22: + cli + push $0 + push $22 + jmp irq_common + +.globl irq23 +irq23: + cli + push $0 + push $23 + jmp irq_common + +.globl irq24 +irq24: + cli + push $0 + push $24 + jmp irq_common + +.globl irq25 +irq25: + cli + push $0 + push $25 + jmp irq_common + +.globl irq26 +irq26: + cli + push $0 + push $26 + jmp irq_common + +.globl irq27 +irq27: + cli + push $0 + push $27 + jmp irq_common + +.globl irq28 +irq28: + cli + push $0 + push $28 + jmp irq_common + +.globl irq29 +irq29: + cli + push $0 + push $29 + jmp irq_common + +.globl irq30 +irq30: + cli + push $0 + push $30 + jmp irq_common + +.globl irq31 +irq31: + cli + push $0 + push $31 + jmp irq_common + + + + + + +.text +irq_common: + pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax + + + mov %ds, %ax + push %eax + + /* load the kernel data segment descriptor*/ + + mov $0x10, %ax + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + call irq_handler + + pop %eax + + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + popa + add $8, %esp # cleans push error and irq code + sti + iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP + +/* +* Create the GDT +*/ +.section .data +gdt_start: +gdt_null: +.long 0x0 +.long 0x0 + +gdt_kcode: +.word 0xFFFF # limit +.word 0x0 # base +.byte 0x0 # base +.byte 0b10011010 # 1st flags | type flags +.byte 0b11001111 # 2nd flags | limit +.byte 0x0 # base + +gdt_kdata: +.word 0xFFFF # limit +.word 0x0 # base +.byte 0x0 # base +.byte 0b10010010 # 1st flags | type flags +.byte 0b11001111 # 2nd flags | limit +.byte 0x0 # base +gdt_end: \ No newline at end of file diff --git a/src/kernel/arch/i386/tty/kterm.c b/src/kernel/arch/i386/tty/kterm.c index 2021e22..6dab47f 100644 --- a/src/kernel/arch/i386/tty/kterm.c +++ b/src/kernel/arch/i386/tty/kterm.c @@ -89,4 +89,3 @@ void kterm_writestring(const char* data ){ AS_KERNEL(); kterm_write(data, strlen(data)); } - diff --git a/src/kernel/arch/i386/tty/kterm.h b/src/kernel/arch/i386/tty/kterm.h index 6cf784e..f1570c6 100644 --- a/src/kernel/arch/i386/tty/kterm.h +++ b/src/kernel/arch/i386/tty/kterm.h @@ -15,6 +15,7 @@ void kterm_putat(char, uint8_t, size_t, size_t); void kterm_put(char); void kterm_write(const char*, size_t); void kterm_writestring(const char*); + void kterm_scrollup(); #define KernelTag "[Kernel]: " diff --git a/src/kernel/gdtc.cpp b/src/kernel/gdtc.cpp new file mode 100644 index 0000000..f21e80f --- /dev/null +++ b/src/kernel/gdtc.cpp @@ -0,0 +1,29 @@ +#include "gdtc.h" + + +gdtEntry_t gdt[3]; + + +void gdtSetGate(int num, uint64_t base, uint64_t limit, uint8_t access, + uint8_t gran){ + gdt[num].lBase = (base & 0xFFFF); + gdt[num].mBase = (base >> 16) & 0xFF; + gdt[num].hBase = (base >> 24) & 0xFF; + + gdt[num].lLimit = (limit & 0xFFFF); + gdt[num].granularity = ((limit >> 16) & 0x0F); + + gdt[num].granularity |= (gran & 0xF0); + gdt[num].access = access; +} + +void setupGdt(){ + gdtPointer.limit = (sizeof(gdtEntry_t) * 3) - 1; + gdtPointer.base = &gdt; + + gdtSetGate(0, 0, 0, 0, 0); + gdtSetGate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); + gdtSetGate(2, 0, 0xFFFFFFFF, 0x92, 0xCF); + + loadGdt(); +} diff --git a/src/kernel/gdtc.h b/src/kernel/gdtc.h new file mode 100644 index 0000000..2b34997 --- /dev/null +++ b/src/kernel/gdtc.h @@ -0,0 +1,20 @@ +#include +extern "c"{ + +typedef struct { + uint16_t lLimit; + uint16_t lBase; + uint8_t mBase; + uint8_t access; + uint8_t granularity; + uint8_t hBase; +} gdtEntry_t; + +struct { + uint16_t limit; + uint32_t base; +} gdtPointer; + +extern void loadGdt(); +void setupGdt(); +} \ No newline at end of file diff --git a/src/kernel/idt.cpp b/src/kernel/idt.cpp new file mode 100644 index 0000000..2ba7165 --- /dev/null +++ b/src/kernel/idt.cpp @@ -0,0 +1,64 @@ +#include "idt.h" + +IDT_entry idt_table[256]; +IDT_ptr idt_ptr; + +void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ + idt_table[num].offset_1 = base & 0xFFFF; + idt_table[num].selector = sel; + idt_table[num].zero = 0; + idt_table[num].type_attr = flags; + idt_table[num].offset_2 = (base >> 16) & 0xFFFF; + +}; + + +void irq_handler (registers regs) { + kterm_writestring("received interrupt!"); +} + + +void init_idt(){ + // Initialise the IDT pointer + idt_ptr.length = sizeof(IDT_entry) * 255; + idt_ptr.base = (uint32_t)&idt_table; + + + // TODO: Set everything to zero first + + set_id_entry(0, (uint32_t) irq0 , 0x08, 0x8E); + set_id_entry(1, (uint32_t) irq1 , 0x08, 0x8E); + set_id_entry(2, (uint32_t) irq2 , 0x08, 0x8E); + set_id_entry(3, (uint32_t) irq3 , 0x08, 0x8E); + set_id_entry(4, (uint32_t) irq4 , 0x08, 0x8E); + set_id_entry(5, (uint32_t) irq5 , 0x08, 0x8E); + set_id_entry(6, (uint32_t) irq6 , 0x08, 0x8E); + set_id_entry(7, (uint32_t) irq7 , 0x08, 0x8E); + set_id_entry(8, (uint32_t) irq8 , 0x08, 0x8E); + set_id_entry(9, (uint32_t) irq9 , 0x08, 0x8E); + set_id_entry(10, (uint32_t) irq10 , 0x08, 0x8E); + set_id_entry(11, (uint32_t) irq11 , 0x08, 0x8E); + set_id_entry(12, (uint32_t) irq12 , 0x08, 0x8E); + set_id_entry(13, (uint32_t) irq13 , 0x08, 0x8E); + set_id_entry(14, (uint32_t) irq14 , 0x08, 0x8E); + set_id_entry(15, (uint32_t) irq15 , 0x08, 0x8E); + set_id_entry(16, (uint32_t) irq16 , 0x08, 0x8E); + set_id_entry(17, (uint32_t) irq17 , 0x08, 0x8E); + set_id_entry(18, (uint32_t) irq18 , 0x08, 0x8E); + set_id_entry(19, (uint32_t) irq19 , 0x08, 0x8E); + set_id_entry(20, (uint32_t) irq20 , 0x08, 0x8E); + set_id_entry(21, (uint32_t) irq21 , 0x08, 0x8E); + set_id_entry(22, (uint32_t) irq22 , 0x08, 0x8E); + set_id_entry(23, (uint32_t) irq23 , 0x08, 0x8E); + set_id_entry(24, (uint32_t) irq24 , 0x08, 0x8E); + set_id_entry(25, (uint32_t) irq25 , 0x08, 0x8E); + set_id_entry(26, (uint32_t) irq26 , 0x08, 0x8E); + set_id_entry(27, (uint32_t) irq27 , 0x08, 0x8E); + set_id_entry(28, (uint32_t) irq28 , 0x08, 0x8E); + set_id_entry(29, (uint32_t) irq29 , 0x08, 0x8E); + set_id_entry(30, (uint32_t) irq30 , 0x08, 0x8E); + set_id_entry(31, (uint32_t) irq31 , 0x08, 0x8E); + + + idt_flush((uint32_t)&idt_ptr); +} diff --git a/src/kernel/idt.h b/src/kernel/idt.h new file mode 100644 index 0000000..78b9a3d --- /dev/null +++ b/src/kernel/idt.h @@ -0,0 +1,70 @@ +#pragma once +#include "stdint.h" + +extern "C" void kterm_writestring(const char* data ); + +extern "C" { + struct __attribute__((__packed__)) IDT_entry { + uint16_t offset_1; + uint16_t selector; + uint8_t zero; + uint8_t type_attr; + uint16_t offset_2; + }; + + struct __attribute__((__packed__)) IDT_ptr { + unsigned short length; + unsigned long base; + }; + + struct registers { + uint32_t ds; // Data segment selector + uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax; // Pushed by pusha. + uint32_t int_no, err_code; // Interrupt number and error code (if applicable) + uint32_t eip, cs, eflags, useresp, ss; + }; + + + extern void idt_flush(uint32_t); + void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags); + void init_idt(); + + void irq_handler (registers regs); + + extern void irq0 (); + extern void irq1 (); + extern void irq2 (); + extern void irq3 (); + extern void irq4 (); + extern void irq5 (); + extern void irq6 (); + extern void irq7 (); + extern void irq8 (); + extern void irq9 (); + extern void irq10 (); + extern void irq11 (); + extern void irq12 (); + extern void irq13 (); + extern void irq14 (); + extern void irq15 (); + extern void irq16 (); + extern void irq17 (); + extern void irq18 (); + extern void irq19 (); + extern void irq20 (); + extern void irq21 (); + extern void irq22 (); + extern void irq23 (); + extern void irq24 (); + extern void irq25 (); + extern void irq26 (); + extern void irq27 (); + extern void irq28 (); + extern void irq29 (); + extern void irq30 (); + extern void irq31 (); + + + + +} diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 14f0321..ddb9402 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -74,6 +74,12 @@ char read_serial() { } +void print_serial(const char* string ){ + for(size_t i = 0; i < strlen(string); i ++){ + write_serial(string[i]); + } +} + void test_serial(){ /** Serial test **/ kterm_writestring("Writing to COM1 serial port:"); @@ -93,11 +99,34 @@ void test_serial(){ } + extern "C" { + + void early_main(){ + + init_serial(); + print_serial("\033[31;42mEarly main called!\n"); + + + } + void kernel_main (void) { + + print_serial("\033[31;42mKernel main called!\n"); + + /** initialize terminal interface */ kterm_init(); + /** Setup the MMU **/ + kterm_writestring("Starting MMU...\n"); + auto mmu = MMU(); + mmu.enable(); + kterm_writestring("MMU enabled!\n"); + + + + /** Wrtite stuff to the screen to test the terminal**/ kterm_writestring("Hello world!\n"); kterm_writestring("We got newline support!\n"); @@ -114,14 +143,11 @@ extern "C" { auto testObject = Test(); testObject.printMe(); - /** Setup the MMU **/ - kterm_writestring("Starting MMU...\n"); - auto mmu = MMU(); - mmu.enable(); - kterm_writestring("MMU enabled!\n"); - + /** test interrupt handlers **/ + //asm volatile ("int $0x3"); + //asm volatile ("int $0x4"); /** Lets start using the serial port for debugging .. **/ // Hopefully once we go into realmode or do something that @@ -129,7 +155,6 @@ extern "C" { // some situational awareness //Serial serialbus = Serial::init(); - test_serial(); } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 080869a..4b2b306 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -1,7 +1,8 @@ #pragma once extern "C" { -#include "../libc/include/string.h" -#include "arch/i386/tty/kterm.h" + #include "../libc/include/string.h" + #include "arch/i386/tty/kterm.h" } #include "MMU.h" #include "io.h" +#include "idt.h" \ No newline at end of file -- 2.39.5 From 0d0c06ab09e6c4058d0da247e9cb6452a9cc3546 Mon Sep 17 00:00:00 2001 From: Nigel Barink Date: Wed, 12 May 2021 23:48:06 +0100 Subject: [PATCH 002/115] Working on PIC --- src/kernel/arch/i386/boot.s | 300 ++++++++++++++++++++++++------------ src/kernel/idt.cpp | 85 ++++++---- src/kernel/idt.h | 50 ++++-- src/kernel/io.cpp | 10 +- src/kernel/io.h | 3 +- src/kernel/kernel.cpp | 49 +++++- src/kernel/kernel.h | 3 +- 7 files changed, 342 insertions(+), 158 deletions(-) diff --git a/src/kernel/arch/i386/boot.s b/src/kernel/arch/i386/boot.s index 91c47df..5f1b4e8 100644 --- a/src/kernel/arch/i386/boot.s +++ b/src/kernel/arch/i386/boot.s @@ -20,103 +20,13 @@ stack_bottom: .skip 16384 # 16 KiB stack_top: -.text -.globl idt_flush -idt_flush: - mov 4(%esp), %eax - lidt (%eax) - ret - -.text -.globl enablePaging -enablePaging: - push %ebp - mov %esp, %ebp - mov %cr0, %eax - or $0x80000000, %eax - mov %eax, %cr0 - mov %ebp, %esp - pop %ebp - ret - -.text -.globl loadPageDirectory -loadPageDirectory: - push %ebp - mov %esp, %ebp - mov 8(%esp), %eax - mov %eax, %cr3 - mov %ebp, %esp - pop %ebp - ret - - .section .text -.global _start -.type _start, @function -_start: - /*Setup the stack pointer to point to the beginning of our stack */ - /* I believe its a hight address growing down to lower adress for the stack on x86*/ - mov $stack_top, %esp - call early_main - - load_gdt: - lgdt gdt - - # set the segment selecters - - movw $0x10, %ax - movw %ax, %ds - movw %ax, %es - movw %ax, %fs - movw %ax, %gs - movw %ax, %ss - ljmp $0x08, $flush - - flush: - #load idt - call init_idt - - # Try enable A20 - # mov $0x2401, %ax - # int $0x15 - - - # enable protected mode - mov %cr0, %eax - or $1, %eax - mov %eax, %cr0 - - - call kernel_main - - - cli - 1: hlt - jmp 1b - - - - - /* Tell processor to use our gdt*/ - gdt: - .word (gdt_end - gdt_start -1) # Size of the GDT in bytes minus 1 for math reasons - .int gdt_start # linear address of our GDT - - - - -.att_syntax - - -.size _start, . - _start - /* * Interupt handlers */ - -.text +# NOTE: I have no clue how I should use these macros. +# Have tried to use them in a myriad of ways, none would actually work .macro irq_NoErrCode code:req .globl irq\code irq\code: @@ -126,7 +36,6 @@ _start: jmp irq_common .endm -.text .macro irq_ErrCode code .globl irq\code irq\code: @@ -135,8 +44,6 @@ _start: jmp irq_common .endm - - .globl irq0 irq0: cli @@ -362,11 +269,120 @@ irq31: jmp irq_common +.globl irq0 +irq0: + cli + push $0 + push $0 + jmp irq_common + +.globl irq1 +irq1: + cli + push $0 + push $1 + jmp irq_common + +.globl irq2 +irq2: + cli + push $0 + push $2 + jmp irq_common + +.globl irq3 +irq3: + cli + push $0 + push $3 + jmp irq_common + +.globl irq4 +irq4: + cli + push $0 + push $4 + jmp irq_common + +.globl irq5 +irq5: + cli + push $0 + push $5 + jmp irq_common + +.globl irq6 +irq6: + cli + push $0 + push $6 + jmp irq_common + +.globl irq7 +irq7: + cli + push $0 + push $7 + jmp irq_common + +.globl irq8 +irq8: + cli + push $0 + push $8 + jmp irq_common + +.globl irq9 +irq9: + cli + push $0 + push $9 + jmp irq_common + +.globl irq10 +irq10: + cli + push $0 + push $10 + jmp irq_common + +.globl irq11 +irq11: + cli + push $0 + push $11 + jmp irq_common + +.globl irq12 +irq12: + cli + push $0 + push $12 + jmp irq_common + +.globl irq13 +irq13: + cli + push $0 + push $13 + jmp irq_common + +.globl irq14 +irq14: + cli + push $0 + push $14 + jmp irq_common + +.globl irq15 +irq15: + cli + push $0 + push $15 + jmp irq_common - -.text irq_common: pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax @@ -396,6 +412,96 @@ irq_common: sti iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP +.globl idt_flush +idt_flush: + mov 4(%esp), %eax + lidt (%eax) + ret + +.globl enablePaging +enablePaging: + push %ebp + mov %esp, %ebp + mov %cr0, %eax + or $0x80000000, %eax + mov %eax, %cr0 + mov %ebp, %esp + pop %ebp + ret + +.globl loadPageDirectory +loadPageDirectory: + push %ebp + mov %esp, %ebp + mov 8(%esp), %eax + mov %eax, %cr3 + mov %ebp, %esp + pop %ebp + ret + +.global _start +.type _start, @function +_start: + /*Setup the stack pointer to point to the beginning of our stack */ + /* I believe its a hight address growing down to lower adress for the stack on x86*/ + mov $stack_top, %esp + call early_main + cli + load_gdt: + lgdt gdt + + # set the segment selecters + + movw $0x10, %ax + movw %ax, %ds + movw %ax, %es + movw %ax, %fs + movw %ax, %gs + movw %ax, %ss + ljmp $0x08, $flush + + flush: + + + #load idt + call init_idt + sti + + # Try enable A20 + # mov $0x2401, %ax + # int $0x15 + + + # enable protected mode + mov %cr0, %eax + or $1, %eax + mov %eax, %cr0 + + + call kernel_main + + + cli + 1: hlt + jmp 1b + + + + + /* Tell processor to use our gdt*/ + gdt: + .word (gdt_end - gdt_start -1) # Size of the GDT in bytes minus 1 for math reasons + .int gdt_start # linear address of our GDT + + + + +.att_syntax + + +.size _start, . - _start + + /* * Create the GDT */ diff --git a/src/kernel/idt.cpp b/src/kernel/idt.cpp index 2ba7165..abe1c4d 100644 --- a/src/kernel/idt.cpp +++ b/src/kernel/idt.cpp @@ -14,7 +14,7 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ void irq_handler (registers regs) { - kterm_writestring("received interrupt!"); + kterm_writestring("received interrupt!\n"); } @@ -26,39 +26,58 @@ void init_idt(){ // TODO: Set everything to zero first - set_id_entry(0, (uint32_t) irq0 , 0x08, 0x8E); - set_id_entry(1, (uint32_t) irq1 , 0x08, 0x8E); - set_id_entry(2, (uint32_t) irq2 , 0x08, 0x8E); - set_id_entry(3, (uint32_t) irq3 , 0x08, 0x8E); - set_id_entry(4, (uint32_t) irq4 , 0x08, 0x8E); - set_id_entry(5, (uint32_t) irq5 , 0x08, 0x8E); - set_id_entry(6, (uint32_t) irq6 , 0x08, 0x8E); - set_id_entry(7, (uint32_t) irq7 , 0x08, 0x8E); - set_id_entry(8, (uint32_t) irq8 , 0x08, 0x8E); - set_id_entry(9, (uint32_t) irq9 , 0x08, 0x8E); - set_id_entry(10, (uint32_t) irq10 , 0x08, 0x8E); - set_id_entry(11, (uint32_t) irq11 , 0x08, 0x8E); - set_id_entry(12, (uint32_t) irq12 , 0x08, 0x8E); - set_id_entry(13, (uint32_t) irq13 , 0x08, 0x8E); - set_id_entry(14, (uint32_t) irq14 , 0x08, 0x8E); - set_id_entry(15, (uint32_t) irq15 , 0x08, 0x8E); - set_id_entry(16, (uint32_t) irq16 , 0x08, 0x8E); - set_id_entry(17, (uint32_t) irq17 , 0x08, 0x8E); - set_id_entry(18, (uint32_t) irq18 , 0x08, 0x8E); - set_id_entry(19, (uint32_t) irq19 , 0x08, 0x8E); - set_id_entry(20, (uint32_t) irq20 , 0x08, 0x8E); - set_id_entry(21, (uint32_t) irq21 , 0x08, 0x8E); - set_id_entry(22, (uint32_t) irq22 , 0x08, 0x8E); - set_id_entry(23, (uint32_t) irq23 , 0x08, 0x8E); - set_id_entry(24, (uint32_t) irq24 , 0x08, 0x8E); - set_id_entry(25, (uint32_t) irq25 , 0x08, 0x8E); - set_id_entry(26, (uint32_t) irq26 , 0x08, 0x8E); - set_id_entry(27, (uint32_t) irq27 , 0x08, 0x8E); - set_id_entry(28, (uint32_t) irq28 , 0x08, 0x8E); - set_id_entry(29, (uint32_t) irq29 , 0x08, 0x8E); - set_id_entry(30, (uint32_t) irq30 , 0x08, 0x8E); - set_id_entry(31, (uint32_t) irq31 , 0x08, 0x8E); + set_id_entry(0, (uint32_t) irs0 , 0x08, 0x8E); + set_id_entry(1, (uint32_t) irs1 , 0x08, 0x8E); + set_id_entry(2, (uint32_t) irs2 , 0x08, 0x8E); + set_id_entry(3, (uint32_t) irs3 , 0x08, 0x8E); + set_id_entry(4, (uint32_t) irs4 , 0x08, 0x8E); + set_id_entry(5, (uint32_t) irs5 , 0x08, 0x8E); + set_id_entry(6, (uint32_t) irs6 , 0x08, 0x8E); + set_id_entry(7, (uint32_t) irs7 , 0x08, 0x8E); + set_id_entry(8, (uint32_t) irs8 , 0x08, 0x8E); + set_id_entry(9, (uint32_t) irs9 , 0x08, 0x8E); + set_id_entry(10, (uint32_t) irs10 , 0x08, 0x8E); + set_id_entry(11, (uint32_t) irs11 , 0x08, 0x8E); + set_id_entry(12, (uint32_t) irs12 , 0x08, 0x8E); + set_id_entry(13, (uint32_t) irs13 , 0x08, 0x8E); + set_id_entry(14, (uint32_t) irs14 , 0x08, 0x8E); + set_id_entry(15, (uint32_t) irs15 , 0x08, 0x8E); + set_id_entry(16, (uint32_t) irs16 , 0x08, 0x8E); + set_id_entry(17, (uint32_t) irs17 , 0x08, 0x8E); + set_id_entry(18, (uint32_t) irs18 , 0x08, 0x8E); + set_id_entry(19, (uint32_t) irs19 , 0x08, 0x8E); + set_id_entry(20, (uint32_t) irs20 , 0x08, 0x8E); + set_id_entry(21, (uint32_t) irs21 , 0x08, 0x8E); + set_id_entry(22, (uint32_t) irs22 , 0x08, 0x8E); + set_id_entry(23, (uint32_t) irs23 , 0x08, 0x8E); + set_id_entry(24, (uint32_t) irs24 , 0x08, 0x8E); + set_id_entry(25, (uint32_t) irs25 , 0x08, 0x8E); + set_id_entry(26, (uint32_t) irs26 , 0x08, 0x8E); + set_id_entry(27, (uint32_t) irs27 , 0x08, 0x8E); + set_id_entry(28, (uint32_t) irs28 , 0x08, 0x8E); + set_id_entry(29, (uint32_t) irs29 , 0x08, 0x8E); + set_id_entry(30, (uint32_t) irs30 , 0x08, 0x8E); + set_id_entry(31, (uint32_t) irs31 , 0x08, 0x8E); + + // pic IRQ Table + set_id_entry(32, (uint32_t)irq0, 0x08, 0x8E); + set_id_entry(33, (uint32_t)irq1, 0x08, 0x8E); + set_id_entry(34, (uint32_t)irq2, 0x08, 0x8E); + set_id_entry(35, (uint32_t)irq3, 0x08, 0x8E); + set_id_entry(36, (uint32_t)irq4, 0x08, 0x8E); + set_id_entry(37, (uint32_t)irq5, 0x08, 0x8E); + set_id_entry(38, (uint32_t)irq6, 0x08, 0x8E); + set_id_entry(39, (uint32_t)irq7, 0x08, 0x8E); + set_id_entry(40, (uint32_t)irq8, 0x08, 0x8E); + set_id_entry(41, (uint32_t)irq9, 0x08, 0x8E); + set_id_entry(42, (uint32_t)irq10, 0x08, 0x8E); + set_id_entry(43, (uint32_t)irq11, 0x08, 0x8E); + set_id_entry(44, (uint32_t)irq12, 0x08, 0x8E); + set_id_entry(45, (uint32_t)irq13, 0x08, 0x8E); + set_id_entry(46, (uint32_t)irq14, 0x08, 0x8E); + set_id_entry(47, (uint32_t)irq15, 0x08, 0x8E); + idt_flush((uint32_t)&idt_ptr); } diff --git a/src/kernel/idt.h b/src/kernel/idt.h index 78b9a3d..d239f43 100644 --- a/src/kernel/idt.h +++ b/src/kernel/idt.h @@ -31,6 +31,39 @@ extern "C" { void irq_handler (registers regs); + extern void irs0 (); + extern void irs1 (); + extern void irs2 (); + extern void irs3 (); + extern void irs4 (); + extern void irs5 (); + extern void irs6 (); + extern void irs7 (); + extern void irs8 (); + extern void irs9 (); + extern void irs10 (); + extern void irs11 (); + extern void irs12 (); + extern void irs13 (); + extern void irs14 (); + extern void irs15 (); + extern void irs16 (); + extern void irs17 (); + extern void irs18 (); + extern void irs19 (); + extern void irs20 (); + extern void irs21 (); + extern void irs22 (); + extern void irs23 (); + extern void irs24 (); + extern void irs25 (); + extern void irs26 (); + extern void irs27 (); + extern void irs28 (); + extern void irs29 (); + extern void irs30 (); + extern void irs31 (); + extern void irq0 (); extern void irq1 (); extern void irq2 (); @@ -47,23 +80,6 @@ extern "C" { extern void irq13 (); extern void irq14 (); extern void irq15 (); - extern void irq16 (); - extern void irq17 (); - extern void irq18 (); - extern void irq19 (); - extern void irq20 (); - extern void irq21 (); - extern void irq22 (); - extern void irq23 (); - extern void irq24 (); - extern void irq25 (); - extern void irq26 (); - extern void irq27 (); - extern void irq28 (); - extern void irq29 (); - extern void irq30 (); - extern void irq31 (); - diff --git a/src/kernel/io.cpp b/src/kernel/io.cpp index 11dbc3b..f9ed07d 100644 --- a/src/kernel/io.cpp +++ b/src/kernel/io.cpp @@ -56,4 +56,12 @@ void outsw(unsigned short , const void *, void outsl(unsigned short , const void *, unsigned long ){ - } \ No newline at end of file + } + +void io_wait(void) +{ + /* TODO: This is probably fragile. */ + asm volatile ( "jmp 1f\n\t" + "1:jmp 2f\n\t" + "2:" ); +} \ No newline at end of file diff --git a/src/kernel/io.h b/src/kernel/io.h index 8b729f9..c7fd561 100644 --- a/src/kernel/io.h +++ b/src/kernel/io.h @@ -40,4 +40,5 @@ void outsb(unsigned short port, const void *addr, void outsw(unsigned short port, const void *addr, unsigned long count); void outsl(unsigned short port, const void *addr, - unsigned long count); \ No newline at end of file + unsigned long count); +void io_wait(); \ No newline at end of file diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index ddb9402..4360aac 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -107,22 +107,37 @@ extern "C" { init_serial(); print_serial("\033[31;42mEarly main called!\n"); + print_serial("Remapping PIC\n"); + // remap the PIC IRQ table + outb(0x20, 0x11); + outb(0xA0, 0x11); + outb(0x21, 0x20); + outb(0xA1, 0x28); + outb(0x21, 0x04); + outb(0xA1, 0x02); + outb(0x21, 0x01); + outb(0xA1, 0x01); + outb(0x21, 0x0); + outb(0xA1, 0x0); + + + print_serial("done... \n"); } void kernel_main (void) { - - print_serial("\033[31;42mKernel main called!\n"); + + print_serial("Kernel main called!\n"); /** initialize terminal interface */ kterm_init(); /** Setup the MMU **/ - kterm_writestring("Starting MMU...\n"); - auto mmu = MMU(); - mmu.enable(); - kterm_writestring("MMU enabled!\n"); + //kterm_writestring("Starting MMU...\n"); + //auto mmu = MMU(); + //mmu.enable(); + //kterm_writestring("MMU enabled!\n"); @@ -143,11 +158,29 @@ extern "C" { auto testObject = Test(); testObject.printMe(); + IRQ_set_mask(0); + IRQ_set_mask(1); + IRQ_set_mask(2); + IRQ_set_mask(3); + IRQ_set_mask(4); + IRQ_set_mask(5); + IRQ_set_mask(6); + IRQ_set_mask(7); + IRQ_set_mask(8); + IRQ_set_mask(9); + IRQ_set_mask(10); + IRQ_set_mask(11); + IRQ_set_mask(12); + IRQ_set_mask(13); + IRQ_set_mask(14); + IRQ_set_mask(15); + + /** test interrupt handlers **/ - //asm volatile ("int $0x3"); + asm volatile ("int $0x03"); - //asm volatile ("int $0x4"); + //asm volatile ("int $4"); /** Lets start using the serial port for debugging .. **/ // Hopefully once we go into realmode or do something that diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 4b2b306..50fc89b 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -5,4 +5,5 @@ extern "C" { } #include "MMU.h" #include "io.h" -#include "idt.h" \ No newline at end of file +#include "idt.h" +#include "pic.h" \ No newline at end of file -- 2.39.5 From 28ac6a05afed8ce88c00208bc987073e0d65ef3d Mon Sep 17 00:00:00 2001 From: nigel Date: Wed, 12 May 2021 20:43:15 -0400 Subject: [PATCH 003/115] Interrupts are working.. processor no longer resets --- Makefile | 2 +- src/kernel/arch/i386/boot.s | 112 -------------------- src/kernel/idt.cpp | 205 +++++++++++++++++++++++++++--------- src/kernel/idt.h | 73 +++++++------ src/kernel/kernel.cpp | 14 ++- src/kernel/kernel.h | 2 +- 6 files changed, 207 insertions(+), 201 deletions(-) diff --git a/Makefile b/Makefile index f329535..3aec044 100644 --- a/Makefile +++ b/Makefile @@ -24,7 +24,7 @@ all: clean build build: build_kernel run run: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio + $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std build_kernel: $(OBJ_LINK_LIST) diff --git a/src/kernel/arch/i386/boot.s b/src/kernel/arch/i386/boot.s index 5f1b4e8..0ea809c 100644 --- a/src/kernel/arch/i386/boot.s +++ b/src/kernel/arch/i386/boot.s @@ -138,7 +138,6 @@ irq12: .globl irq13 irq13: cli - push $0 push $13 jmp irq_common @@ -269,117 +268,6 @@ irq31: jmp irq_common -.globl irq0 -irq0: - cli - push $0 - push $0 - jmp irq_common - -.globl irq1 -irq1: - cli - push $0 - push $1 - jmp irq_common - -.globl irq2 -irq2: - cli - push $0 - push $2 - jmp irq_common - -.globl irq3 -irq3: - cli - push $0 - push $3 - jmp irq_common - -.globl irq4 -irq4: - cli - push $0 - push $4 - jmp irq_common - -.globl irq5 -irq5: - cli - push $0 - push $5 - jmp irq_common - -.globl irq6 -irq6: - cli - push $0 - push $6 - jmp irq_common - -.globl irq7 -irq7: - cli - push $0 - push $7 - jmp irq_common - -.globl irq8 -irq8: - cli - push $0 - push $8 - jmp irq_common - -.globl irq9 -irq9: - cli - push $0 - push $9 - jmp irq_common - -.globl irq10 -irq10: - cli - push $0 - push $10 - jmp irq_common - -.globl irq11 -irq11: - cli - push $0 - push $11 - jmp irq_common - -.globl irq12 -irq12: - cli - push $0 - push $12 - jmp irq_common - -.globl irq13 -irq13: - cli - push $0 - push $13 - jmp irq_common - -.globl irq14 -irq14: - cli - push $0 - push $14 - jmp irq_common - -.globl irq15 -irq15: - cli - push $0 - push $15 - jmp irq_common diff --git a/src/kernel/idt.cpp b/src/kernel/idt.cpp index abe1c4d..c32d6e4 100644 --- a/src/kernel/idt.cpp +++ b/src/kernel/idt.cpp @@ -1,5 +1,103 @@ #include "idt.h" +static void itoa (char *buf, int base, int d) { + char *p = buf; + char *p1, *p2; + unsigned long ud = d; + int divisor = 10; + if ( base == 'd' && d < 0){ + *p++ = '-'; + buf++; + ud = -d; + } else if (base == 'x'){ + divisor = 16; + } + + do { + int remainder = ud % divisor; + + *p++ = (remainder < 10 ) ? remainder + '0' : remainder + 'a' -10; + } while(ud /= divisor); + + /*terminate buf*/ + *p =0; + p1 = buf; + p2 = p -1; + + while (p1 < p2) + { + char tmp = *p1; + *p1 = *p2; + *p2 = tmp; + p1++; + p2--; + + } + +} + +void printf ( const char *format, ...) { + + AS_KERNEL(); + char **arg = (char **)&format; + int c; + char buf[20]; + + arg++; + + while ((c = *format++) != 0){ + if( c != '%') + kterm_put(c); + else{ + char *p, *p2; + int pad0 = 0, pad = 0; + + c = *format++; + if(c =='0'){ + pad0 = 1; + c = *format++; + } + + if ( c >= '0' && c <= '9'){ + pad = c - '0'; + c = *format++; + } + + switch (c) + { + case 'd': + + case 'u': + case 'x': + itoa(buf, c, *((int *) arg++)); + + p = buf; + goto string; + break; + + case 's': + p = *arg++; + if(!p) + p = "(null)"; + + string: + for (p2 = p; *p2; p2++); + for (; p2 < p + pad; p2++) + kterm_put(pad0 ? '0': ' '); + while (*p) + kterm_put(*p++); + break; + + + default: + kterm_put(*((int *)arg++)); + break; + } + } + } +} + + IDT_entry idt_table[256]; IDT_ptr idt_ptr; @@ -15,6 +113,15 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ void irq_handler (registers regs) { kterm_writestring("received interrupt!\n"); + + + printf(" Interrupt number: %d \n", regs.int_no); + + if( regs.int_no == 13){ + printf(" Error code: %d \n", regs.err_code); + + } + } @@ -26,57 +133,57 @@ void init_idt(){ // TODO: Set everything to zero first - set_id_entry(0, (uint32_t) irs0 , 0x08, 0x8E); - set_id_entry(1, (uint32_t) irs1 , 0x08, 0x8E); - set_id_entry(2, (uint32_t) irs2 , 0x08, 0x8E); - set_id_entry(3, (uint32_t) irs3 , 0x08, 0x8E); - set_id_entry(4, (uint32_t) irs4 , 0x08, 0x8E); - set_id_entry(5, (uint32_t) irs5 , 0x08, 0x8E); - set_id_entry(6, (uint32_t) irs6 , 0x08, 0x8E); - set_id_entry(7, (uint32_t) irs7 , 0x08, 0x8E); - set_id_entry(8, (uint32_t) irs8 , 0x08, 0x8E); - set_id_entry(9, (uint32_t) irs9 , 0x08, 0x8E); - set_id_entry(10, (uint32_t) irs10 , 0x08, 0x8E); - set_id_entry(11, (uint32_t) irs11 , 0x08, 0x8E); - set_id_entry(12, (uint32_t) irs12 , 0x08, 0x8E); - set_id_entry(13, (uint32_t) irs13 , 0x08, 0x8E); - set_id_entry(14, (uint32_t) irs14 , 0x08, 0x8E); - set_id_entry(15, (uint32_t) irs15 , 0x08, 0x8E); - set_id_entry(16, (uint32_t) irs16 , 0x08, 0x8E); - set_id_entry(17, (uint32_t) irs17 , 0x08, 0x8E); - set_id_entry(18, (uint32_t) irs18 , 0x08, 0x8E); - set_id_entry(19, (uint32_t) irs19 , 0x08, 0x8E); - set_id_entry(20, (uint32_t) irs20 , 0x08, 0x8E); - set_id_entry(21, (uint32_t) irs21 , 0x08, 0x8E); - set_id_entry(22, (uint32_t) irs22 , 0x08, 0x8E); - set_id_entry(23, (uint32_t) irs23 , 0x08, 0x8E); - set_id_entry(24, (uint32_t) irs24 , 0x08, 0x8E); - set_id_entry(25, (uint32_t) irs25 , 0x08, 0x8E); - set_id_entry(26, (uint32_t) irs26 , 0x08, 0x8E); - set_id_entry(27, (uint32_t) irs27 , 0x08, 0x8E); - set_id_entry(28, (uint32_t) irs28 , 0x08, 0x8E); - set_id_entry(29, (uint32_t) irs29 , 0x08, 0x8E); - set_id_entry(30, (uint32_t) irs30 , 0x08, 0x8E); - set_id_entry(31, (uint32_t) irs31 , 0x08, 0x8E); - + set_id_entry(0, (uint32_t) irq0 , 0x08, 0x8E); + set_id_entry(1, (uint32_t) irq1 , 0x08, 0x8E); + set_id_entry(2, (uint32_t) irq2 , 0x08, 0x8E); + set_id_entry(3, (uint32_t) irq3 , 0x08, 0x8E); + set_id_entry(4, (uint32_t) irq4 , 0x08, 0x8E); + set_id_entry(5, (uint32_t) irq5 , 0x08, 0x8E); + set_id_entry(6, (uint32_t) irq6 , 0x08, 0x8E); + set_id_entry(7, (uint32_t) irq7 , 0x08, 0x8E); + set_id_entry(8, (uint32_t) irq8 , 0x08, 0x8E); + set_id_entry(9, (uint32_t) irq9 , 0x08, 0x8E); + set_id_entry(10, (uint32_t) irq10 , 0x08, 0x8E); + set_id_entry(11, (uint32_t) irq11 , 0x08, 0x8E); + set_id_entry(12, (uint32_t) irq12 , 0x08, 0x8E); + set_id_entry(13, (uint32_t) irq13 , 0x08, 0x8E); + set_id_entry(14, (uint32_t) irq14 , 0x08, 0x8E); + set_id_entry(15, (uint32_t) irq15 , 0x08, 0x8E); + set_id_entry(16, (uint32_t) irq16 , 0x08, 0x8E); + set_id_entry(17, (uint32_t) irq17 , 0x08, 0x8E); + set_id_entry(18, (uint32_t) irq18 , 0x08, 0x8E); + set_id_entry(19, (uint32_t) irq19 , 0x08, 0x8E); + set_id_entry(20, (uint32_t) irq20 , 0x08, 0x8E); + set_id_entry(21, (uint32_t) irq21 , 0x08, 0x8E); + set_id_entry(22, (uint32_t) irq22 , 0x08, 0x8E); + set_id_entry(23, (uint32_t) irq23 , 0x08, 0x8E); + set_id_entry(24, (uint32_t) irq24 , 0x08, 0x8E); + set_id_entry(25, (uint32_t) irq25 , 0x08, 0x8E); + set_id_entry(26, (uint32_t) irq26 , 0x08, 0x8E); + set_id_entry(27, (uint32_t) irq27 , 0x08, 0x8E); + set_id_entry(28, (uint32_t) irq28 , 0x08, 0x8E); + set_id_entry(29, (uint32_t) irq29 , 0x08, 0x8E); + set_id_entry(30, (uint32_t) irq30 , 0x08, 0x8E); + set_id_entry(31, (uint32_t) irq31 , 0x08, 0x8E); +/* // pic IRQ Table - set_id_entry(32, (uint32_t)irq0, 0x08, 0x8E); - set_id_entry(33, (uint32_t)irq1, 0x08, 0x8E); - set_id_entry(34, (uint32_t)irq2, 0x08, 0x8E); - set_id_entry(35, (uint32_t)irq3, 0x08, 0x8E); - set_id_entry(36, (uint32_t)irq4, 0x08, 0x8E); - set_id_entry(37, (uint32_t)irq5, 0x08, 0x8E); - set_id_entry(38, (uint32_t)irq6, 0x08, 0x8E); - set_id_entry(39, (uint32_t)irq7, 0x08, 0x8E); - set_id_entry(40, (uint32_t)irq8, 0x08, 0x8E); - set_id_entry(41, (uint32_t)irq9, 0x08, 0x8E); - set_id_entry(42, (uint32_t)irq10, 0x08, 0x8E); - set_id_entry(43, (uint32_t)irq11, 0x08, 0x8E); - set_id_entry(44, (uint32_t)irq12, 0x08, 0x8E); - set_id_entry(45, (uint32_t)irq13, 0x08, 0x8E); - set_id_entry(46, (uint32_t)irq14, 0x08, 0x8E); - set_id_entry(47, (uint32_t)irq15, 0x08, 0x8E); + set_id_entry(32, (uint32_t)irs0, 0x08, 0x8E); + set_id_entry(33, (uint32_t)irs1, 0x08, 0x8E); + set_id_entry(34, (uint32_t)irs2, 0x08, 0x8E); + set_id_entry(35, (uint32_t)irs3, 0x08, 0x8E); + set_id_entry(36, (uint32_t)irs4, 0x08, 0x8E); + set_id_entry(37, (uint32_t)irs5, 0x08, 0x8E); + set_id_entry(38, (uint32_t)irs6, 0x08, 0x8E); + set_id_entry(39, (uint32_t)irs7, 0x08, 0x8E); + set_id_entry(40, (uint32_t)irs8, 0x08, 0x8E); + set_id_entry(41, (uint32_t)irs9, 0x08, 0x8E); + set_id_entry(42, (uint32_t)irs10, 0x08, 0x8E); + set_id_entry(43, (uint32_t)irs11, 0x08, 0x8E); + set_id_entry(44, (uint32_t)irs12, 0x08, 0x8E); + set_id_entry(45, (uint32_t)irs13, 0x08, 0x8E); + set_id_entry(46, (uint32_t)irs14, 0x08, 0x8E); + set_id_entry(47, (uint32_t)irs15, 0x08, 0x8E);*/ idt_flush((uint32_t)&idt_ptr); diff --git a/src/kernel/idt.h b/src/kernel/idt.h index d239f43..07c7440 100644 --- a/src/kernel/idt.h +++ b/src/kernel/idt.h @@ -1,7 +1,14 @@ #pragma once #include "stdint.h" +#include "stddef.h" +#include "arch/i386/vga/colors.h" + +#define AS_KERNEL() ( kterm_writestring("[KERNEL]:")) extern "C" void kterm_writestring(const char* data ); +extern "C" void kterm_putat(char, uint8_t, size_t, size_t); +extern "C" void kterm_put(char); + extern "C" { struct __attribute__((__packed__)) IDT_entry { @@ -31,39 +38,6 @@ extern "C" { void irq_handler (registers regs); - extern void irs0 (); - extern void irs1 (); - extern void irs2 (); - extern void irs3 (); - extern void irs4 (); - extern void irs5 (); - extern void irs6 (); - extern void irs7 (); - extern void irs8 (); - extern void irs9 (); - extern void irs10 (); - extern void irs11 (); - extern void irs12 (); - extern void irs13 (); - extern void irs14 (); - extern void irs15 (); - extern void irs16 (); - extern void irs17 (); - extern void irs18 (); - extern void irs19 (); - extern void irs20 (); - extern void irs21 (); - extern void irs22 (); - extern void irs23 (); - extern void irs24 (); - extern void irs25 (); - extern void irs26 (); - extern void irs27 (); - extern void irs28 (); - extern void irs29 (); - extern void irs30 (); - extern void irs31 (); - extern void irq0 (); extern void irq1 (); extern void irq2 (); @@ -80,6 +54,39 @@ extern "C" { extern void irq13 (); extern void irq14 (); extern void irq15 (); + extern void irq16 (); + extern void irq17 (); + extern void irq18 (); + extern void irq19 (); + extern void irq20 (); + extern void irq21 (); + extern void irq22 (); + extern void irq23 (); + extern void irq24 (); + extern void irq25 (); + extern void irq26 (); + extern void irq27 (); + extern void irq28 (); + extern void irq29 (); + extern void irq30 (); + extern void irq31 (); +/* + extern void irq0 (); + extern void irq1 (); + extern void irq2 (); + extern void irq3 (); + extern void irq4 (); + extern void irq5 (); + extern void irq6 (); + extern void irq7 (); + extern void irq8 (); + extern void irq9 (); + extern void irq10 (); + extern void irq11 (); + extern void irq12 (); + extern void irq13 (); + extern void irq14 (); + extern void irq15 ();*/ diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 4360aac..2530c7a 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -9,6 +9,10 @@ void delay(int t){ asm("NOP"); } + + + + class Test { public: Test(); @@ -109,7 +113,7 @@ extern "C" { print_serial("Remapping PIC\n"); // remap the PIC IRQ table - outb(0x20, 0x11); + /*outb(0x20, 0x11); outb(0xA0, 0x11); outb(0x21, 0x20); outb(0xA1, 0x28); @@ -118,7 +122,7 @@ extern "C" { outb(0x21, 0x01); outb(0xA1, 0x01); outb(0x21, 0x0); - outb(0xA1, 0x0); + outb(0xA1, 0x0);*/ print_serial("done... \n"); @@ -158,7 +162,7 @@ extern "C" { auto testObject = Test(); testObject.printMe(); - IRQ_set_mask(0); + /*IRQ_set_mask(0); IRQ_set_mask(1); IRQ_set_mask(2); IRQ_set_mask(3); @@ -174,13 +178,13 @@ extern "C" { IRQ_set_mask(13); IRQ_set_mask(14); IRQ_set_mask(15); - + */ /** test interrupt handlers **/ asm volatile ("int $0x03"); - //asm volatile ("int $4"); + asm volatile ("int $4"); /** Lets start using the serial port for debugging .. **/ // Hopefully once we go into realmode or do something that diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 50fc89b..3b1b0bc 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -6,4 +6,4 @@ extern "C" { #include "MMU.h" #include "io.h" #include "idt.h" -#include "pic.h" \ No newline at end of file +//#include "pic.h" \ No newline at end of file -- 2.39.5 From 592db0ebcf787ac33bf2acb317afa04ef65bfce6 Mon Sep 17 00:00:00 2001 From: Nigel Barink Date: Sun, 16 May 2021 15:53:14 +0100 Subject: [PATCH 004/115] More work on interrupt handling, Started timer interrupt implementation, PIC remapped hopefully successfull --- Makefile | 11 +- README.md | 3 + screenshots/WIP_interruptHandling.png | 3 + src/kernel/arch/i386/boot.s | 426 +++++++++++++++--------- src/kernel/{ => arch/i386/gdt}/gdtc.cpp | 0 src/kernel/{ => arch/i386/gdt}/gdtc.h | 0 src/kernel/{ => arch/i386/idt}/idt.cpp | 111 +++--- src/kernel/arch/i386/idt/idt.h | 81 +++++ src/kernel/arch/i386/pic/pic.cpp | 62 ++++ src/kernel/arch/i386/pic/pic.h | 57 ++++ src/kernel/idt.h | 93 ------ src/kernel/kernel.cpp | 46 +-- src/kernel/kernel.h | 4 +- src/kernel/timer.cpp | 27 ++ src/kernel/timer.h | 6 + 15 files changed, 580 insertions(+), 350 deletions(-) create mode 100644 screenshots/WIP_interruptHandling.png rename src/kernel/{ => arch/i386/gdt}/gdtc.cpp (100%) rename src/kernel/{ => arch/i386/gdt}/gdtc.h (100%) rename src/kernel/{ => arch/i386/idt}/idt.cpp (51%) create mode 100644 src/kernel/arch/i386/idt/idt.h create mode 100644 src/kernel/arch/i386/pic/pic.cpp create mode 100644 src/kernel/arch/i386/pic/pic.h delete mode 100644 src/kernel/idt.h create mode 100644 src/kernel/timer.cpp create mode 100644 src/kernel/timer.h diff --git a/Makefile b/Makefile index 3aec044..aa43673 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/MMU.o $(BUILD_DIR)/idt.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/MMU.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o SRC_DIR = src BUILD_DIR = build @@ -24,7 +24,7 @@ all: clean build build: build_kernel run run: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std + $(EMULATOR) -d int -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std build_kernel: $(OBJ_LINK_LIST) @@ -55,7 +55,12 @@ $(BUILD_DIR)/crtn.o: $(BUILD_DIR)/io.o: $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti + $(BUILD_DIR)/MMU.o: $(CPP) -c $(SRC_DIR)/kernel/MMU.cpp -o $(BUILD_DIR)/MMU.o $(CFLAGS) -fno-exceptions -fno-rtti + $(BUILD_DIR)/idt.o: - $(CPP) -c $(SRC_DIR)/kernel/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file + $(CPP) -c $(SRC_DIR)/kernel/arch/i386/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/pic.o: + $(CPP) -c $(SRC_DIR)/kernel/arch/i386/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/README.md b/README.md index cf263a6..eefdecd 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,9 @@ ________________________ The first scrolling boot screen. 😲 + +W.I.P - Working on interrupt handling + ________________________ ### The goal diff --git a/screenshots/WIP_interruptHandling.png b/screenshots/WIP_interruptHandling.png new file mode 100644 index 0000000..6c22b50 --- /dev/null +++ b/screenshots/WIP_interruptHandling.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfbde3cc43610681eca3f38e56d8af1d0e5d0ad2f465cb743a5b8ea5c3adbe47 +size 16282 diff --git a/src/kernel/arch/i386/boot.s b/src/kernel/arch/i386/boot.s index 0ea809c..17432e4 100644 --- a/src/kernel/arch/i386/boot.s +++ b/src/kernel/arch/i386/boot.s @@ -27,251 +27,365 @@ stack_top: */ # NOTE: I have no clue how I should use these macros. # Have tried to use them in a myriad of ways, none would actually work -.macro irq_NoErrCode code:req - .globl irq\code - irq\code: +.macro irs_NoErrCode code:req + .globl irs\code + irs\code: cli pushb $0 pushb \code - jmp irq_common + jmp irs_common .endm -.macro irq_ErrCode code - .globl irq\code - irq\code: +.macro irs_ErrCode code + .globl irs\code + irs\code: cli pushb \code - jmp irq_common + jmp irs_common .endm +.globl irs0 +irs0: + cli + push $0 + push $0 + jmp irs_common + +.globl irs1 +irs1: + cli + push $0 + push $1 + jmp irs_common + +.globl irs2 +irs2: + cli + push $0 + push $2 + jmp irs_common + +.globl irs3 +irs3: + cli + push $0 + push $3 + jmp irs_common + +.globl irs4 +irs4: + cli + push $0 + push $4 + jmp irs_common + +.globl irs5 +irs5: + cli + push $0 + push $5 + jmp irs_common + +.globl irs6 +irs6: + cli + push $0 + push $6 + jmp irs_common + +.globl irs7 +irs7: + cli + push $0 + push $7 + jmp irs_common + +.globl irs8 +irs8: + cli + push $0 + push $8 + jmp irs_common + +.globl irs9 +irs9: + cli + push $0 + push $9 + jmp irs_common + +.globl irs10 +irs10: + cli + push $0 + push $10 + jmp irs_common + +.globl irs11 +irs11: + cli + push $0 + push $11 + jmp irs_common + +.globl irs12 +irs12: + cli + push $0 + push $12 + jmp irs_common + +.globl irs13 +irs13: + cli + push $13 + jmp irs_common + +.globl irs14 +irs14: + cli + push $0 + push $14 + jmp irs_common + +.globl irs15 +irs15: + cli + push $0 + push $15 + jmp irs_common + +.globl irs16 +irs16: + cli + push $0 + push $16 + jmp irs_common + +.globl irs17 +irs17: + cli + push $0 + push $17 + jmp irs_common + +.globl irs18 +irs18: + cli + push $0 + push $18 + jmp irs_common + +.globl irs19 +irs19: + cli + push $0 + push $19 + jmp irs_common + +.globl irs20 +irs20: + cli + push $0 + push $20 + jmp irs_common + +.globl irs21 +irs21: + cli + push $0 + push $21 + jmp irs_common + +.globl irs22 +irs22: + cli + push $0 + push $22 + jmp irs_common + +.globl irs23 +irs23: + cli + push $0 + push $23 + jmp irs_common + +.globl irs24 +irs24: + cli + push $0 + push $24 + jmp irs_common + +.globl irs25 +irs25: + cli + push $0 + push $25 + jmp irs_common + +.globl irs26 +irs26: + cli + push $0 + push $26 + jmp irs_common + +.globl irs27 +irs27: + cli + push $0 + push $27 + jmp irs_common + +.globl irs28 +irs28: + cli + push $0 + push $28 + jmp irs_common + +.globl irs29 +irs29: + cli + push $0 + push $29 + jmp irs_common + +.globl irs30 +irs30: + cli + push $0 + push $30 + jmp irs_common + +.globl irs31 +irs31: + cli + push $0 + push $31 + jmp irs_common + + + .globl irq0 irq0: cli push $0 - push $0 - jmp irq_common + push $32 + jmp irs_common .globl irq1 irq1: cli push $0 - push $1 - jmp irq_common + push $33 + jmp irs_common .globl irq2 irq2: cli push $0 - push $2 - jmp irq_common + push $34 + jmp irs_common .globl irq3 irq3: cli push $0 - push $3 - jmp irq_common + push $35 + jmp irs_common .globl irq4 irq4: cli push $0 - push $4 - jmp irq_common + push $36 + jmp irs_common .globl irq5 irq5: cli push $0 - push $5 - jmp irq_common + push $37 + jmp irs_common .globl irq6 irq6: cli push $0 - push $6 - jmp irq_common + push $38 + jmp irs_common .globl irq7 irq7: cli push $0 - push $7 - jmp irq_common + push $39 + jmp irs_common .globl irq8 irq8: cli push $0 - push $8 - jmp irq_common + push $40 + jmp irs_common .globl irq9 irq9: cli push $0 - push $9 - jmp irq_common + push $41 + jmp irs_common .globl irq10 irq10: cli push $0 - push $10 - jmp irq_common + push $42 + jmp irs_common .globl irq11 irq11: cli push $0 - push $11 - jmp irq_common + push $43 + jmp irs_common + .globl irq12 irq12: cli push $0 - push $12 - jmp irq_common + push $44 + jmp irs_common .globl irq13 irq13: cli - push $13 - jmp irq_common + push $0 + push $45 + jmp irs_common .globl irq14 irq14: cli push $0 - push $14 - jmp irq_common + push $46 + jmp irs_common .globl irq15 irq15: cli push $0 - push $15 - jmp irq_common - -.globl irq16 -irq16: - cli - push $0 - push $16 - jmp irq_common - -.globl irq17 -irq17: - cli - push $0 - push $17 - jmp irq_common - -.globl irq18 -irq18: - cli - push $0 - push $18 - jmp irq_common - -.globl irq19 -irq19: - cli - push $0 - push $19 - jmp irq_common - -.globl irq20 -irq20: - cli - push $0 - push $20 - jmp irq_common - -.globl irq21 -irq21: - cli - push $0 - push $21 - jmp irq_common - -.globl irq22 -irq22: - cli - push $0 - push $22 - jmp irq_common - -.globl irq23 -irq23: - cli - push $0 - push $23 - jmp irq_common - -.globl irq24 -irq24: - cli - push $0 - push $24 - jmp irq_common - -.globl irq25 -irq25: - cli - push $0 - push $25 - jmp irq_common - -.globl irq26 -irq26: - cli - push $0 - push $26 - jmp irq_common - -.globl irq27 -irq27: - cli - push $0 - push $27 - jmp irq_common - -.globl irq28 -irq28: - cli - push $0 - push $28 - jmp irq_common - -.globl irq29 -irq29: - cli - push $0 - push $29 - jmp irq_common - -.globl irq30 -irq30: - cli - push $0 - push $30 - jmp irq_common - -.globl irq31 -irq31: - cli - push $0 - push $31 - jmp irq_common + push $47 + jmp irs_common - -irq_common: +irs_common: pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax @@ -286,7 +400,7 @@ irq_common: mov %ax, %fs mov %ax, %gs - call irq_handler + call irs_handler pop %eax @@ -296,7 +410,7 @@ irq_common: mov %ax, %gs popa - add $8, %esp # cleans push error and irq code + add $8, %esp # cleans push error and irs code sti iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP diff --git a/src/kernel/gdtc.cpp b/src/kernel/arch/i386/gdt/gdtc.cpp similarity index 100% rename from src/kernel/gdtc.cpp rename to src/kernel/arch/i386/gdt/gdtc.cpp diff --git a/src/kernel/gdtc.h b/src/kernel/arch/i386/gdt/gdtc.h similarity index 100% rename from src/kernel/gdtc.h rename to src/kernel/arch/i386/gdt/gdtc.h diff --git a/src/kernel/idt.cpp b/src/kernel/arch/i386/idt/idt.cpp similarity index 51% rename from src/kernel/idt.cpp rename to src/kernel/arch/i386/idt/idt.cpp index c32d6e4..d515272 100644 --- a/src/kernel/idt.cpp +++ b/src/kernel/arch/i386/idt/idt.cpp @@ -111,10 +111,9 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ }; -void irq_handler (registers regs) { +void irs_handler (registers regs) { kterm_writestring("received interrupt!\n"); - - + printf(" Interrupt number: %d \n", regs.int_no); if( regs.int_no == 13){ @@ -125,6 +124,10 @@ void irq_handler (registers regs) { } + + + + void init_idt(){ // Initialise the IDT pointer idt_ptr.length = sizeof(IDT_entry) * 255; @@ -133,57 +136,61 @@ void init_idt(){ // TODO: Set everything to zero first - set_id_entry(0, (uint32_t) irq0 , 0x08, 0x8E); - set_id_entry(1, (uint32_t) irq1 , 0x08, 0x8E); - set_id_entry(2, (uint32_t) irq2 , 0x08, 0x8E); - set_id_entry(3, (uint32_t) irq3 , 0x08, 0x8E); - set_id_entry(4, (uint32_t) irq4 , 0x08, 0x8E); - set_id_entry(5, (uint32_t) irq5 , 0x08, 0x8E); - set_id_entry(6, (uint32_t) irq6 , 0x08, 0x8E); - set_id_entry(7, (uint32_t) irq7 , 0x08, 0x8E); - set_id_entry(8, (uint32_t) irq8 , 0x08, 0x8E); - set_id_entry(9, (uint32_t) irq9 , 0x08, 0x8E); - set_id_entry(10, (uint32_t) irq10 , 0x08, 0x8E); - set_id_entry(11, (uint32_t) irq11 , 0x08, 0x8E); - set_id_entry(12, (uint32_t) irq12 , 0x08, 0x8E); - set_id_entry(13, (uint32_t) irq13 , 0x08, 0x8E); - set_id_entry(14, (uint32_t) irq14 , 0x08, 0x8E); - set_id_entry(15, (uint32_t) irq15 , 0x08, 0x8E); - set_id_entry(16, (uint32_t) irq16 , 0x08, 0x8E); - set_id_entry(17, (uint32_t) irq17 , 0x08, 0x8E); - set_id_entry(18, (uint32_t) irq18 , 0x08, 0x8E); - set_id_entry(19, (uint32_t) irq19 , 0x08, 0x8E); - set_id_entry(20, (uint32_t) irq20 , 0x08, 0x8E); - set_id_entry(21, (uint32_t) irq21 , 0x08, 0x8E); - set_id_entry(22, (uint32_t) irq22 , 0x08, 0x8E); - set_id_entry(23, (uint32_t) irq23 , 0x08, 0x8E); - set_id_entry(24, (uint32_t) irq24 , 0x08, 0x8E); - set_id_entry(25, (uint32_t) irq25 , 0x08, 0x8E); - set_id_entry(26, (uint32_t) irq26 , 0x08, 0x8E); - set_id_entry(27, (uint32_t) irq27 , 0x08, 0x8E); - set_id_entry(28, (uint32_t) irq28 , 0x08, 0x8E); - set_id_entry(29, (uint32_t) irq29 , 0x08, 0x8E); - set_id_entry(30, (uint32_t) irq30 , 0x08, 0x8E); - set_id_entry(31, (uint32_t) irq31 , 0x08, 0x8E); + set_id_entry(0, (uint32_t) irs0 , 0x08, 0x8E); + set_id_entry(1, (uint32_t) irs1 , 0x08, 0x8E); + set_id_entry(2, (uint32_t) irs2 , 0x08, 0x8E); + set_id_entry(3, (uint32_t) irs3 , 0x08, 0x8E); + set_id_entry(4, (uint32_t) irs4 , 0x08, 0x8E); + set_id_entry(5, (uint32_t) irs5 , 0x08, 0x8E); + set_id_entry(6, (uint32_t) irs6 , 0x08, 0x8E); + set_id_entry(7, (uint32_t) irs7 , 0x08, 0x8E); + set_id_entry(8, (uint32_t) irs8 , 0x08, 0x8E); + set_id_entry(9, (uint32_t) irs9 , 0x08, 0x8E); + set_id_entry(10, (uint32_t) irs10 , 0x08, 0x8E); + set_id_entry(11, (uint32_t) irs11 , 0x08, 0x8E); + set_id_entry(12, (uint32_t) irs12 , 0x08, 0x8E); + set_id_entry(13, (uint32_t) irs13 , 0x08, 0x8E); + set_id_entry(14, (uint32_t) irs14 , 0x08, 0x8E); + set_id_entry(15, (uint32_t) irs15 , 0x08, 0x8E); + set_id_entry(16, (uint32_t) irs16 , 0x08, 0x8E); + set_id_entry(17, (uint32_t) irs17 , 0x08, 0x8E); + set_id_entry(18, (uint32_t) irs18 , 0x08, 0x8E); + set_id_entry(19, (uint32_t) irs19 , 0x08, 0x8E); + set_id_entry(20, (uint32_t) irs20 , 0x08, 0x8E); + set_id_entry(21, (uint32_t) irs21 , 0x08, 0x8E); + set_id_entry(22, (uint32_t) irs22 , 0x08, 0x8E); + set_id_entry(23, (uint32_t) irs23 , 0x08, 0x8E); + set_id_entry(24, (uint32_t) irs24 , 0x08, 0x8E); + set_id_entry(25, (uint32_t) irs25 , 0x08, 0x8E); + set_id_entry(26, (uint32_t) irs26 , 0x08, 0x8E); + set_id_entry(27, (uint32_t) irs27 , 0x08, 0x8E); + set_id_entry(28, (uint32_t) irs28 , 0x08, 0x8E); + set_id_entry(29, (uint32_t) irs29 , 0x08, 0x8E); + set_id_entry(30, (uint32_t) irs30 , 0x08, 0x8E); + set_id_entry(31, (uint32_t) irs31 , 0x08, 0x8E); + + + //print_serial("Remapping PIC\n"); + PIC_remap(0x20, 0x28); + -/* // pic IRQ Table - set_id_entry(32, (uint32_t)irs0, 0x08, 0x8E); - set_id_entry(33, (uint32_t)irs1, 0x08, 0x8E); - set_id_entry(34, (uint32_t)irs2, 0x08, 0x8E); - set_id_entry(35, (uint32_t)irs3, 0x08, 0x8E); - set_id_entry(36, (uint32_t)irs4, 0x08, 0x8E); - set_id_entry(37, (uint32_t)irs5, 0x08, 0x8E); - set_id_entry(38, (uint32_t)irs6, 0x08, 0x8E); - set_id_entry(39, (uint32_t)irs7, 0x08, 0x8E); - set_id_entry(40, (uint32_t)irs8, 0x08, 0x8E); - set_id_entry(41, (uint32_t)irs9, 0x08, 0x8E); - set_id_entry(42, (uint32_t)irs10, 0x08, 0x8E); - set_id_entry(43, (uint32_t)irs11, 0x08, 0x8E); - set_id_entry(44, (uint32_t)irs12, 0x08, 0x8E); - set_id_entry(45, (uint32_t)irs13, 0x08, 0x8E); - set_id_entry(46, (uint32_t)irs14, 0x08, 0x8E); - set_id_entry(47, (uint32_t)irs15, 0x08, 0x8E);*/ + set_id_entry(32, (uint32_t)irq0, 0x08, 0x8E); + set_id_entry(33, (uint32_t)irq1, 0x08, 0x8E); + set_id_entry(34, (uint32_t)irq2, 0x08, 0x8E); + set_id_entry(35, (uint32_t)irq3, 0x08, 0x8E); + set_id_entry(36, (uint32_t)irq4, 0x08, 0x8E); + set_id_entry(37, (uint32_t)irq5, 0x08, 0x8E); + set_id_entry(38, (uint32_t)irq6, 0x08, 0x8E); + set_id_entry(39, (uint32_t)irq7, 0x08, 0x8E); + set_id_entry(40, (uint32_t)irq8, 0x08, 0x8E); + set_id_entry(41, (uint32_t)irq9, 0x08, 0x8E); + set_id_entry(42, (uint32_t)irq10, 0x08, 0x8E); + set_id_entry(43, (uint32_t)irq11, 0x08, 0x8E); + set_id_entry(44, (uint32_t)irq12, 0x08, 0x8E); + set_id_entry(45, (uint32_t)irq13, 0x08, 0x8E); + set_id_entry(46, (uint32_t)irq14, 0x08, 0x8E); + set_id_entry(47, (uint32_t)irq15, 0x08, 0x8E); idt_flush((uint32_t)&idt_ptr); diff --git a/src/kernel/arch/i386/idt/idt.h b/src/kernel/arch/i386/idt/idt.h new file mode 100644 index 0000000..7281fa9 --- /dev/null +++ b/src/kernel/arch/i386/idt/idt.h @@ -0,0 +1,81 @@ +#pragma once + +#include "stdint.h" +#include "stddef.h" +#include "../vga/colors.h" +#include "../pic/pic.h"; + +#define AS_KERNEL() ( kterm_writestring("[KERNEL]:")) + +extern "C" void kterm_writestring(const char* data ); +extern "C" void kterm_putat(char, uint8_t, size_t, size_t); +extern "C" void kterm_put(char); + + +extern "C" { + struct __attribute__((__packed__)) IDT_entry { + uint16_t offset_1; + uint16_t selector; + uint8_t zero; + uint8_t type_attr; + uint16_t offset_2; + }; + + struct __attribute__((__packed__)) IDT_ptr { + unsigned short length; + unsigned long base; + }; + + struct registers { + uint32_t ds; // Data segment selector + uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax; // Pushed by pusha. + uint32_t int_no, err_code; // Interrupt number and error code (if applicable) + uint32_t eip, cs, eflags, useresp, ss; + }; + + + extern void idt_flush(uint32_t); + void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags); + void init_idt(); + + void irq_handler (registers regs); + + void irs_handler (registers regs); + + extern void irs0 (); + extern void irs1 (); + extern void irs2 (); + extern void irs3 (); + extern void irs4 (); + extern void irs5 (); + extern void irs6 (); + extern void irs7 (); + extern void irs8 (); + extern void irs9 (); + extern void irs10 (); + extern void irs11 (); + extern void irs12 (); + extern void irs13 (); + extern void irs14 (); + extern void irs15 (); + extern void irs16 (); + extern void irs17 (); + extern void irs18 (); + extern void irs19 (); + extern void irs20 (); + extern void irs21 (); + extern void irs22 (); + extern void irs23 (); + extern void irs24 (); + extern void irs25 (); + extern void irs26 (); + extern void irs27 (); + extern void irs28 (); + extern void irs29 (); + extern void irs30 (); + extern void irs31 (); + + + + +} diff --git a/src/kernel/arch/i386/pic/pic.cpp b/src/kernel/arch/i386/pic/pic.cpp new file mode 100644 index 0000000..5f1967c --- /dev/null +++ b/src/kernel/arch/i386/pic/pic.cpp @@ -0,0 +1,62 @@ +#include "pic.h" + +extern "C" void PIC_sendEOI (unsigned char irq){ + if(irq >= 8) + outb(PIC2_COMMAND, PIC_EOI); + outb(PIC1_COMMAND, PIC_EOI); +} + +/* Helper func */ +static uint16_t __pic_get_irq_reg(int ocw3) +{ + /* OCW3 to PIC CMD to get the register values. PIC2 is chained, and + * represents IRQs 8-15. PIC1 is IRQs 0-7, with 2 being the chain */ + outb(PIC1_COMMAND, ocw3); + outb(PIC2_COMMAND, ocw3); + return (inb(PIC2_COMMAND) << 8) | inb(PIC1_COMMAND); +} + +/* Returns the combined value of the cascaded PICs irq request register */ +uint16_t pic_get_irr(void) +{ + return __pic_get_irq_reg(PIC_READ_IRR); +} + +/* Returns the combined value of the cascaded PICs in-service register */ +uint16_t pic_get_isr(void) +{ + return __pic_get_irq_reg(PIC_READ_ISR); +} + + +void PIC_remap (int offset1, int offset2 ){ + unsigned char a1, a2; + + a1 = inb(PIC1_DATA); + a2 = inb(PIC2_DATA); + + + // Start initialization + + outb(PIC1_COMMAND, ICW1_INIT | ICW1_ICW4); + io_wait(); + outb(PIC2_COMMAND, ICW1_INIT | ICW1_ICW4); + io_wait(); + outb(PIC1_DATA, offset1); + io_wait(); + outb(PIC2_DATA, offset2); + io_wait(); + outb(PIC1_DATA, 4); + io_wait(); + outb(PIC2_DATA, 2); + io_wait(); + + outb(PIC1_DATA, ICW4_8086); + io_wait(); + outb(PIC2_DATA, ICW4_8086); + io_wait(); + + outb(PIC1_DATA, a1); + outb(PIC2_DATA, a2); + +} \ No newline at end of file diff --git a/src/kernel/arch/i386/pic/pic.h b/src/kernel/arch/i386/pic/pic.h new file mode 100644 index 0000000..5358f5a --- /dev/null +++ b/src/kernel/arch/i386/pic/pic.h @@ -0,0 +1,57 @@ +#pragma once +#include "../../../io.h" + +#define PIC1 0x20 /* IO base address for master PIC */ +#define PIC2 0xA0 /* IO base address for slave PIC */ +#define PIC1_COMMAND PIC1 +#define PIC1_DATA (PIC1+1) +#define PIC2_COMMAND PIC2 +#define PIC2_DATA (PIC2+1) + + +#define ICW1_ICW4 0x01 /* ICW4 (not) needed */ +#define ICW1_SINGLE 0x02 /* Single (cascade) mode */ +#define ICW1_INTERVAL4 0x04 /* Call address interval 4 (8) */ +#define ICW1_LEVEL 0x08 /* Level triggered (edge) mode */ +#define ICW1_INIT 0x10 /* Initialization - required! */ + +#define ICW4_8086 0x01 /* 8086/88 (MCS-80/85) mode */ +#define ICW4_AUTO 0x02 /* Auto (normal) EOI */ +#define ICW4_BUF_SLAVE 0x08 /* Buffered mode/slave */ +#define ICW4_BUF_MASTER 0x0C /* Buffered mode/master */ +#define ICW4_SFNM 0x10 /* Special fully nested (not) */ + +#define PIC_EOI 0x20 +#define PIC_READ_IRR 0x0a /* OCW3 irq ready next CMD read */ +#define PIC_READ_ISR 0x0b /* OCW3 irq service next CMD read */ + +extern "C"{ + +extern void irq0 (); +extern void irq1 (); +extern void irq2 (); +extern void irq3 (); +extern void irq4 (); +extern void irq5 (); +extern void irq6 (); +extern void irq7 (); +extern void irq8 (); +extern void irq9 (); +extern void irq10 (); +extern void irq11 (); +extern void irq12 (); +extern void irq13 (); +extern void irq14 (); +extern void irq15 (); + +void PIC_sendEOI (unsigned char irq); + +} + + +static uint16_t __pic_get_irq_reg(int ocw3); +uint16_t pic_get_irr(void); +uint16_t pic_get_isr(void); + + +void PIC_remap (int offset1, int offset2 ); \ No newline at end of file diff --git a/src/kernel/idt.h b/src/kernel/idt.h deleted file mode 100644 index 07c7440..0000000 --- a/src/kernel/idt.h +++ /dev/null @@ -1,93 +0,0 @@ -#pragma once -#include "stdint.h" -#include "stddef.h" -#include "arch/i386/vga/colors.h" - -#define AS_KERNEL() ( kterm_writestring("[KERNEL]:")) - -extern "C" void kterm_writestring(const char* data ); -extern "C" void kterm_putat(char, uint8_t, size_t, size_t); -extern "C" void kterm_put(char); - - -extern "C" { - struct __attribute__((__packed__)) IDT_entry { - uint16_t offset_1; - uint16_t selector; - uint8_t zero; - uint8_t type_attr; - uint16_t offset_2; - }; - - struct __attribute__((__packed__)) IDT_ptr { - unsigned short length; - unsigned long base; - }; - - struct registers { - uint32_t ds; // Data segment selector - uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax; // Pushed by pusha. - uint32_t int_no, err_code; // Interrupt number and error code (if applicable) - uint32_t eip, cs, eflags, useresp, ss; - }; - - - extern void idt_flush(uint32_t); - void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags); - void init_idt(); - - void irq_handler (registers regs); - - extern void irq0 (); - extern void irq1 (); - extern void irq2 (); - extern void irq3 (); - extern void irq4 (); - extern void irq5 (); - extern void irq6 (); - extern void irq7 (); - extern void irq8 (); - extern void irq9 (); - extern void irq10 (); - extern void irq11 (); - extern void irq12 (); - extern void irq13 (); - extern void irq14 (); - extern void irq15 (); - extern void irq16 (); - extern void irq17 (); - extern void irq18 (); - extern void irq19 (); - extern void irq20 (); - extern void irq21 (); - extern void irq22 (); - extern void irq23 (); - extern void irq24 (); - extern void irq25 (); - extern void irq26 (); - extern void irq27 (); - extern void irq28 (); - extern void irq29 (); - extern void irq30 (); - extern void irq31 (); -/* - extern void irq0 (); - extern void irq1 (); - extern void irq2 (); - extern void irq3 (); - extern void irq4 (); - extern void irq5 (); - extern void irq6 (); - extern void irq7 (); - extern void irq8 (); - extern void irq9 (); - extern void irq10 (); - extern void irq11 (); - extern void irq12 (); - extern void irq13 (); - extern void irq14 (); - extern void irq15 ();*/ - - - -} diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 2530c7a..edd7f22 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -9,10 +9,6 @@ void delay(int t){ asm("NOP"); } - - - - class Test { public: Test(); @@ -20,7 +16,6 @@ class Test { ~Test(); }; - Test::Test(){ kterm_writestring("Create a test object\n"); }; @@ -56,7 +51,6 @@ static int init_serial() { return 0; } - int is_transmit_empty() { return inb(PORT + 5) & 0x20; } @@ -77,7 +71,6 @@ char read_serial() { return inb(PORT); } - void print_serial(const char* string ){ for(size_t i = 0; i < strlen(string); i ++){ write_serial(string[i]); @@ -102,31 +95,13 @@ void test_serial(){ kterm_writestring("\n"); } - - extern "C" { void early_main(){ init_serial(); print_serial("\033[31;42mEarly main called!\n"); - - print_serial("Remapping PIC\n"); - // remap the PIC IRQ table - /*outb(0x20, 0x11); - outb(0xA0, 0x11); - outb(0x21, 0x20); - outb(0xA1, 0x28); - outb(0x21, 0x04); - outb(0xA1, 0x02); - outb(0x21, 0x01); - outb(0xA1, 0x01); - outb(0x21, 0x0); - outb(0xA1, 0x0);*/ - - - print_serial("done... \n"); - + } void kernel_main (void) { @@ -162,24 +137,7 @@ extern "C" { auto testObject = Test(); testObject.printMe(); - /*IRQ_set_mask(0); - IRQ_set_mask(1); - IRQ_set_mask(2); - IRQ_set_mask(3); - IRQ_set_mask(4); - IRQ_set_mask(5); - IRQ_set_mask(6); - IRQ_set_mask(7); - IRQ_set_mask(8); - IRQ_set_mask(9); - IRQ_set_mask(10); - IRQ_set_mask(11); - IRQ_set_mask(12); - IRQ_set_mask(13); - IRQ_set_mask(14); - IRQ_set_mask(15); - */ - + /** test interrupt handlers **/ asm volatile ("int $0x03"); diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 3b1b0bc..ced720a 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -3,7 +3,7 @@ extern "C" { #include "../libc/include/string.h" #include "arch/i386/tty/kterm.h" } + +#include "arch/i386/idt/idt.h" #include "MMU.h" #include "io.h" -#include "idt.h" -//#include "pic.h" \ No newline at end of file diff --git a/src/kernel/timer.cpp b/src/kernel/timer.cpp new file mode 100644 index 0000000..35a8a4a --- /dev/null +++ b/src/kernel/timer.cpp @@ -0,0 +1,27 @@ +#include "timer.h" + +uint32_t tick = 0; + + +static void timer_callback (registers_t regs ){ + tick ++ ; + kterm_writestring ("tick passed!"); +} + +void init_timer (uint32_t frequency){ + // register timer callback + + uint32_t divisor = 1193180 / frequency; + + // Send the commmand byte + outb(0x43, 0x36); + + // Divisor has to be sent byt-wise , so will send lower then upper bytes + uint8_t low = (uint8_t) (divisor & 0xFF); + uint8_t high = (uint8_t) ((divisor >> 8) & 0xFF); + + outb(0x40, low); + outb(0x40, high); + + +} \ No newline at end of file diff --git a/src/kernel/timer.h b/src/kernel/timer.h new file mode 100644 index 0000000..db8be78 --- /dev/null +++ b/src/kernel/timer.h @@ -0,0 +1,6 @@ +#pragma once + +#include +#include + +void init_timer (uint32_t frequency); \ No newline at end of file -- 2.39.5 From a094f510d3738e84aaae4ef8162e4301bd218c5c Mon Sep 17 00:00:00 2001 From: Nigel Barink Date: Sun, 16 May 2021 15:53:14 +0100 Subject: [PATCH 005/115] More work on interrupt handling, Started timer interrupt implementation, PIC remapped hopefully successfull --- Makefile | 11 +- README.md | 3 + screenshots/WIP_interruptHandling.png | Bin 0 -> 16282 bytes src/kernel/arch/i386/boot.s | 426 +++++++++++++++--------- src/kernel/{ => arch/i386/gdt}/gdtc.cpp | 0 src/kernel/{ => arch/i386/gdt}/gdtc.h | 0 src/kernel/{ => arch/i386/idt}/idt.cpp | 111 +++--- src/kernel/arch/i386/idt/idt.h | 81 +++++ src/kernel/arch/i386/pic/pic.cpp | 62 ++++ src/kernel/arch/i386/pic/pic.h | 57 ++++ src/kernel/idt.h | 93 ------ src/kernel/kernel.cpp | 46 +-- src/kernel/kernel.h | 4 +- src/kernel/timer.cpp | 27 ++ src/kernel/timer.h | 6 + 15 files changed, 577 insertions(+), 350 deletions(-) create mode 100644 screenshots/WIP_interruptHandling.png rename src/kernel/{ => arch/i386/gdt}/gdtc.cpp (100%) rename src/kernel/{ => arch/i386/gdt}/gdtc.h (100%) rename src/kernel/{ => arch/i386/idt}/idt.cpp (51%) create mode 100644 src/kernel/arch/i386/idt/idt.h create mode 100644 src/kernel/arch/i386/pic/pic.cpp create mode 100644 src/kernel/arch/i386/pic/pic.h delete mode 100644 src/kernel/idt.h create mode 100644 src/kernel/timer.cpp create mode 100644 src/kernel/timer.h diff --git a/Makefile b/Makefile index 3aec044..aa43673 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/MMU.o $(BUILD_DIR)/idt.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/MMU.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o SRC_DIR = src BUILD_DIR = build @@ -24,7 +24,7 @@ all: clean build build: build_kernel run run: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std + $(EMULATOR) -d int -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std build_kernel: $(OBJ_LINK_LIST) @@ -55,7 +55,12 @@ $(BUILD_DIR)/crtn.o: $(BUILD_DIR)/io.o: $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti + $(BUILD_DIR)/MMU.o: $(CPP) -c $(SRC_DIR)/kernel/MMU.cpp -o $(BUILD_DIR)/MMU.o $(CFLAGS) -fno-exceptions -fno-rtti + $(BUILD_DIR)/idt.o: - $(CPP) -c $(SRC_DIR)/kernel/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file + $(CPP) -c $(SRC_DIR)/kernel/arch/i386/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/pic.o: + $(CPP) -c $(SRC_DIR)/kernel/arch/i386/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/README.md b/README.md index cf263a6..eefdecd 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,9 @@ ________________________ The first scrolling boot screen. 😲 + +W.I.P - Working on interrupt handling + ________________________ ### The goal diff --git a/screenshots/WIP_interruptHandling.png b/screenshots/WIP_interruptHandling.png new file mode 100644 index 0000000000000000000000000000000000000000..cc9c89ed85437e6a10451f6fc4bb91c6af6cc3be GIT binary patch literal 16282 zcmeHucUTkayX`1$vEmj)M4E*nU69`Q7DT{+bO=pFKnxv152B(-SCG()^cF%3B|wm_ zgeE0HF!UZegc8~v_ICfu{+)B~`Tt%Xo@Y{KzL{^nch#&jO^p@Sho)#W|BPozRu3(w6wJJIaKsJROE+pfaBcK&+pd(|6jbQ zJ9+YCne#+TprqZv%4C$5!cJg%dU^;n(z+{AdVOST*k^g4N~O9Fm)o24i_n0_Vnn2* za)N?_Mo=adOD|P95F3=J%>l~@^b&?>PP<8=EK1ABK;gdNu1cuTh=_bN+Hq}kbab|< zsi_7B&W}~hYi%+nG%QS?jRoB4p@yZUWjr`{1>LL%aYK^u`3*DPA@BQU&^fOqtsPtvG5#Ug!XO(d-&c*D>~`y6}O~x zzj!fqmijgRbgrXt(w-_ucbxECR10xF+hRM|!P9sA&EoEbZt~&AqIYwrV3?vON@#!H zaU(-!|Ne!&Z5_mZOZKHbL!9FwasKWMTl$=qFhNpr|0YRsY5ggnX%X)C z=+!P%_PSAjLp-lg#SFD^%o~op(5t`X{b(4ru}MtMVxnmEG@(3Z@fN#b$#x#p4-UpV zR*0J)m9z#C;g=Jg-&)&kClwwDoE8I~evp2NTgL5*S+!m2h!@w0;+B_97gbOwq>za) zJW?=T-lx3c+Obpzs&!Ik-NA+`yp28Gdu7I=FVmvhKob2uZElx6lUOt3Te~|s(re-8 ztzD3_W-%GZI!@!SaNEd|cMV z$ojD)vAfj87l$DV+pBm=!mi{qd^yB>FZqyAaWH?Ax{#LLKe*eE9Zd>^xg-~IvlCJL zgl9e1v!B)gJ&zg?0tUmT=RJKIj2o#pkC zfz5qllq3fo?8w0D&4&)ZvCA!pCDqJ$3z`%kyqUTQ_%~Pyjcs=aDx`HGmUKFjWDR4? zHrX&k_8ke5S}V6dEc;0g+bxfFuT&la7L`_&@zl5LVU$4|JCauM}!Veh9 zk&ZX)6t_}NiruzNM+)LJEYXQ*U8eRv@e3)14DKAgiy;n#JNvt^(JJOy_iB{8&+iP2 zGZCx4bxDEAySeh8f+`1&0YRc&N)ceZd2YL~xpn_G1WUH*N=D&@>mJ;_JA*_jjl4MA z59(U3J3Pp2I+p4Ys_0o~5P=c5oX3mpsvxM8yRumgh|rqhO*rzd1%do8pea|N3xPex>N%cRyB}Sbi^h!2#PWoe*uh= zny#9yN9R*kwmI3HIxXhX(cZaP8;e<%T8g?nH3tzJL1=`bh4&Wg`Danc7t4GkX=HZk zvGeEDuU2b>I1cBykLW>$)V!a3*CELYVW_lX+pjh)u|D5)g!gu~ zMYo}Y=Z%LP`wQpF%JeIQ%s-)QQVNm=waC*d6)?S?&!dw}NT>UQzP%M2j&Rv`hqiIdszZ`|nALYS%g9k5Y9JI%Z$+Zc{X-Fd=DXZxUH zWdA&3>Mc+5iyZM(8;!UjZ|@y?l8AR?IIBf&Gk-GVv&lY}yVgusd)GlSfWF*(M zQ%2J@LP2|-T0WNx_n4=`{8AnLc5SdWy4xxMkWZ+m+5S zeh|rr!p8u!ba9(b)&qT7Fzbejjwqi3w;MO;pMjgt$G}_z#WCcTexnV-qm&>C-Y+!%E7p z{c86<>Xvog3E3!Rk<2q|6#-{*4JrQ;=TVGwkcOUZV0MEcHRYTQNhQzVJEz?QF_gYA zB5XBF9^SyaE`G(&d-PF~`~k}Ca|}g`3B;3yK5rc4@Bv%xN+UG}9X6ZC zv0sflM0L$tF3V|_md7ZRiB)zT-yh?_<=|gJ!V8x{Ln zM|>lP;a{0H4*mYzWuvZ3@$N2!u8A-R2|TC|+z__l_@+-Z%^efoM-9Jd!Qa5^mON9e zRVMCRr*C>reU))rJDZZ=J8KIqnwh|kVNJ@oo}aT_l{eIJZ4Qk1Ho4egfvT&U2iLK& zRpD@8$%f2Ph&AO)5&n-PV_z_XcZWqKo zZ)PVpTMO155C@BfR%NDEcwe@9^o(WK>Qtk4GYhLN#ilX5tB`{J9xJjKeChh&a#hrA z&u-sZ-=fSp*XjApE_n&7gR%HK-uahD%KPz0WzUL0;4Wcs5bN>*xy6Qxl3{im(I^|u zs4W}Mk}VVLF2Ueey*s|@VxCS8Q9I&o#3ag%BSzfA3e80Fn7ZWeS7R~=>^x*abn+*Y zI*M(Wzze+u)r#3w*+Rld&3+j5bHy^EkTnAZk@V9|*+26eF01@AK2AoonL5D^+k zaz*L1?Lo4j8VJyP((^tm$K+Sjq~l9r8aj2;tRfas4i;&Q345VONYmv4-TqYT^~M2< zu~1EM%g9on_n8ZV-geD&sG+wGi>)o6ONZ679Vv}a|UL!-Xgr^|8=pl|^?A>}Ri zETn3O94aymQmB1BAI;nej}CD%GiQmji7OgB?B5)!H`L4tjaP^W;$h6v3w(lG8-Lau zQS#jEc5gW0v%N*XFrhi@`<0Q#3fr$J25S0U^TL-b9)#<{Ch5@@HO36tI1QUlk`~QY z7jaD3`(X%DK6$0}G&rXcCjp~p z^Y?1l_v{gL-Qk>NSG47WerB{c&c$nE&ZZ3F^L(%msRxZG5|B0$wss2=2udwSe{{s9 zq2;E#b=_UdGO9DlYiAZ+cJ-3HJx%ZmTm14Dhfv};XHv0-t7sl__KxPxWrIsd}9Wu#y~O#wfcqeqi`>K%P*FAIAs>C#C(yt8bQ z!6o}3yPQ(3@9{j0uGfNc%-q6Rg;c|?g{YG}Fc*#IimPYC_GTtz7TB2P z!`7{zxg4gt4=pPrM$a0~mqf6l=YFy3UsOdCr-%xlZVn@gJAI~bgYazI!QI&kvexjL zsJv&t2ZbN4(r7Qgnoq{mEI&(1K_u(`o~c-vRup8bm9+>Xd{ zl5>ayv0mo+fdr{$(xLfBHaG=;R?z}!kx$|wG0!?=H;LscAsB@l9ISOS)zsFmj&7A1 zzXv0GuaDV#`C<%ytkCRFRCM*F)b1#C3|D3Drg-1O*X@byceE(>dA&Gr^j;4A&3>o| z%6~xC*>ARzoS)m&-ce=B+%H4!lT*l%Jj3Y~hpUR@3!Cw2-_CE@u5KxQ(hC24`2^sEQ=Pq2(h;ym=2<&_4c)j8Keg zA7lo^$EPv2C&8mIcaIxyaY_eqZRUs&leosngp6*P!ZP>z6SCWf0FdgT-7xmO;msnO zbv{VRy5$qqrA(Wm9hJFav@@^Wyonm=<{$5`zFQIENfx#&A)FP6vp? z#C#?>D_5gId}{AF;O`=3KecFilab8Fs@eQXQf=v?1r zx&g1+2-2}qzh-t{GacJE;_Mbyw~7l}7e=t_{FK2&}4Lpc^H z=h1e(0n<}YY_jiX^AlK-LgIoSy5*|guAkjw@|7by_e7#9ajzm&_w5+v+)XWTEy-Mk z88dC~z7w4VM0T$ln%+pE>@zsf0!sRPykkY&#R~M_(io=GGCGd10DzuLkxCxw{4#f%w7aU=g|!4oIWY|MlC-RRA?kLVZ4u~x7r?EnzK zSWf3=%*6oj-D$jj!GJ|6u|(Z)o(~rED*!0y<30pO1eAs&tUl${_X$g4LT z1B2rGZ5mReY26dm^_^QL$ADDghd=9{TSs34tUs%uME4sT#i3?wD$U7#+_`2Ie6IR$ zYw%-lBBCUxM>oHdnnZ;RCIH}(YMgbd>OH6|=X;3eEx}^dFy`hQ-4X(dKia58f2IR0 z#&RNi&x!SjTM7>La+&PTU$y%T=kDIUJ9NmO2azf)C_wByn2rp;xS%MMJUXGR7&rlu(X6yb zN?gXZFe;dDA07i{;n5$RjG~MDaclzP+bXk!$!@qQXAb~~nLH*d#psJ_OC~9@daFRaPQ?r6Hqn3&rvA=7J}d4- zQv46P3m3AH7q_1?aK$Q{M9mZ+^mD(s8f9k0CP=XZKrkWlY3D73UB(l$H#g_2a*WnC zrh06cS#kpy7-O(gB?eM!CV_N~nZmXval|Aj z39=AY>_Jsp_6QjISWXKAKy!Xgz!82wqo;qCs!>Fd0D!5~KR$8#eC}V1=D*>C?|mpi z;Q3r}CD-?~3{22G|6H*Ef(!NQSdWBo3Iaq8kEu2$2y={;8ct@d>IWx~D)*1jfNMoY z89j-(>iR9s{iQ4Eq>KYkRi%VB2LZ|XJri9vfLEt89arx`NiK-nnnE7jdi^4_WuFc@ z2mo!Wrvq)^q{Z8gug2D1n%xs^r1Q#oEw_9Z&kuRM@PW4 zxg^?-`Fr1bdQwKvYw6?N09fX0bkIfLKym{VI*6Bl~RM(T570iZuO zBOqOO`aQCpdS4lZfb$dM=hB8Y@|+?s1+KGpVUXs*=(#Pppl?y1WRx6@Qtc(3hHt#6 z+4f&m<(Iu{Ij{KhQcoL!kj(LyyMVIL6gkDe0CA@Y>7Je zeAdEuhZuA-UZD7v47i6tW=RSi%$vtSUGE z0_2!$=s0SAJuV+y0!HFm?!QE2VCBbNFoQk&=yZfebfA<5ZvFvE$l_8VMW$ip%%$pM z_x?mCcIW(?mx`bNK1gp3HzcUjL*%u*kT1`2WZ&#s^=+OwyPV=HFi{d-+phoE2-M|- z|1&6~R*yaDZCamPpH>=C^F-T@@3y7|nRK|)2m&dh_8G4{A#rd=EEXY^ZtQv3M@u}e z#K4GDYUPU5mZhphzjAY@ZyyAMPFJNPd2;_(b$*T@ax2t*{LXX+`fYl0NJwTWgK4s7 zPm5Jh>y(t5NMOX{+AMAR@xiJU#t8C2RHv({NenLSiIC{&GE-rWneM?DEgV{OtzvewW0JIx%iHgfq1;>+g&bE3Ipl;8OpK+N5h-NG zAO@Y`Y&>3^%mHgJv{dsc$bm(3C0E845al%<82bsECTm4f5btMLp)a%qC)$R%1@Daz z&j1BrR(u!F96o+i4YR2)Nw{#FLx96U;iIv~70q9R7lvHyG~}$3Q!;RQ_eBdVwL)?W z$mRsheCTyg2J2y}Wuz+b1r4&FJFpt3$FicQ-65gtoIRw6B^NV;WeMxt=SkH1MVKi# z0@my-(K9b}WNTR^{t-Rf0=~qTXwc1;S+2d~C=#I6ixJJ50O6b6&_- zs6b6@=JwT@U%(}&pUqM3i;O*Klli*!UG>Y`S|zYKe5Mv`&1}Q_+t}0o*7E@bT%*N;_v>0pbHkYykbAMEW84 z{XZp1sYT^0<}HE_J5?*(eDIO;xBuc~)vs&b$>P%qNc+f=rE0ar|LGFdZU;MfG1YU+~aHhMjhw%Nv%xv3? zG%y-8qCU?nO9Iwe?-crS7IMJ82X)0p;jU^9Zc5G1)L0Z}hvDfX@XnD>=r|g^A?brn z7}qg=c49G4(oAK!5JIKd^eO$bDszR-PZ;48UyG1OCiJd=iVL(w$lhHXr72}gUdr%( zjwko{X@-o*xSCF$E9GK_sN>e`X6$!Ho#(1^Vp01o#hm?x2(F`3QTB{1-Ptq-Emh3& z1y-AypVlrJKWSU@8C&y>ELeUmH`7h^dCqJ&EMY4`#TfvP^wmI6Yj?WDp_Ye1V~hQM z-F~#=wEn3b+vxP_;nNYMrO7z&`W`1mUnTM}n-BDXmDyHFp}x(z`h?r-1db@V<4S&S zIJ=XKC*GVL`k+<>dy>fWVd-sT*e(4Z#mSPkvxEx{7888ydwq-0$`)O#J=_c7o)b~C zkLnaavhpRX2%g%Qd8sySJ@76&1ZyJ47c>gf`HcSb=~EB=rbEu-P!j;)xOUVFa9J(_ zc&|FelDmChiacO=x&FmK<6(Dpw6WgKr>lF9D!9A!TTL$=olDBfJOtaU>oMl~7?LI( z_)SU}41kYHs$6LxbW8EG$=&;LKENx|Ov6G50gYNtBZkoNH+ex2wJwHF`>`Eby`3 zmXR*iBi9*o-a7}XzalPW)q*)ipIQ6J$I2;DASCofD*>)aPtIg8cp zhFu;Gd}V>9u zV`U0w@riQx{N>>b%{$%qi64!(vhs%l@5H~^(n2^10%F>K6e!G?1PeXhFaM+ux|xe7 zVrOEVr*1m$8{sv5TM{?=oqEb!wH0UfgXQf_k)EdEQI}k|uMl8Y`?(8~&RVQihRe^% zwPN6N{Cv|lqLlEIHD@{$VrOy}dSWOtmgZJuuc*6iX}&GILCwU2r(f5^JZ94sx<`nc zxM343`1P62TC|OgrNy)^F3d@9Urt{b7{XpK0-d2^Xvg zY;PF?ZtRw`4$*7H&G6)+`6ADe2YR3Ik+Cswl#J!6;efb`gV;$BX!$u`F1243HXR6m z@XCx~LN3Tn@}r${?szz*M(u8epA%S4#m!_p5F5mk`6jmZeLirmmU!*=cBnf==jLU?k8Ehg3wevuA2B^y&N zB>cP9ElE+Yh#40@-!1(~X*VwpX!uM%Br->F_*m*W&3q?-^h%T=b$7+*e5ycn3`j)Y z|8l1b$ZI$!=B;VUd(wY;Y>Qcm@%~Y%4bc81DnH+8%3gdM;~Zk*CsY%pPV%4$4VKS^ z=v2#%FI^KJ?_A5lSS4f>R4*oYC%?kyPswYlCQs}Hw=xYY?ijULvH8UD+Z3tO0v4hj zN~$Qh>7Qaq8qq_Dh2xq8L{3Y=kZUC=U@M**_d-BmB5!CQp{$YLpXwU_@*Xy;9V=-@ zQb_zJQ1fE`HSAbw&>4-?3Hq-&q`frt-|pRm7H2XdC6KsyK6{?ea;>5N##5ro<-@7c z%Z3ZK6D3U(E{PejjjcuIy*U!ji>BMbt?&i48R7^p00_vNB0G+Ns@(ibTr|d6_79no@=MtYLM| z0%{nTg&KG&OL;{?tXXU1rja(0PeaaG#2D>^j4jzSuarySB=279k}f+)hPFgkK%k*G zG$UZ7uhVc*{0?igYUK09e1`ADHOKYVYMF5OPNcIkV?)Bw`6O-@k_q5t8jQET#L zU1MTx0j!_-?h1E%4W*S61Xqjer`>D_o?{K}Pw5xpugs`rRDXJUQ=QSHU zr!1g0;g_zPz@#=<;wjK~%4|lftZ;0uC~nwVUDo%@IjJ~+`s&&*!qj{;zGfUT&0)3A zY}?c*>RIPwvCgyLqH}d?2jy^yobObpjkxGR^Emk_u_s0&g)mt?OG#_|nis)x3WeZ8 zc=B-V;+}*D%P$8$hRUfScCN-OuSdDvjm{K~A)DWm!_|HG>LVAkK2eRn(e(+x+wCG} zVIQfyze)#KIYHmh%wGN&2ap0sV1U&h%-dfe*6ZX$M(fmXuH)(=fY^mPFxY=uravpg zpYNOogKpP^n*3OE9fRo2<5(W)EvVT?4o+S4p!K@wfmB5a4slwM>___6FPWMPE<4Mt zv342C;Z_d5wu%ao2k@rSuk~es?MT~`GS5*HSe~zH0>w^l@sdVQPodc!bug^AlyOPqeVczURpX0tI}|i=+?Fi5t765UB^VfLrcgTd7|g zo4y+d4;(x3=?hMu6t+HQe{h9 z&N7wXjCw?DlG3_CI?u(TomXio@7U9g;`o7U(VyPQ9l|(;Ww&i34$U)8bAPM%L$ERd z?;)US5valItuk{VP%hrB!c&jFo|xfp0qQ83Tni)tPxfQiBHAQ%RzElqiqQhE4vPX0 zKWXuo=B(Wn->!FnBm65{#}g}kQ&KWm@&pi7 zrdy)ptNUROh9{~LIYtnSUUX)|fyjxS=TV&V5gx#;*S&nKN)@T?CuSA)%xP|E)Zrg+ z0s#EChI6TW(L^O0D_9RC9vHW(Iy?^e{&%9sV^8La%Bh)#gq%Kv>7v2Z2?mYL$~Ah z@?F|N3FMu^d92AqX_IAGGqJe0yi60z&e;k0bH3?N;weT-fn;O-qi&zEPM9^1$f@BI z{Tf03R+o$O;#zWG6Ac)NikwxkeR)EL(J_Fcd;d5oPTah*h%N3!HFt{_{hUmU-Q))( zaDstVW7pwH++3$Di+Qw6^Y`=1#Ybvkj`?HBi*JwOaya1>;(41oqZfRAV7}0B*b?lz z)yJJtjXQ0V6ls$3s?=Xw(S#v!g*?ywoYgi{02xQk>iiu{S7-@a^xQNjcBzgD@L#jS z1{K}J-{T|bOQj`;1aoPD3>jJcL0xt5-gN~7%XhGZ@-wPB7DyJXz-mTr?>#=S9N!kl z8IHY!nKXflJmQkH5RvhIN#R>is@FY!e!F`z{(IUsG&dut&By^%eN*^^$CS1v_(AH> z4FO3p@4TM7wqdPjxPawS^ZIchNAjoB!o>jTgE5^0tGeH(4-cB>72;t9;3`=$jnmdaJL z-Rrna5O@Clj+j?A*jh8+mK)HhV!HDd&eQPWgMppxo6N9Gbk@5;h+t*DNhPGn?1yvO zV1_)0A>Ak}<~NQ^eg#W+(sv=PDrF?wiPEJE!-`@Wpj#}ie614-iW4OFKg0h$U3u4CSXWHEOD$TRql_~Ay{RR(J~ zL`Ei88mo?o8100&-VmIA6#3kCgp(w88B`Gs1|R`rI>F{2X1E)q3fvwh$)Lcs1Li-i z=}QHJg;uxWW$mDNbcUc*6m-McmolY+jBQjjiJHZRks65N_Tyly-j^G_kN`Gg37z7? zhKm$aJpnI}dX@^Y;rBDDY>Jxlbnco0%?^Bnhuj!(+x*SVLcz@I zp!z%dQHdr;5+4jU7hOwf(>Q7<^5=eh^6IRpftL?nYO;9hWI5ay^?Kb zK3)n=e#?$@-udy4NANf6n0tVdu***tX^1Ke^7zokT8cK~$=s-vO&IR8Z{Yy^(=Pp? zdJ&RNfr9@}GC9wkxRHV2;+Pz48H_ng78$oLB8wG{l6%G>&lwmEb%NedeoR)Gxx7bG(f#S5I|44ai0@& zHgBl%RjVeyMbOZ`@VuuNwIrPXhtL-nI#66G0Slc1wStK6maKMyk%_v;^KUw+YSar_|J7< zvg5roR-o$wV@y;jFF$=~2T2n|MDyYY%!c~x+l73a**#cewjf3F06;3_`kJUs9k}0& zJ)_#^s$Dz@YD`^x5;}9Yo-l^zQP0%1Z1J%=+xHG;pb{^_6Ia&NEHz;)9yinQ!R&-E zJySFjOD<^R|E_sj?0vMxD=1Zn2E_SX>$1_+=iKn{{sLNr9ZgS4LYW5^k2AnJ|YLwTSA}o@fySCx%q7cCeAo^ zf(}9Qlo(Bz8>oGH=x1jT@`Aute19tcAKDN~_F{Nw*%J+Z0eb;NKV*fxChAUGwshYn zsF}FrfwPuDiDWO%Gg0EpJSV^}7Op)bS>3kfQRM(RG_ZQ6D(Loqsk2|#%2hRWxkS;Y zc6WDg9tJ;W2auDwtKkXa?c~PF$U(x2ru5C`tb`?QZ{DBO|CL&RQ~8%LM;Xe9Ce}BE>_X z-U1G4<+p6@)2Qm+0vZ--{K}PO9e5iHa5iRDYbv@eR>qO&a8nT7fj(7`$b9%fpgaBa zPbo3I#k4HPY}B;kW%!VqP$8s`7R#mPKF2S(Swep*rZUoveBK9g)sP{obCe_9w(d3H z@BInPI@l%mSjl>)orl6V;~odf_5GH-b$uvp243;Ih6O>wd3BrB@al+2Hm0uwd*p;*=CB6{HT&pgfW%J2O5b62kCK5jW%Cmp{{R}i< zcWpJ$c5wL`kZKO<;j=(S-Mq&AE-c2=U6FOjo(Os>@xl^HV*qaw`Ca^!%f z!Zh!ZwezpWzd;f@uGc`lh}+7x^~?)Y5(aHP>1}>LBSg0e19n;<8?00Dd~rDmB{tP& z)~L3`?|gsyG%E@x{D<{+_*g-cu-3Hg8|15Nk}-WAH@6ui^m|&HGn_2_i@*8%+<=?& z+`nl&xhk-DN|7C&SV{lu**|nX2FDbxo3{M)8MQ*Wwde~DM4Z6a%r_C}{zhjjdF!G* zE>@H6s?iA{XQM&o<_~(vsPZ=Do=RWmuICz)R9qBJANr8b`$QJ6^-_4(R^911J6 zh0wGL(k0kYahA!L#5|reV-^v^gXAu4r@QRDcf$?lGAkoQZwo%$C{Qc@BQ!cW=xT4E zi>{b_grjXQBdA6SeuM z@Hd_k8m89}6s$pVG0t}~8ZRj<{BTLji7QCpPO7bli2>$a2!C#h6AQiy??RgBjKD)u zk>_FC62}04HfgSIU_LAWB+lddN3I5FZ=XIb*3C8G%>p*6{PZ#Y76yYs-L0bkX#P>) z6og&IY#9BBwA1bxRHj647$I?y2Jf6~6Jok>VB1Z#%T!2KD87W#f>iwK3?TM@!ymoh z?bIU8sOllL1t%J~3OPyMjpk7;{TmsjYBN^>rPF~Pe_6)IEdI2NX*ibe4!45Bv?dp; z(0H3`TjdT}^RR7sljOi2A#zgI~Y63N|3D5F9$|=YWnQyCS>&x?mjT!#n8i zyg{LOuS&(7eo~XLpx5NT!H>WTun&1Y^F4jIrmc$2Td8?3;>1)?rU@Lk2{GZVkN=p- zhF=qRMRR-Dns%KHa&ry_uYdf}y{kZc`rpjr|0M{SfRE5EgDg;}NH_tO^F?Jh_dNTY z$JLbtzzTiC7E*&ihGwAdzu&}WY~mtM{)IqQ|7!$VU!jp?B9v=se)R_h08eK}#F6zpJll&vo!dyq|*b*3rzaIu^D>0sGv_3m$NzH{`V?o<;Q?SMwrMDMm4ypN2Ae7K>A`0L6 zVvN`)uDy;)_KaNFtt!|m;{suFEj6I=PD(YKL6TFdOnm?Y0Q6~OC7luk!!0cmpQH1> zQ}dPa5a^`wY2*fK*#5RMlOvJD_G4``dei8tMmy*#Jn3X`jHO(0p1~GQv^7$PSImY# zZVvOxvI9z`mqclj{@Df<5OI;n{Z|)MV5Z$?DD>AYMxT}9l~qvW4&j;>?b7;-LO(Ip z=29`9`c7Z-Zp$dy^5af2EeP(=g`kqTw8 zL0l~#4?oKtXB9@G*G&RJNK6&fPP5C>?%ZXi)R0%#ntH-|6jok;eVJK{_9Lg|t?QO$ zH5mtB!)hHs&eWz0R$WJ2Dy%Ev)cQDi>SNKO&3^sv{h5b@{}EW|d`fZ?VQDV@Gi3^u?qhUd(rJ^9)T>Z0($ z`^~M-&pF#i8C)%@8RkmPu*~{e%J&WfVMM&KnDAi?uPnE<_a&UN@p9aTQW}Up(fU$A zY6S>r{=$%ac_HWzb)H&Jzj=wxqm$&APjRu%%5!qQ)2-OLM*^qYM{}q97OREFkdcNp zR*f{w0uP}D9%}vUsrz659^|Lv`?Im?CvE>98uR}B*DC-2uz%8v|9>a{yWceZKM*Ac Zino= 8) + outb(PIC2_COMMAND, PIC_EOI); + outb(PIC1_COMMAND, PIC_EOI); +} + +/* Helper func */ +static uint16_t __pic_get_irq_reg(int ocw3) +{ + /* OCW3 to PIC CMD to get the register values. PIC2 is chained, and + * represents IRQs 8-15. PIC1 is IRQs 0-7, with 2 being the chain */ + outb(PIC1_COMMAND, ocw3); + outb(PIC2_COMMAND, ocw3); + return (inb(PIC2_COMMAND) << 8) | inb(PIC1_COMMAND); +} + +/* Returns the combined value of the cascaded PICs irq request register */ +uint16_t pic_get_irr(void) +{ + return __pic_get_irq_reg(PIC_READ_IRR); +} + +/* Returns the combined value of the cascaded PICs in-service register */ +uint16_t pic_get_isr(void) +{ + return __pic_get_irq_reg(PIC_READ_ISR); +} + + +void PIC_remap (int offset1, int offset2 ){ + unsigned char a1, a2; + + a1 = inb(PIC1_DATA); + a2 = inb(PIC2_DATA); + + + // Start initialization + + outb(PIC1_COMMAND, ICW1_INIT | ICW1_ICW4); + io_wait(); + outb(PIC2_COMMAND, ICW1_INIT | ICW1_ICW4); + io_wait(); + outb(PIC1_DATA, offset1); + io_wait(); + outb(PIC2_DATA, offset2); + io_wait(); + outb(PIC1_DATA, 4); + io_wait(); + outb(PIC2_DATA, 2); + io_wait(); + + outb(PIC1_DATA, ICW4_8086); + io_wait(); + outb(PIC2_DATA, ICW4_8086); + io_wait(); + + outb(PIC1_DATA, a1); + outb(PIC2_DATA, a2); + +} \ No newline at end of file diff --git a/src/kernel/arch/i386/pic/pic.h b/src/kernel/arch/i386/pic/pic.h new file mode 100644 index 0000000..5358f5a --- /dev/null +++ b/src/kernel/arch/i386/pic/pic.h @@ -0,0 +1,57 @@ +#pragma once +#include "../../../io.h" + +#define PIC1 0x20 /* IO base address for master PIC */ +#define PIC2 0xA0 /* IO base address for slave PIC */ +#define PIC1_COMMAND PIC1 +#define PIC1_DATA (PIC1+1) +#define PIC2_COMMAND PIC2 +#define PIC2_DATA (PIC2+1) + + +#define ICW1_ICW4 0x01 /* ICW4 (not) needed */ +#define ICW1_SINGLE 0x02 /* Single (cascade) mode */ +#define ICW1_INTERVAL4 0x04 /* Call address interval 4 (8) */ +#define ICW1_LEVEL 0x08 /* Level triggered (edge) mode */ +#define ICW1_INIT 0x10 /* Initialization - required! */ + +#define ICW4_8086 0x01 /* 8086/88 (MCS-80/85) mode */ +#define ICW4_AUTO 0x02 /* Auto (normal) EOI */ +#define ICW4_BUF_SLAVE 0x08 /* Buffered mode/slave */ +#define ICW4_BUF_MASTER 0x0C /* Buffered mode/master */ +#define ICW4_SFNM 0x10 /* Special fully nested (not) */ + +#define PIC_EOI 0x20 +#define PIC_READ_IRR 0x0a /* OCW3 irq ready next CMD read */ +#define PIC_READ_ISR 0x0b /* OCW3 irq service next CMD read */ + +extern "C"{ + +extern void irq0 (); +extern void irq1 (); +extern void irq2 (); +extern void irq3 (); +extern void irq4 (); +extern void irq5 (); +extern void irq6 (); +extern void irq7 (); +extern void irq8 (); +extern void irq9 (); +extern void irq10 (); +extern void irq11 (); +extern void irq12 (); +extern void irq13 (); +extern void irq14 (); +extern void irq15 (); + +void PIC_sendEOI (unsigned char irq); + +} + + +static uint16_t __pic_get_irq_reg(int ocw3); +uint16_t pic_get_irr(void); +uint16_t pic_get_isr(void); + + +void PIC_remap (int offset1, int offset2 ); \ No newline at end of file diff --git a/src/kernel/idt.h b/src/kernel/idt.h deleted file mode 100644 index 07c7440..0000000 --- a/src/kernel/idt.h +++ /dev/null @@ -1,93 +0,0 @@ -#pragma once -#include "stdint.h" -#include "stddef.h" -#include "arch/i386/vga/colors.h" - -#define AS_KERNEL() ( kterm_writestring("[KERNEL]:")) - -extern "C" void kterm_writestring(const char* data ); -extern "C" void kterm_putat(char, uint8_t, size_t, size_t); -extern "C" void kterm_put(char); - - -extern "C" { - struct __attribute__((__packed__)) IDT_entry { - uint16_t offset_1; - uint16_t selector; - uint8_t zero; - uint8_t type_attr; - uint16_t offset_2; - }; - - struct __attribute__((__packed__)) IDT_ptr { - unsigned short length; - unsigned long base; - }; - - struct registers { - uint32_t ds; // Data segment selector - uint32_t edi, esi, ebp, esp, ebx, edx, ecx, eax; // Pushed by pusha. - uint32_t int_no, err_code; // Interrupt number and error code (if applicable) - uint32_t eip, cs, eflags, useresp, ss; - }; - - - extern void idt_flush(uint32_t); - void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags); - void init_idt(); - - void irq_handler (registers regs); - - extern void irq0 (); - extern void irq1 (); - extern void irq2 (); - extern void irq3 (); - extern void irq4 (); - extern void irq5 (); - extern void irq6 (); - extern void irq7 (); - extern void irq8 (); - extern void irq9 (); - extern void irq10 (); - extern void irq11 (); - extern void irq12 (); - extern void irq13 (); - extern void irq14 (); - extern void irq15 (); - extern void irq16 (); - extern void irq17 (); - extern void irq18 (); - extern void irq19 (); - extern void irq20 (); - extern void irq21 (); - extern void irq22 (); - extern void irq23 (); - extern void irq24 (); - extern void irq25 (); - extern void irq26 (); - extern void irq27 (); - extern void irq28 (); - extern void irq29 (); - extern void irq30 (); - extern void irq31 (); -/* - extern void irq0 (); - extern void irq1 (); - extern void irq2 (); - extern void irq3 (); - extern void irq4 (); - extern void irq5 (); - extern void irq6 (); - extern void irq7 (); - extern void irq8 (); - extern void irq9 (); - extern void irq10 (); - extern void irq11 (); - extern void irq12 (); - extern void irq13 (); - extern void irq14 (); - extern void irq15 ();*/ - - - -} diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 2530c7a..edd7f22 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -9,10 +9,6 @@ void delay(int t){ asm("NOP"); } - - - - class Test { public: Test(); @@ -20,7 +16,6 @@ class Test { ~Test(); }; - Test::Test(){ kterm_writestring("Create a test object\n"); }; @@ -56,7 +51,6 @@ static int init_serial() { return 0; } - int is_transmit_empty() { return inb(PORT + 5) & 0x20; } @@ -77,7 +71,6 @@ char read_serial() { return inb(PORT); } - void print_serial(const char* string ){ for(size_t i = 0; i < strlen(string); i ++){ write_serial(string[i]); @@ -102,31 +95,13 @@ void test_serial(){ kterm_writestring("\n"); } - - extern "C" { void early_main(){ init_serial(); print_serial("\033[31;42mEarly main called!\n"); - - print_serial("Remapping PIC\n"); - // remap the PIC IRQ table - /*outb(0x20, 0x11); - outb(0xA0, 0x11); - outb(0x21, 0x20); - outb(0xA1, 0x28); - outb(0x21, 0x04); - outb(0xA1, 0x02); - outb(0x21, 0x01); - outb(0xA1, 0x01); - outb(0x21, 0x0); - outb(0xA1, 0x0);*/ - - - print_serial("done... \n"); - + } void kernel_main (void) { @@ -162,24 +137,7 @@ extern "C" { auto testObject = Test(); testObject.printMe(); - /*IRQ_set_mask(0); - IRQ_set_mask(1); - IRQ_set_mask(2); - IRQ_set_mask(3); - IRQ_set_mask(4); - IRQ_set_mask(5); - IRQ_set_mask(6); - IRQ_set_mask(7); - IRQ_set_mask(8); - IRQ_set_mask(9); - IRQ_set_mask(10); - IRQ_set_mask(11); - IRQ_set_mask(12); - IRQ_set_mask(13); - IRQ_set_mask(14); - IRQ_set_mask(15); - */ - + /** test interrupt handlers **/ asm volatile ("int $0x03"); diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 3b1b0bc..ced720a 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -3,7 +3,7 @@ extern "C" { #include "../libc/include/string.h" #include "arch/i386/tty/kterm.h" } + +#include "arch/i386/idt/idt.h" #include "MMU.h" #include "io.h" -#include "idt.h" -//#include "pic.h" \ No newline at end of file diff --git a/src/kernel/timer.cpp b/src/kernel/timer.cpp new file mode 100644 index 0000000..35a8a4a --- /dev/null +++ b/src/kernel/timer.cpp @@ -0,0 +1,27 @@ +#include "timer.h" + +uint32_t tick = 0; + + +static void timer_callback (registers_t regs ){ + tick ++ ; + kterm_writestring ("tick passed!"); +} + +void init_timer (uint32_t frequency){ + // register timer callback + + uint32_t divisor = 1193180 / frequency; + + // Send the commmand byte + outb(0x43, 0x36); + + // Divisor has to be sent byt-wise , so will send lower then upper bytes + uint8_t low = (uint8_t) (divisor & 0xFF); + uint8_t high = (uint8_t) ((divisor >> 8) & 0xFF); + + outb(0x40, low); + outb(0x40, high); + + +} \ No newline at end of file diff --git a/src/kernel/timer.h b/src/kernel/timer.h new file mode 100644 index 0000000..db8be78 --- /dev/null +++ b/src/kernel/timer.h @@ -0,0 +1,6 @@ +#pragma once + +#include +#include + +void init_timer (uint32_t frequency); \ No newline at end of file -- 2.39.5 From 394882ca2e2f4124a9370a4bbb30c9bb8c7d2c1a Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 18 May 2021 21:11:48 +0100 Subject: [PATCH 006/115] Added CMOS time read function, Added cariage return support to kterm --- src/kernel/arch/i386/tty/kterm.c | 105 ++++++++++++++++++++- src/kernel/arch/i386/tty/kterm.h | 10 +- src/kernel/time.h | 151 +++++++++++++++++++++++++++++++ 3 files changed, 261 insertions(+), 5 deletions(-) create mode 100644 src/kernel/time.h diff --git a/src/kernel/arch/i386/tty/kterm.c b/src/kernel/arch/i386/tty/kterm.c index 6dab47f..7ec9ae1 100644 --- a/src/kernel/arch/i386/tty/kterm.c +++ b/src/kernel/arch/i386/tty/kterm.c @@ -62,15 +62,17 @@ void kterm_scrollup(){ } void kterm_put (char c) { - if(++kterm_column == VGA_WIDTH || c == '\n' ) { kterm_column = 0; - if(kterm_row == VGA_HEIGHT-1) { + if(kterm_row == VGA_HEIGHT-1 ) { kterm_scrollup(); } else { kterm_row ++; } - + } + if ( c == '\r'){ + kterm_column = 0; + return; } if(c == '\n') return; @@ -89,3 +91,100 @@ void kterm_writestring(const char* data ){ AS_KERNEL(); kterm_write(data, strlen(data)); } + + +static void itoa (char *buf, int base, int d) { + char *p = buf; + char *p1, *p2; + unsigned long ud = d; + int divisor = 10; + if ( base == 'd' && d < 0){ + *p++ = '-'; + buf++; + ud = -d; + } else if (base == 'x'){ + divisor = 16; + } + + do { + int remainder = ud % divisor; + + *p++ = (remainder < 10 ) ? remainder + '0' : remainder + 'a' -10; + } while(ud /= divisor); + + /*terminate buf*/ + *p =0; + p1 = buf; + p2 = p -1; + + while (p1 < p2) + { + char tmp = *p1; + *p1 = *p2; + *p2 = tmp; + p1++; + p2--; + + } + +} + +void printf ( const char *format, ...) { + + char **arg = (char **)&format; + int c; + char buf[20]; + + arg++; + + while ((c = *format++) != 0){ + if( c != '%') + kterm_put(c); + else{ + char *p, *p2; + int pad0 = 0, pad = 0; + + c = *format++; + if(c =='0'){ + pad0 = 1; + c = *format++; + } + + if ( c >= '0' && c <= '9'){ + pad = c - '0'; + c = *format++; + } + + switch (c) + { + case 'd': + + case 'u': + case 'x': + itoa(buf, c, *((int *) arg++)); + + p = buf; + goto string; + break; + + case 's': + p = *arg++; + if(!p) + p = "(null)"; + + string: + for (p2 = p; *p2; p2++); + for (; p2 < p + pad; p2++) + kterm_put(pad0 ? '0': ' '); + while (*p) + kterm_put(*p++); + break; + + + default: + kterm_put(*((int *)arg++)); + break; + } + } + } +} \ No newline at end of file diff --git a/src/kernel/arch/i386/tty/kterm.h b/src/kernel/arch/i386/tty/kterm.h index f1570c6..d9f704f 100644 --- a/src/kernel/arch/i386/tty/kterm.h +++ b/src/kernel/arch/i386/tty/kterm.h @@ -15,10 +15,16 @@ void kterm_putat(char, uint8_t, size_t, size_t); void kterm_put(char); void kterm_write(const char*, size_t); void kterm_writestring(const char*); - void kterm_scrollup(); + +void printf ( const char *format, ...); + +static void itoa (char *buf, int base, int d); + #define KernelTag "[Kernel]: " #define AS_KERNEL() ( kterm_setcolor(VGA_COLOR_LIGHT_BLUE),\ kterm_write(KernelTag, 10 ), \ - kterm_resetcolor()) \ No newline at end of file + kterm_resetcolor()) + + diff --git a/src/kernel/time.h b/src/kernel/time.h new file mode 100644 index 0000000..6a098b7 --- /dev/null +++ b/src/kernel/time.h @@ -0,0 +1,151 @@ +#define CURRENT_YEAR 2021 // Change this each year! + +int century_register = 0x00; // Set by ACPI table parsing code if possible + +unsigned char second; +unsigned char minute; +unsigned char hour; +unsigned char day; +unsigned char month; +unsigned int year; + + + +enum { + cmos_address = 0x70, + cmos_data = 0x71 +}; + +int get_update_in_progress_flag() { + outb(cmos_address, 0x0A); + return (inb(cmos_data) & 0x80); +} + +unsigned char get_RTC_register(int reg) { + outb(cmos_address, reg); + return inb(cmos_data); +} + +void read_rtc() { + unsigned char century; + unsigned char last_second; + unsigned char last_minute; + unsigned char last_hour; + unsigned char last_day; + unsigned char last_month; + unsigned char last_year; + unsigned char last_century; + unsigned char registerB; + + // Note: This uses the "read registers until you get the same values twice in a row" technique + // to avoid getting dodgy/inconsistent values due to RTC updates + + while (get_update_in_progress_flag()); // Make sure an update isn't in progress + second = get_RTC_register(0x00); + minute = get_RTC_register(0x02); + hour = get_RTC_register(0x04); + day = get_RTC_register(0x07); + month = get_RTC_register(0x08); + year = get_RTC_register(0x09); + if(century_register != 0) { + century = get_RTC_register(century_register); + } + + do { + last_second = second; + last_minute = minute; + last_hour = hour; + last_day = day; + last_month = month; + last_year = year; + last_century = century; + + while (get_update_in_progress_flag()); // Make sure an update isn't in progress + second = get_RTC_register(0x00); + minute = get_RTC_register(0x02); + hour = get_RTC_register(0x04); + day = get_RTC_register(0x07); + month = get_RTC_register(0x08); + year = get_RTC_register(0x09); + if(century_register != 0) { + century = get_RTC_register(century_register); + } + } while( (last_second != second) || (last_minute != minute) || (last_hour != hour) || + (last_day != day) || (last_month != month) || (last_year != year) || + (last_century != century) ); + + registerB = get_RTC_register(0x0B); + + // Convert BCD to binary values if necessary + + if (!(registerB & 0x04)) { + second = (second & 0x0F) + ((second / 16) * 10); + minute = (minute & 0x0F) + ((minute / 16) * 10); + hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80); + day = (day & 0x0F) + ((day / 16) * 10); + month = (month & 0x0F) + ((month / 16) * 10); + year = (year & 0x0F) + ((year / 16) * 10); + if(century_register != 0) { + century = (century & 0x0F) + ((century / 16) * 10); + } + } + + // Convert 12 hour clock to 24 hour clock if necessary + + if (!(registerB & 0x02) && (hour & 0x80)) { + hour = ((hour & 0x7F) + 12) % 24; + } + + // Calculate the full (4-digit) year + + if(century_register != 0) { + year += century * 100; + } else { + year += (CURRENT_YEAR / 100) * 100; + if(year < CURRENT_YEAR) year += 100; + } +} + + +/* +void ReadFromCMOS(unsigned char array[]) +{ + unsigned char tvalue, index; + + for (index = 0; index < 128; index++) + { + asm( + "cli\n\t" // Disable interrupts + "mov al, index\n\t" // Move index address + // since the 0x80 bit of al is not set, NMI is active + "out 0x70,al\n\t" // Copy address to CMOS register + // some kind of real delay here is probably best + "in al,0x71\n\t" // Fetch 1 byte to al + "sti\n\t" // Enable interrupts + "mov tvalue,al\n\t"); + + array[index] = tvalue; + } +} +*/ + +/* +void WriteTOCMOS(unsigned char array[]) +{ + unsigned char index; + + for(index = 0; index < 128; index++) + { + unsigned char tvalue = array[index]; + + asm("cli\n\t" // Clear interrupts + "mov al,index\n\t" // move index address + "out 0x70,al\n\t" // copy address to CMOS register + /* some kind of real delay here is probably best + "mov al,tvalue\n\t" // move value to al + "out 0x71,al\n\t" // write 1 byte to CMOS + "sti\n\\t" ); // Enable interrupts + + } +} +*/ \ No newline at end of file -- 2.39.5 From 63ea825e2e2a5dfc123c266a49b7967b4e82bed5 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 18 May 2021 21:11:48 +0100 Subject: [PATCH 007/115] Added CMOS time read function, Added cariage return support to kterm --- src/kernel/arch/i386/tty/kterm.c | 105 ++++++++++++++++++++- src/kernel/arch/i386/tty/kterm.h | 10 +- src/kernel/time.h | 151 +++++++++++++++++++++++++++++++ 3 files changed, 261 insertions(+), 5 deletions(-) create mode 100644 src/kernel/time.h diff --git a/src/kernel/arch/i386/tty/kterm.c b/src/kernel/arch/i386/tty/kterm.c index 6dab47f..7ec9ae1 100644 --- a/src/kernel/arch/i386/tty/kterm.c +++ b/src/kernel/arch/i386/tty/kterm.c @@ -62,15 +62,17 @@ void kterm_scrollup(){ } void kterm_put (char c) { - if(++kterm_column == VGA_WIDTH || c == '\n' ) { kterm_column = 0; - if(kterm_row == VGA_HEIGHT-1) { + if(kterm_row == VGA_HEIGHT-1 ) { kterm_scrollup(); } else { kterm_row ++; } - + } + if ( c == '\r'){ + kterm_column = 0; + return; } if(c == '\n') return; @@ -89,3 +91,100 @@ void kterm_writestring(const char* data ){ AS_KERNEL(); kterm_write(data, strlen(data)); } + + +static void itoa (char *buf, int base, int d) { + char *p = buf; + char *p1, *p2; + unsigned long ud = d; + int divisor = 10; + if ( base == 'd' && d < 0){ + *p++ = '-'; + buf++; + ud = -d; + } else if (base == 'x'){ + divisor = 16; + } + + do { + int remainder = ud % divisor; + + *p++ = (remainder < 10 ) ? remainder + '0' : remainder + 'a' -10; + } while(ud /= divisor); + + /*terminate buf*/ + *p =0; + p1 = buf; + p2 = p -1; + + while (p1 < p2) + { + char tmp = *p1; + *p1 = *p2; + *p2 = tmp; + p1++; + p2--; + + } + +} + +void printf ( const char *format, ...) { + + char **arg = (char **)&format; + int c; + char buf[20]; + + arg++; + + while ((c = *format++) != 0){ + if( c != '%') + kterm_put(c); + else{ + char *p, *p2; + int pad0 = 0, pad = 0; + + c = *format++; + if(c =='0'){ + pad0 = 1; + c = *format++; + } + + if ( c >= '0' && c <= '9'){ + pad = c - '0'; + c = *format++; + } + + switch (c) + { + case 'd': + + case 'u': + case 'x': + itoa(buf, c, *((int *) arg++)); + + p = buf; + goto string; + break; + + case 's': + p = *arg++; + if(!p) + p = "(null)"; + + string: + for (p2 = p; *p2; p2++); + for (; p2 < p + pad; p2++) + kterm_put(pad0 ? '0': ' '); + while (*p) + kterm_put(*p++); + break; + + + default: + kterm_put(*((int *)arg++)); + break; + } + } + } +} \ No newline at end of file diff --git a/src/kernel/arch/i386/tty/kterm.h b/src/kernel/arch/i386/tty/kterm.h index f1570c6..d9f704f 100644 --- a/src/kernel/arch/i386/tty/kterm.h +++ b/src/kernel/arch/i386/tty/kterm.h @@ -15,10 +15,16 @@ void kterm_putat(char, uint8_t, size_t, size_t); void kterm_put(char); void kterm_write(const char*, size_t); void kterm_writestring(const char*); - void kterm_scrollup(); + +void printf ( const char *format, ...); + +static void itoa (char *buf, int base, int d); + #define KernelTag "[Kernel]: " #define AS_KERNEL() ( kterm_setcolor(VGA_COLOR_LIGHT_BLUE),\ kterm_write(KernelTag, 10 ), \ - kterm_resetcolor()) \ No newline at end of file + kterm_resetcolor()) + + diff --git a/src/kernel/time.h b/src/kernel/time.h new file mode 100644 index 0000000..6a098b7 --- /dev/null +++ b/src/kernel/time.h @@ -0,0 +1,151 @@ +#define CURRENT_YEAR 2021 // Change this each year! + +int century_register = 0x00; // Set by ACPI table parsing code if possible + +unsigned char second; +unsigned char minute; +unsigned char hour; +unsigned char day; +unsigned char month; +unsigned int year; + + + +enum { + cmos_address = 0x70, + cmos_data = 0x71 +}; + +int get_update_in_progress_flag() { + outb(cmos_address, 0x0A); + return (inb(cmos_data) & 0x80); +} + +unsigned char get_RTC_register(int reg) { + outb(cmos_address, reg); + return inb(cmos_data); +} + +void read_rtc() { + unsigned char century; + unsigned char last_second; + unsigned char last_minute; + unsigned char last_hour; + unsigned char last_day; + unsigned char last_month; + unsigned char last_year; + unsigned char last_century; + unsigned char registerB; + + // Note: This uses the "read registers until you get the same values twice in a row" technique + // to avoid getting dodgy/inconsistent values due to RTC updates + + while (get_update_in_progress_flag()); // Make sure an update isn't in progress + second = get_RTC_register(0x00); + minute = get_RTC_register(0x02); + hour = get_RTC_register(0x04); + day = get_RTC_register(0x07); + month = get_RTC_register(0x08); + year = get_RTC_register(0x09); + if(century_register != 0) { + century = get_RTC_register(century_register); + } + + do { + last_second = second; + last_minute = minute; + last_hour = hour; + last_day = day; + last_month = month; + last_year = year; + last_century = century; + + while (get_update_in_progress_flag()); // Make sure an update isn't in progress + second = get_RTC_register(0x00); + minute = get_RTC_register(0x02); + hour = get_RTC_register(0x04); + day = get_RTC_register(0x07); + month = get_RTC_register(0x08); + year = get_RTC_register(0x09); + if(century_register != 0) { + century = get_RTC_register(century_register); + } + } while( (last_second != second) || (last_minute != minute) || (last_hour != hour) || + (last_day != day) || (last_month != month) || (last_year != year) || + (last_century != century) ); + + registerB = get_RTC_register(0x0B); + + // Convert BCD to binary values if necessary + + if (!(registerB & 0x04)) { + second = (second & 0x0F) + ((second / 16) * 10); + minute = (minute & 0x0F) + ((minute / 16) * 10); + hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80); + day = (day & 0x0F) + ((day / 16) * 10); + month = (month & 0x0F) + ((month / 16) * 10); + year = (year & 0x0F) + ((year / 16) * 10); + if(century_register != 0) { + century = (century & 0x0F) + ((century / 16) * 10); + } + } + + // Convert 12 hour clock to 24 hour clock if necessary + + if (!(registerB & 0x02) && (hour & 0x80)) { + hour = ((hour & 0x7F) + 12) % 24; + } + + // Calculate the full (4-digit) year + + if(century_register != 0) { + year += century * 100; + } else { + year += (CURRENT_YEAR / 100) * 100; + if(year < CURRENT_YEAR) year += 100; + } +} + + +/* +void ReadFromCMOS(unsigned char array[]) +{ + unsigned char tvalue, index; + + for (index = 0; index < 128; index++) + { + asm( + "cli\n\t" // Disable interrupts + "mov al, index\n\t" // Move index address + // since the 0x80 bit of al is not set, NMI is active + "out 0x70,al\n\t" // Copy address to CMOS register + // some kind of real delay here is probably best + "in al,0x71\n\t" // Fetch 1 byte to al + "sti\n\t" // Enable interrupts + "mov tvalue,al\n\t"); + + array[index] = tvalue; + } +} +*/ + +/* +void WriteTOCMOS(unsigned char array[]) +{ + unsigned char index; + + for(index = 0; index < 128; index++) + { + unsigned char tvalue = array[index]; + + asm("cli\n\t" // Clear interrupts + "mov al,index\n\t" // move index address + "out 0x70,al\n\t" // copy address to CMOS register + /* some kind of real delay here is probably best + "mov al,tvalue\n\t" // move value to al + "out 0x71,al\n\t" // write 1 byte to CMOS + "sti\n\\t" ); // Enable interrupts + + } +} +*/ \ No newline at end of file -- 2.39.5 From e0dfa69df8b662d9ab51adb832787be41ab22bcd Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 18 May 2021 21:13:14 +0100 Subject: [PATCH 008/115] Removed itoa and printf from idt --- src/kernel/arch/i386/idt/idt.cpp | 97 -------------------------------- src/kernel/arch/i386/idt/idt.h | 9 ++- 2 files changed, 4 insertions(+), 102 deletions(-) diff --git a/src/kernel/arch/i386/idt/idt.cpp b/src/kernel/arch/i386/idt/idt.cpp index d515272..165e7a8 100644 --- a/src/kernel/arch/i386/idt/idt.cpp +++ b/src/kernel/arch/i386/idt/idt.cpp @@ -1,102 +1,5 @@ #include "idt.h" -static void itoa (char *buf, int base, int d) { - char *p = buf; - char *p1, *p2; - unsigned long ud = d; - int divisor = 10; - if ( base == 'd' && d < 0){ - *p++ = '-'; - buf++; - ud = -d; - } else if (base == 'x'){ - divisor = 16; - } - - do { - int remainder = ud % divisor; - - *p++ = (remainder < 10 ) ? remainder + '0' : remainder + 'a' -10; - } while(ud /= divisor); - - /*terminate buf*/ - *p =0; - p1 = buf; - p2 = p -1; - - while (p1 < p2) - { - char tmp = *p1; - *p1 = *p2; - *p2 = tmp; - p1++; - p2--; - - } - -} - -void printf ( const char *format, ...) { - - AS_KERNEL(); - char **arg = (char **)&format; - int c; - char buf[20]; - - arg++; - - while ((c = *format++) != 0){ - if( c != '%') - kterm_put(c); - else{ - char *p, *p2; - int pad0 = 0, pad = 0; - - c = *format++; - if(c =='0'){ - pad0 = 1; - c = *format++; - } - - if ( c >= '0' && c <= '9'){ - pad = c - '0'; - c = *format++; - } - - switch (c) - { - case 'd': - - case 'u': - case 'x': - itoa(buf, c, *((int *) arg++)); - - p = buf; - goto string; - break; - - case 's': - p = *arg++; - if(!p) - p = "(null)"; - - string: - for (p2 = p; *p2; p2++); - for (; p2 < p + pad; p2++) - kterm_put(pad0 ? '0': ' '); - while (*p) - kterm_put(*p++); - break; - - - default: - kterm_put(*((int *)arg++)); - break; - } - } - } -} - IDT_entry idt_table[256]; IDT_ptr idt_ptr; diff --git a/src/kernel/arch/i386/idt/idt.h b/src/kernel/arch/i386/idt/idt.h index 7281fa9..b616b85 100644 --- a/src/kernel/arch/i386/idt/idt.h +++ b/src/kernel/arch/i386/idt/idt.h @@ -3,14 +3,13 @@ #include "stdint.h" #include "stddef.h" #include "../vga/colors.h" -#include "../pic/pic.h"; +#include "../pic/pic.h" +extern "C"{ + #include "../tty/kterm.h" +} #define AS_KERNEL() ( kterm_writestring("[KERNEL]:")) -extern "C" void kterm_writestring(const char* data ); -extern "C" void kterm_putat(char, uint8_t, size_t, size_t); -extern "C" void kterm_put(char); - extern "C" { struct __attribute__((__packed__)) IDT_entry { -- 2.39.5 From f71a3a8ed66266a913bae5de88060e5476d4f308 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 18 May 2021 21:13:14 +0100 Subject: [PATCH 009/115] Removed itoa and printf from idt --- src/kernel/arch/i386/idt/idt.cpp | 97 -------------------------------- src/kernel/arch/i386/idt/idt.h | 9 ++- 2 files changed, 4 insertions(+), 102 deletions(-) diff --git a/src/kernel/arch/i386/idt/idt.cpp b/src/kernel/arch/i386/idt/idt.cpp index d515272..165e7a8 100644 --- a/src/kernel/arch/i386/idt/idt.cpp +++ b/src/kernel/arch/i386/idt/idt.cpp @@ -1,102 +1,5 @@ #include "idt.h" -static void itoa (char *buf, int base, int d) { - char *p = buf; - char *p1, *p2; - unsigned long ud = d; - int divisor = 10; - if ( base == 'd' && d < 0){ - *p++ = '-'; - buf++; - ud = -d; - } else if (base == 'x'){ - divisor = 16; - } - - do { - int remainder = ud % divisor; - - *p++ = (remainder < 10 ) ? remainder + '0' : remainder + 'a' -10; - } while(ud /= divisor); - - /*terminate buf*/ - *p =0; - p1 = buf; - p2 = p -1; - - while (p1 < p2) - { - char tmp = *p1; - *p1 = *p2; - *p2 = tmp; - p1++; - p2--; - - } - -} - -void printf ( const char *format, ...) { - - AS_KERNEL(); - char **arg = (char **)&format; - int c; - char buf[20]; - - arg++; - - while ((c = *format++) != 0){ - if( c != '%') - kterm_put(c); - else{ - char *p, *p2; - int pad0 = 0, pad = 0; - - c = *format++; - if(c =='0'){ - pad0 = 1; - c = *format++; - } - - if ( c >= '0' && c <= '9'){ - pad = c - '0'; - c = *format++; - } - - switch (c) - { - case 'd': - - case 'u': - case 'x': - itoa(buf, c, *((int *) arg++)); - - p = buf; - goto string; - break; - - case 's': - p = *arg++; - if(!p) - p = "(null)"; - - string: - for (p2 = p; *p2; p2++); - for (; p2 < p + pad; p2++) - kterm_put(pad0 ? '0': ' '); - while (*p) - kterm_put(*p++); - break; - - - default: - kterm_put(*((int *)arg++)); - break; - } - } - } -} - IDT_entry idt_table[256]; IDT_ptr idt_ptr; diff --git a/src/kernel/arch/i386/idt/idt.h b/src/kernel/arch/i386/idt/idt.h index 7281fa9..b616b85 100644 --- a/src/kernel/arch/i386/idt/idt.h +++ b/src/kernel/arch/i386/idt/idt.h @@ -3,14 +3,13 @@ #include "stdint.h" #include "stddef.h" #include "../vga/colors.h" -#include "../pic/pic.h"; +#include "../pic/pic.h" +extern "C"{ + #include "../tty/kterm.h" +} #define AS_KERNEL() ( kterm_writestring("[KERNEL]:")) -extern "C" void kterm_writestring(const char* data ); -extern "C" void kterm_putat(char, uint8_t, size_t, size_t); -extern "C" void kterm_put(char); - extern "C" { struct __attribute__((__packed__)) IDT_entry { -- 2.39.5 From 48b65b22768bc1d74d8289033c45e58fc458bd09 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 18 May 2021 21:14:26 +0100 Subject: [PATCH 010/115] Kernel now enter continuous time telling mode --- src/kernel/kernel.cpp | 9 +++++++++ src/kernel/kernel.h | 1 + 2 files changed, 10 insertions(+) diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index edd7f22..1b87e9f 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -144,6 +144,15 @@ extern "C" { asm volatile ("int $4"); + + + while (true){ + // Read time indefinetely + read_rtc(); + printf( "(YY-MM-DD h:mm:ss): %2d-%2d-%2d %2d:%2d:%2d\r" ,year, month, day, hour, minute, second); + delay(1000); + } + /** Lets start using the serial port for debugging .. **/ // Hopefully once we go into realmode or do something that // cause the screen to go black.. this serial comms part will give diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index ced720a..eed09c0 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -7,3 +7,4 @@ extern "C" { #include "arch/i386/idt/idt.h" #include "MMU.h" #include "io.h" +#include "time.h" -- 2.39.5 From e84d196b002bb97ddf164796d14c6397de6e2017 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 18 May 2021 21:14:26 +0100 Subject: [PATCH 011/115] Kernel now enter continuous time telling mode --- src/kernel/kernel.cpp | 9 +++++++++ src/kernel/kernel.h | 1 + 2 files changed, 10 insertions(+) diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index edd7f22..1b87e9f 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -144,6 +144,15 @@ extern "C" { asm volatile ("int $4"); + + + while (true){ + // Read time indefinetely + read_rtc(); + printf( "(YY-MM-DD h:mm:ss): %2d-%2d-%2d %2d:%2d:%2d\r" ,year, month, day, hour, minute, second); + delay(1000); + } + /** Lets start using the serial port for debugging .. **/ // Hopefully once we go into realmode or do something that // cause the screen to go black.. this serial comms part will give diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index ced720a..eed09c0 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -7,3 +7,4 @@ extern "C" { #include "arch/i386/idt/idt.h" #include "MMU.h" #include "io.h" +#include "time.h" -- 2.39.5 From 83d220019cbdd7f7ced9c798f3507a0b9dab11dc Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 22 May 2021 19:24:29 +0100 Subject: [PATCH 012/115] Nicer time print --- src/kernel/kernel.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 1b87e9f..d27944d 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -149,7 +149,7 @@ extern "C" { while (true){ // Read time indefinetely read_rtc(); - printf( "(YY-MM-DD h:mm:ss): %2d-%2d-%2d %2d:%2d:%2d\r" ,year, month, day, hour, minute, second); + printf( "UTC time: %2d-%2d-%2d %2d:%2d:%2d : (YY-MM-DD h:mm:ss)\r" ,year, month, day, hour, minute, second); delay(1000); } -- 2.39.5 From 595a7d51635835fc626d2025a68af039153527f8 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 22 May 2021 19:24:29 +0100 Subject: [PATCH 013/115] Nicer time print --- src/kernel/kernel.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 1b87e9f..d27944d 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -149,7 +149,7 @@ extern "C" { while (true){ // Read time indefinetely read_rtc(); - printf( "(YY-MM-DD h:mm:ss): %2d-%2d-%2d %2d:%2d:%2d\r" ,year, month, day, hour, minute, second); + printf( "UTC time: %2d-%2d-%2d %2d:%2d:%2d : (YY-MM-DD h:mm:ss)\r" ,year, month, day, hour, minute, second); delay(1000); } -- 2.39.5 From 24a855bb3bb84e90975f9eaddec9d1e95835e7aa Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 28 May 2021 22:18:50 +0100 Subject: [PATCH 014/115] Fix up wrong interrupt handler numbers in boot.s --- src/kernel/arch/i386/boot.s | 88 +++++++++++++++++++++++-------------- 1 file changed, 56 insertions(+), 32 deletions(-) diff --git a/src/kernel/arch/i386/boot.s b/src/kernel/arch/i386/boot.s index 17432e4..2de2f8d 100644 --- a/src/kernel/arch/i386/boot.s +++ b/src/kernel/arch/i386/boot.s @@ -273,116 +273,140 @@ irs31: irq0: cli push $0 - push $32 - jmp irs_common + push $0 + jmp irq_common .globl irq1 irq1: cli push $0 - push $33 - jmp irs_common + push $1 + jmp irq_common .globl irq2 irq2: cli push $0 - push $34 - jmp irs_common + push $2 + jmp irq_common .globl irq3 irq3: cli push $0 - push $35 - jmp irs_common + push $3 + jmp irq_common .globl irq4 irq4: cli push $0 - push $36 - jmp irs_common + push $4 + jmp irq_common .globl irq5 irq5: cli push $0 - push $37 - jmp irs_common + push $5 + jmp irq_common .globl irq6 irq6: cli push $0 - push $38 - jmp irs_common + push $6 + jmp irq_common .globl irq7 irq7: cli push $0 - push $39 - jmp irs_common + push $7 + jmp irq_common .globl irq8 irq8: cli push $0 - push $40 - jmp irs_common + push $8 + jmp irq_common .globl irq9 irq9: cli push $0 - push $41 - jmp irs_common + push $9 + jmp irq_common .globl irq10 irq10: cli push $0 - push $42 - jmp irs_common + push $10 + jmp irq_common .globl irq11 irq11: cli push $0 - push $43 - jmp irs_common + push $11 + jmp irq_common .globl irq12 irq12: cli push $0 - push $44 - jmp irs_common + push $12 + jmp irq_common .globl irq13 irq13: cli push $0 - push $45 - jmp irs_common + push $13 + jmp irq_common .globl irq14 irq14: cli push $0 - push $46 - jmp irs_common + push $14 + jmp irq_common .globl irq15 irq15: cli push $0 - push $47 - jmp irs_common + push $15 + jmp irq_common +irq_common: + pusha + mov %ds, %ax + push %eax + + mov $0x10, %ax + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + call irq_handler + + pop %eax + + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + popa + add $8, %esp # cleans push error and irs code + sti + iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP irs_common: -- 2.39.5 From 5f50f8c01322124b80b498277949a8b60882724d Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 28 May 2021 22:18:50 +0100 Subject: [PATCH 015/115] Fix up wrong interrupt handler numbers in boot.s --- src/kernel/arch/i386/boot.s | 88 +++++++++++++++++++++++-------------- 1 file changed, 56 insertions(+), 32 deletions(-) diff --git a/src/kernel/arch/i386/boot.s b/src/kernel/arch/i386/boot.s index 17432e4..2de2f8d 100644 --- a/src/kernel/arch/i386/boot.s +++ b/src/kernel/arch/i386/boot.s @@ -273,116 +273,140 @@ irs31: irq0: cli push $0 - push $32 - jmp irs_common + push $0 + jmp irq_common .globl irq1 irq1: cli push $0 - push $33 - jmp irs_common + push $1 + jmp irq_common .globl irq2 irq2: cli push $0 - push $34 - jmp irs_common + push $2 + jmp irq_common .globl irq3 irq3: cli push $0 - push $35 - jmp irs_common + push $3 + jmp irq_common .globl irq4 irq4: cli push $0 - push $36 - jmp irs_common + push $4 + jmp irq_common .globl irq5 irq5: cli push $0 - push $37 - jmp irs_common + push $5 + jmp irq_common .globl irq6 irq6: cli push $0 - push $38 - jmp irs_common + push $6 + jmp irq_common .globl irq7 irq7: cli push $0 - push $39 - jmp irs_common + push $7 + jmp irq_common .globl irq8 irq8: cli push $0 - push $40 - jmp irs_common + push $8 + jmp irq_common .globl irq9 irq9: cli push $0 - push $41 - jmp irs_common + push $9 + jmp irq_common .globl irq10 irq10: cli push $0 - push $42 - jmp irs_common + push $10 + jmp irq_common .globl irq11 irq11: cli push $0 - push $43 - jmp irs_common + push $11 + jmp irq_common .globl irq12 irq12: cli push $0 - push $44 - jmp irs_common + push $12 + jmp irq_common .globl irq13 irq13: cli push $0 - push $45 - jmp irs_common + push $13 + jmp irq_common .globl irq14 irq14: cli push $0 - push $46 - jmp irs_common + push $14 + jmp irq_common .globl irq15 irq15: cli push $0 - push $47 - jmp irs_common + push $15 + jmp irq_common +irq_common: + pusha + mov %ds, %ax + push %eax + + mov $0x10, %ax + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + call irq_handler + + pop %eax + + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + popa + add $8, %esp # cleans push error and irs code + sti + iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP irs_common: -- 2.39.5 From 04f941a625d225b3edcb5abca860b4047dd73ce8 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 28 May 2021 22:20:13 +0100 Subject: [PATCH 016/115] Kernel now responding to keyboard interrupts --- src/kernel/arch/i386/idt/idt.cpp | 52 ++++++++++++++++++++++++++++++-- src/kernel/kernel.cpp | 9 +++--- 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/kernel/arch/i386/idt/idt.cpp b/src/kernel/arch/i386/idt/idt.cpp index 165e7a8..b81ace6 100644 --- a/src/kernel/arch/i386/idt/idt.cpp +++ b/src/kernel/arch/i386/idt/idt.cpp @@ -1,5 +1,5 @@ #include "idt.h" - +#include "Scancodes.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; @@ -17,7 +17,7 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ void irs_handler (registers regs) { kterm_writestring("received interrupt!\n"); - printf(" Interrupt number: %d \n", regs.int_no); + printf("(IRS) Interrupt number: %d \n", regs.int_no); if( regs.int_no == 13){ printf(" Error code: %d \n", regs.err_code); @@ -28,6 +28,52 @@ void irs_handler (registers regs) { +void irq_handler (registers regs) { + + + if ( regs.int_no != 0) { + kterm_writestring("received interrupt!\n"); + printf("(IRQ) Interrupt number: %d \n", regs.int_no); + + } + + if ( regs.int_no == 1 ){ + // Keyboard interrupt !! + + int scan; + register int i; + + // Read scancode + + scan = inb(0x60); + + // Send ack message! + i = inb(0x61); + outb(0x61, i|0x80); + outb(0x61, i); + kterm_writestring("A key was pressed/released\n"); + printf( "Scancode: %x\n", scan); + + + } + + + + outb(0x20, 0x20); // send end of interrupt to master + + if ( regs.int_no > 8 && regs.int_no <= 15) { + outb(0xA0, 0x20); // send end of interrupt to slave + } + + + if( regs.int_no == 13){ + printf(" Error code: %d \n", regs.err_code); + + } + +} + + @@ -39,7 +85,7 @@ void init_idt(){ // TODO: Set everything to zero first - set_id_entry(0, (uint32_t) irs0 , 0x08, 0x8E); + set_id_entry(0, (uint32_t) irs0 , 0x08, 0x8F); set_id_entry(1, (uint32_t) irs1 , 0x08, 0x8E); set_id_entry(2, (uint32_t) irs2 , 0x08, 0x8E); set_id_entry(3, (uint32_t) irs3 , 0x08, 0x8E); diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index d27944d..6764040 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -140,18 +140,17 @@ extern "C" { /** test interrupt handlers **/ - asm volatile ("int $0x03"); + //asm volatile ("int $0x03"); - asm volatile ("int $4"); + //asm volatile ("int $0x04"); - - while (true){ - // Read time indefinetely + //Read time indefinetely read_rtc(); printf( "UTC time: %2d-%2d-%2d %2d:%2d:%2d : (YY-MM-DD h:mm:ss)\r" ,year, month, day, hour, minute, second); delay(1000); } + /** Lets start using the serial port for debugging .. **/ // Hopefully once we go into realmode or do something that -- 2.39.5 From 59bcc17668dc7ec9b053b6b18c46a19f55767014 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 28 May 2021 22:20:13 +0100 Subject: [PATCH 017/115] Kernel now responding to keyboard interrupts --- src/kernel/arch/i386/idt/idt.cpp | 52 ++++++++++++++++++++++++++++++-- src/kernel/kernel.cpp | 9 +++--- 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/src/kernel/arch/i386/idt/idt.cpp b/src/kernel/arch/i386/idt/idt.cpp index 165e7a8..b81ace6 100644 --- a/src/kernel/arch/i386/idt/idt.cpp +++ b/src/kernel/arch/i386/idt/idt.cpp @@ -1,5 +1,5 @@ #include "idt.h" - +#include "Scancodes.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; @@ -17,7 +17,7 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ void irs_handler (registers regs) { kterm_writestring("received interrupt!\n"); - printf(" Interrupt number: %d \n", regs.int_no); + printf("(IRS) Interrupt number: %d \n", regs.int_no); if( regs.int_no == 13){ printf(" Error code: %d \n", regs.err_code); @@ -28,6 +28,52 @@ void irs_handler (registers regs) { +void irq_handler (registers regs) { + + + if ( regs.int_no != 0) { + kterm_writestring("received interrupt!\n"); + printf("(IRQ) Interrupt number: %d \n", regs.int_no); + + } + + if ( regs.int_no == 1 ){ + // Keyboard interrupt !! + + int scan; + register int i; + + // Read scancode + + scan = inb(0x60); + + // Send ack message! + i = inb(0x61); + outb(0x61, i|0x80); + outb(0x61, i); + kterm_writestring("A key was pressed/released\n"); + printf( "Scancode: %x\n", scan); + + + } + + + + outb(0x20, 0x20); // send end of interrupt to master + + if ( regs.int_no > 8 && regs.int_no <= 15) { + outb(0xA0, 0x20); // send end of interrupt to slave + } + + + if( regs.int_no == 13){ + printf(" Error code: %d \n", regs.err_code); + + } + +} + + @@ -39,7 +85,7 @@ void init_idt(){ // TODO: Set everything to zero first - set_id_entry(0, (uint32_t) irs0 , 0x08, 0x8E); + set_id_entry(0, (uint32_t) irs0 , 0x08, 0x8F); set_id_entry(1, (uint32_t) irs1 , 0x08, 0x8E); set_id_entry(2, (uint32_t) irs2 , 0x08, 0x8E); set_id_entry(3, (uint32_t) irs3 , 0x08, 0x8E); diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index d27944d..6764040 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -140,18 +140,17 @@ extern "C" { /** test interrupt handlers **/ - asm volatile ("int $0x03"); + //asm volatile ("int $0x03"); - asm volatile ("int $4"); + //asm volatile ("int $0x04"); - - while (true){ - // Read time indefinetely + //Read time indefinetely read_rtc(); printf( "UTC time: %2d-%2d-%2d %2d:%2d:%2d : (YY-MM-DD h:mm:ss)\r" ,year, month, day, hour, minute, second); delay(1000); } + /** Lets start using the serial port for debugging .. **/ // Hopefully once we go into realmode or do something that -- 2.39.5 From 7409e579c8935accd2c0d076e3963fd6ffa744c2 Mon Sep 17 00:00:00 2001 From: Nigel Date: Wed, 21 Jul 2021 21:31:57 +0100 Subject: [PATCH 018/115] Basic keyboard input --- .../Screenshot from 2021-06-21 14-26-39.png | 3 + src/kernel/arch/i386/idt/idt.cpp | 2 +- src/kernel/arch/i386/idt/scancodes/set1.h | 184 ++++++++++++++++++ 3 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 screenshots/Screenshot from 2021-06-21 14-26-39.png create mode 100644 src/kernel/arch/i386/idt/scancodes/set1.h diff --git a/screenshots/Screenshot from 2021-06-21 14-26-39.png b/screenshots/Screenshot from 2021-06-21 14-26-39.png new file mode 100644 index 0000000..30c104f --- /dev/null +++ b/screenshots/Screenshot from 2021-06-21 14-26-39.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73b9d3ed540e1bc0b6d55114a00f9aa688006b38a542c1bf048d90b791a748ce +size 141605 diff --git a/src/kernel/arch/i386/idt/idt.cpp b/src/kernel/arch/i386/idt/idt.cpp index b81ace6..4722109 100644 --- a/src/kernel/arch/i386/idt/idt.cpp +++ b/src/kernel/arch/i386/idt/idt.cpp @@ -1,5 +1,5 @@ #include "idt.h" -#include "Scancodes.h" +//#include "scancodes/set1.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; diff --git a/src/kernel/arch/i386/idt/scancodes/set1.h b/src/kernel/arch/i386/idt/scancodes/set1.h new file mode 100644 index 0000000..2fe6b17 --- /dev/null +++ b/src/kernel/arch/i386/idt/scancodes/set1.h @@ -0,0 +1,184 @@ +#pragma once + + + + + + +// ScanCode set 1 +int ScanCodeToKeyCode [0xD8]; + +/* key pressed scancode */ +ScanCodeToKeyCode[0x01] = 4017; // escape pressed +ScanCodeToKeyCode[0x02] = 4018; // 1 pressed +ScanCodeToKeyCode[0x03] = 4019; // 2 pressed +ScanCodeToKeyCode[0x04] = 4020; // 3 pressed +ScanCodeToKeyCode[0x05] ="" // 4 pressed +ScanCodeToKeyCode[0x06] ="" // 5 pressed +ScanCodeToKeyCode[0x07] ="" // 6 pressed +ScanCodeToKeyCode[0x08] ="" // 7 pressed +ScanCodeToKeyCode[0x09] ="" // 8 pressed +ScanCodeToKeyCode[0x0A] ="" // 9 pressed +ScanCodeToKeyCode[0x0B] ="" // 0 (zero) pressed +ScanCodeToKeyCode[0x0C] ="" // - pressed +ScanCodeToKeyCode[0x0D] ="" // = pressed +ScanCodeToKeyCode[0x0E] ="" // backspace pressed +ScanCodeToKeyCode[0x0F] ="" // tab pressed +ScanCodeToKeyCode[0x10] ="" // Q pressed +ScanCodeToKeyCode[0x11] ="" // W pressed +ScanCodeToKeyCode[0x12] ="" // E pressed +ScanCodeToKeyCode[0x13] ="" // R pressed +ScanCodeToKeyCode[0x14] ="" // T pressed +ScanCodeToKeyCode[0x15] ="" // Y pressed +ScanCodeToKeyCode[0x16] ="" // U pressed +ScanCodeToKeyCode[0x17] ="" // I pressed +ScanCodeToKeyCode[0x18] ="" // O pressed +ScanCodeToKeyCode[0x19] ="" // P pressed +ScanCodeToKeyCode[0x1A] ="" // [ pressed +ScanCodeToKeyCode[0x1B] ="" // ] pressed +ScanCodeToKeyCode[0x1C] ="" // enter pressed +ScanCodeToKeyCode[0x1D] ="" // left control pressed +ScanCodeToKeyCode[0x1E] ="" // A pressed +ScanCodeToKeyCode[0x1F] ="" // S pressed +ScanCodeToKeyCode[0x20] ="" // D pressed +ScanCodeToKeyCode[0x21] ="" // F pressed +ScanCodeToKeyCode[0x22] ="" // G pressed +ScanCodeToKeyCode[0x23] ="" // H pressed +ScanCodeToKeyCode[0x24] ="" // J pressed +ScanCodeToKeyCode[0x25] ="" // K pressed +ScanCodeToKeyCode[0x26] ="" // L pressed +ScanCodeToKeyCode[0x27] ="" // ; pressed +ScanCodeToKeyCode[0x28] ="" // ' (single quote) pressed +ScanCodeToKeyCode[0x29] ="" // ` (back tick) pressed +ScanCodeToKeyCode[0x2A] ="" // left shift pressed +ScanCodeToKeyCode[0x2B] ="" // \ pressed +ScanCodeToKeyCode[0x2C] ="" // Z pressed +ScanCodeToKeyCode[0x2D] ="" // X pressed +ScanCodeToKeyCode[0x2E] ="" // C pressed +ScanCodeToKeyCode[0x2F] ="" // V pressed +ScanCodeToKeyCode[0x30] ="" // B pressed +ScanCodeToKeyCode[0x31] ="" // N pressed +ScanCodeToKeyCode[0x32] ="" // M pressed +ScanCodeToKeyCode[0x33] ="" // , pressed +ScanCodeToKeyCode[0x34] ="" // . pressed +ScanCodeToKeyCode[0x35] ="" // / pressed +ScanCodeToKeyCode[0x36] ="" // right shift pressed +ScanCodeToKeyCode[0x37] ="" // (keypad) * pressed +ScanCodeToKeyCode[0x38] ="" // left alt pressed +ScanCodeToKeyCode[0x39] ="" // space pressed +ScanCodeToKeyCode[0x3A] ="" // CapsLock pressed +ScanCodeToKeyCode[0x3B] ="" // F1 pressed +ScanCodeToKeyCode[0x3C] ="" // F2 pressed +ScanCodeToKeyCode[0x3D] ="" // F3 pressed +ScanCodeToKeyCode[0x3E] ="" // F4 pressed +ScanCodeToKeyCode[0x3F] ="" // F5 pressed +ScanCodeToKeyCode[0x40] ="" // F6 pressed +ScanCodeToKeyCode[0x41] ="" // F7 pressed +ScanCodeToKeyCode[0x42] ="" // F8 pressed +ScanCodeToKeyCode[0x43] ="" // F9 pressed +ScanCodeToKeyCode[0x44] ="" // F10 pressed +ScanCodeToKeyCode[0x45] ="" // NumberLock pressed +ScanCodeToKeyCode[0x46] ="" // ScrollLock pressed +ScanCodeToKeyCode[0x47] ="" // (keypad) 7 pressed +ScanCodeToKeyCode[0x48] ="" // (keypad) 8 pressed +ScanCodeToKeyCode[0x49] ="" // (keypad) 9 pressed +ScanCodeToKeyCode[0x4A] ="" // (keypad) - pressed +ScanCodeToKeyCode[0x4B] ="" // (keypad) 4 pressed +ScanCodeToKeyCode[0x4C] ="" // (keypad) 5 pressed +ScanCodeToKeyCode[0x4D] ="" // (keypad) 6 pressed +ScanCodeToKeyCode[0x4E] ="" // (keypad) + pressed +ScanCodeToKeyCode[0x4F] ="" // (keypad) 1 pressed +ScanCodeToKeyCode[0x50] ="" // (keypad) 2 pressed +ScanCodeToKeyCode[0x51] ="" // (keypad) 3 pressed +ScanCodeToKeyCode[0x52] ="" // (keypad) 0 pressed +ScanCodeToKeyCode[0x53] ="" // (keypad) . pressed +ScanCodeToKeyCode[0x57] ="" // F11 pressed +ScanCodeToKeyCode[0x58] ="" // F12 pressed + + +/* key released scanCode.""*/ +ScanCodeToKeyCode[0x81] ="" // escape released +ScanCodeToKeyCode[0x82] ="" // 1 released +ScanCodeToKeyCode[0x83] ="" // 2 released +ScanCodeToKeyCode[0x84] ="" // 3 released +ScanCodeToKeyCode[0x85] ="" // 4 released +ScanCodeToKeyCode[0x86] ="" // 5 released +ScanCodeToKeyCode[0x87] ="" // 6 released +ScanCodeToKeyCode[0x88] ="" // 7 released +ScanCodeToKeyCode[0x89] ="" // 8 released +ScanCodeToKeyCode[0x8A] ="" // 9 released +ScanCodeToKeyCode[0x8B] ="" // 0 (zero) released +ScanCodeToKeyCode[0x8C] ="" // - released +ScanCodeToKeyCode[0x8D] ="" // = released +ScanCodeToKeyCode[0x8E] ="" // backspace released +ScanCodeToKeyCode[0x8F] ="" // tab released +ScanCodeToKeyCode[0x90] ="" // Q released +ScanCodeToKeyCode[0x91] ="" // W released +ScanCodeToKeyCode[0x92] ="" // E released +ScanCodeToKeyCode[0x93] ="" // R released +ScanCodeToKeyCode[0x94] ="" // T released +ScanCodeToKeyCode[0x95] ="" // Y released +ScanCodeToKeyCode[0x96] ="" // U released +ScanCodeToKeyCode[0x97] ="" // I released +ScanCodeToKeyCode[0x98] ="" // O released +ScanCodeToKeyCode[0x99] ="" // P released +ScanCodeToKeyCode[0x9A] ="" // [ released +ScanCodeToKeyCode[0x9B] ="" // ] released +ScanCodeToKeyCode[0x9C] ="" // enter released +ScanCodeToKeyCode[0x9D] ="" // left control released +ScanCodeToKeyCode[0x9E] ="" // A released +ScanCodeToKeyCode[0x9F] ="" // S released +ScanCodeToKeyCode[0xA0] ="" // D released +ScanCodeToKeyCode[0xA1] ="" // F released +ScanCodeToKeyCode[0xA2] ="" // G released +ScanCodeToKeyCode[0xA3] ="" // H released +ScanCodeToKeyCode[0xA4] ="" // J released +ScanCodeToKeyCode[0xA5] ="" // K released +ScanCodeToKeyCode[0xA6] ="" // L released +ScanCodeToKeyCode[0xA7] ="" // ; released +ScanCodeToKeyCode[0xA8] ="" // ' (single quote) released +ScanCodeToKeyCode[0xA9] ="" // ` (back tick) released +ScanCodeToKeyCode[0xAA] ="" // left shift released +ScanCodeToKeyCode[0xAB] ="" // \ released +ScanCodeToKeyCode[0xAC] ="" // Z released +ScanCodeToKeyCode[0xAD] ="" // X released +ScanCodeToKeyCode[0xAE] ="" // C released +ScanCodeToKeyCode[0xAF] ="" // V released +ScanCodeToKeyCode[0xB0] ="" // B released +ScanCodeToKeyCode[0xB1] ="" // N released +ScanCodeToKeyCode[0xB2] ="" // M released +ScanCodeToKeyCode[0xB3] ="" // , released +ScanCodeToKeyCode[0xB4] ="" // . released +ScanCodeToKeyCode[0xB5] ="" // / released +ScanCodeToKeyCode[0xB6] ="" // right shift released +ScanCodeToKeyCode[0xB7] ="" // (keypad) * released +ScanCodeToKeyCode[0xB8] ="" // left alt released +ScanCodeToKeyCode[0xB9] ="" // space released +ScanCodeToKeyCode[0xBA] ="" // CapsLock released +ScanCodeToKeyCode[0xBB] ="" // F1 released +ScanCodeToKeyCode[0xBC] ="" // F2 released +ScanCodeToKeyCode[0xBD] ="" // F3 released +ScanCodeToKeyCode[0xBE] ="" // F4 released +ScanCodeToKeyCode[0xBF] ="" // F5 released +ScanCodeToKeyCode[0xC0] ="" // F6 released +ScanCodeToKeyCode[0xC1] ="" // F7 released +ScanCodeToKeyCode[0xC2] ="" // F8 released +ScanCodeToKeyCode[0xC3] ="" // F9 released +ScanCodeToKeyCode[0xC4] ="" // F10 released +ScanCodeToKeyCode[0xC5] ="" // NumberLock released +ScanCodeToKeyCode[0xC6] ="" // ScrollLock released +ScanCodeToKeyCode[0xC7] ="" // (keypad) 7 released +ScanCodeToKeyCode[0xC8] ="" // (keypad) 8 released +ScanCodeToKeyCode[0xC9] ="" // (keypad) 9 released +ScanCodeToKeyCode[0xCA] ="" // (keypad) - released +ScanCodeToKeyCode[0xCB] ="" // (keypad) 4 released +ScanCodeToKeyCode[0xCC] ="" // (keypad) 5 released +ScanCodeToKeyCode[0xCD] ="" // (keypad) 6 released +ScanCodeToKeyCode[0xCE] ="" // (keypad) + released +ScanCodeToKeyCode[0xCF] ="" // (keypad) 1 released +ScanCodeToKeyCode[0xD0] ="" // (keypad) 2 released +ScanCodeToKeyCode[0xD1] ="" // (keypad) 3 released +ScanCodeToKeyCode[0xD2] ="" // (keypad) 0 released +ScanCodeToKeyCode[0xD3] ="" // (keypad) . released +ScanCodeToKeyCode[0xD7] ="" // F11 released +ScanCodeToKeyCode[0xD8] ="" // F12 released \ No newline at end of file -- 2.39.5 From 9dc7a05da14ba40a09c0c138268b10688b52809f Mon Sep 17 00:00:00 2001 From: Nigel Date: Wed, 21 Jul 2021 21:31:57 +0100 Subject: [PATCH 019/115] Basic keyboard input --- .../Screenshot from 2021-06-21 14-26-39.png | 3 + src/kernel/arch/i386/idt/idt.cpp | 2 +- src/kernel/arch/i386/idt/scancodes/set1.h | 184 ++++++++++++++++++ 3 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 screenshots/Screenshot from 2021-06-21 14-26-39.png create mode 100644 src/kernel/arch/i386/idt/scancodes/set1.h diff --git a/screenshots/Screenshot from 2021-06-21 14-26-39.png b/screenshots/Screenshot from 2021-06-21 14-26-39.png new file mode 100644 index 0000000..30c104f --- /dev/null +++ b/screenshots/Screenshot from 2021-06-21 14-26-39.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:73b9d3ed540e1bc0b6d55114a00f9aa688006b38a542c1bf048d90b791a748ce +size 141605 diff --git a/src/kernel/arch/i386/idt/idt.cpp b/src/kernel/arch/i386/idt/idt.cpp index b81ace6..4722109 100644 --- a/src/kernel/arch/i386/idt/idt.cpp +++ b/src/kernel/arch/i386/idt/idt.cpp @@ -1,5 +1,5 @@ #include "idt.h" -#include "Scancodes.h" +//#include "scancodes/set1.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; diff --git a/src/kernel/arch/i386/idt/scancodes/set1.h b/src/kernel/arch/i386/idt/scancodes/set1.h new file mode 100644 index 0000000..2fe6b17 --- /dev/null +++ b/src/kernel/arch/i386/idt/scancodes/set1.h @@ -0,0 +1,184 @@ +#pragma once + + + + + + +// ScanCode set 1 +int ScanCodeToKeyCode [0xD8]; + +/* key pressed scancode */ +ScanCodeToKeyCode[0x01] = 4017; // escape pressed +ScanCodeToKeyCode[0x02] = 4018; // 1 pressed +ScanCodeToKeyCode[0x03] = 4019; // 2 pressed +ScanCodeToKeyCode[0x04] = 4020; // 3 pressed +ScanCodeToKeyCode[0x05] ="" // 4 pressed +ScanCodeToKeyCode[0x06] ="" // 5 pressed +ScanCodeToKeyCode[0x07] ="" // 6 pressed +ScanCodeToKeyCode[0x08] ="" // 7 pressed +ScanCodeToKeyCode[0x09] ="" // 8 pressed +ScanCodeToKeyCode[0x0A] ="" // 9 pressed +ScanCodeToKeyCode[0x0B] ="" // 0 (zero) pressed +ScanCodeToKeyCode[0x0C] ="" // - pressed +ScanCodeToKeyCode[0x0D] ="" // = pressed +ScanCodeToKeyCode[0x0E] ="" // backspace pressed +ScanCodeToKeyCode[0x0F] ="" // tab pressed +ScanCodeToKeyCode[0x10] ="" // Q pressed +ScanCodeToKeyCode[0x11] ="" // W pressed +ScanCodeToKeyCode[0x12] ="" // E pressed +ScanCodeToKeyCode[0x13] ="" // R pressed +ScanCodeToKeyCode[0x14] ="" // T pressed +ScanCodeToKeyCode[0x15] ="" // Y pressed +ScanCodeToKeyCode[0x16] ="" // U pressed +ScanCodeToKeyCode[0x17] ="" // I pressed +ScanCodeToKeyCode[0x18] ="" // O pressed +ScanCodeToKeyCode[0x19] ="" // P pressed +ScanCodeToKeyCode[0x1A] ="" // [ pressed +ScanCodeToKeyCode[0x1B] ="" // ] pressed +ScanCodeToKeyCode[0x1C] ="" // enter pressed +ScanCodeToKeyCode[0x1D] ="" // left control pressed +ScanCodeToKeyCode[0x1E] ="" // A pressed +ScanCodeToKeyCode[0x1F] ="" // S pressed +ScanCodeToKeyCode[0x20] ="" // D pressed +ScanCodeToKeyCode[0x21] ="" // F pressed +ScanCodeToKeyCode[0x22] ="" // G pressed +ScanCodeToKeyCode[0x23] ="" // H pressed +ScanCodeToKeyCode[0x24] ="" // J pressed +ScanCodeToKeyCode[0x25] ="" // K pressed +ScanCodeToKeyCode[0x26] ="" // L pressed +ScanCodeToKeyCode[0x27] ="" // ; pressed +ScanCodeToKeyCode[0x28] ="" // ' (single quote) pressed +ScanCodeToKeyCode[0x29] ="" // ` (back tick) pressed +ScanCodeToKeyCode[0x2A] ="" // left shift pressed +ScanCodeToKeyCode[0x2B] ="" // \ pressed +ScanCodeToKeyCode[0x2C] ="" // Z pressed +ScanCodeToKeyCode[0x2D] ="" // X pressed +ScanCodeToKeyCode[0x2E] ="" // C pressed +ScanCodeToKeyCode[0x2F] ="" // V pressed +ScanCodeToKeyCode[0x30] ="" // B pressed +ScanCodeToKeyCode[0x31] ="" // N pressed +ScanCodeToKeyCode[0x32] ="" // M pressed +ScanCodeToKeyCode[0x33] ="" // , pressed +ScanCodeToKeyCode[0x34] ="" // . pressed +ScanCodeToKeyCode[0x35] ="" // / pressed +ScanCodeToKeyCode[0x36] ="" // right shift pressed +ScanCodeToKeyCode[0x37] ="" // (keypad) * pressed +ScanCodeToKeyCode[0x38] ="" // left alt pressed +ScanCodeToKeyCode[0x39] ="" // space pressed +ScanCodeToKeyCode[0x3A] ="" // CapsLock pressed +ScanCodeToKeyCode[0x3B] ="" // F1 pressed +ScanCodeToKeyCode[0x3C] ="" // F2 pressed +ScanCodeToKeyCode[0x3D] ="" // F3 pressed +ScanCodeToKeyCode[0x3E] ="" // F4 pressed +ScanCodeToKeyCode[0x3F] ="" // F5 pressed +ScanCodeToKeyCode[0x40] ="" // F6 pressed +ScanCodeToKeyCode[0x41] ="" // F7 pressed +ScanCodeToKeyCode[0x42] ="" // F8 pressed +ScanCodeToKeyCode[0x43] ="" // F9 pressed +ScanCodeToKeyCode[0x44] ="" // F10 pressed +ScanCodeToKeyCode[0x45] ="" // NumberLock pressed +ScanCodeToKeyCode[0x46] ="" // ScrollLock pressed +ScanCodeToKeyCode[0x47] ="" // (keypad) 7 pressed +ScanCodeToKeyCode[0x48] ="" // (keypad) 8 pressed +ScanCodeToKeyCode[0x49] ="" // (keypad) 9 pressed +ScanCodeToKeyCode[0x4A] ="" // (keypad) - pressed +ScanCodeToKeyCode[0x4B] ="" // (keypad) 4 pressed +ScanCodeToKeyCode[0x4C] ="" // (keypad) 5 pressed +ScanCodeToKeyCode[0x4D] ="" // (keypad) 6 pressed +ScanCodeToKeyCode[0x4E] ="" // (keypad) + pressed +ScanCodeToKeyCode[0x4F] ="" // (keypad) 1 pressed +ScanCodeToKeyCode[0x50] ="" // (keypad) 2 pressed +ScanCodeToKeyCode[0x51] ="" // (keypad) 3 pressed +ScanCodeToKeyCode[0x52] ="" // (keypad) 0 pressed +ScanCodeToKeyCode[0x53] ="" // (keypad) . pressed +ScanCodeToKeyCode[0x57] ="" // F11 pressed +ScanCodeToKeyCode[0x58] ="" // F12 pressed + + +/* key released scanCode.""*/ +ScanCodeToKeyCode[0x81] ="" // escape released +ScanCodeToKeyCode[0x82] ="" // 1 released +ScanCodeToKeyCode[0x83] ="" // 2 released +ScanCodeToKeyCode[0x84] ="" // 3 released +ScanCodeToKeyCode[0x85] ="" // 4 released +ScanCodeToKeyCode[0x86] ="" // 5 released +ScanCodeToKeyCode[0x87] ="" // 6 released +ScanCodeToKeyCode[0x88] ="" // 7 released +ScanCodeToKeyCode[0x89] ="" // 8 released +ScanCodeToKeyCode[0x8A] ="" // 9 released +ScanCodeToKeyCode[0x8B] ="" // 0 (zero) released +ScanCodeToKeyCode[0x8C] ="" // - released +ScanCodeToKeyCode[0x8D] ="" // = released +ScanCodeToKeyCode[0x8E] ="" // backspace released +ScanCodeToKeyCode[0x8F] ="" // tab released +ScanCodeToKeyCode[0x90] ="" // Q released +ScanCodeToKeyCode[0x91] ="" // W released +ScanCodeToKeyCode[0x92] ="" // E released +ScanCodeToKeyCode[0x93] ="" // R released +ScanCodeToKeyCode[0x94] ="" // T released +ScanCodeToKeyCode[0x95] ="" // Y released +ScanCodeToKeyCode[0x96] ="" // U released +ScanCodeToKeyCode[0x97] ="" // I released +ScanCodeToKeyCode[0x98] ="" // O released +ScanCodeToKeyCode[0x99] ="" // P released +ScanCodeToKeyCode[0x9A] ="" // [ released +ScanCodeToKeyCode[0x9B] ="" // ] released +ScanCodeToKeyCode[0x9C] ="" // enter released +ScanCodeToKeyCode[0x9D] ="" // left control released +ScanCodeToKeyCode[0x9E] ="" // A released +ScanCodeToKeyCode[0x9F] ="" // S released +ScanCodeToKeyCode[0xA0] ="" // D released +ScanCodeToKeyCode[0xA1] ="" // F released +ScanCodeToKeyCode[0xA2] ="" // G released +ScanCodeToKeyCode[0xA3] ="" // H released +ScanCodeToKeyCode[0xA4] ="" // J released +ScanCodeToKeyCode[0xA5] ="" // K released +ScanCodeToKeyCode[0xA6] ="" // L released +ScanCodeToKeyCode[0xA7] ="" // ; released +ScanCodeToKeyCode[0xA8] ="" // ' (single quote) released +ScanCodeToKeyCode[0xA9] ="" // ` (back tick) released +ScanCodeToKeyCode[0xAA] ="" // left shift released +ScanCodeToKeyCode[0xAB] ="" // \ released +ScanCodeToKeyCode[0xAC] ="" // Z released +ScanCodeToKeyCode[0xAD] ="" // X released +ScanCodeToKeyCode[0xAE] ="" // C released +ScanCodeToKeyCode[0xAF] ="" // V released +ScanCodeToKeyCode[0xB0] ="" // B released +ScanCodeToKeyCode[0xB1] ="" // N released +ScanCodeToKeyCode[0xB2] ="" // M released +ScanCodeToKeyCode[0xB3] ="" // , released +ScanCodeToKeyCode[0xB4] ="" // . released +ScanCodeToKeyCode[0xB5] ="" // / released +ScanCodeToKeyCode[0xB6] ="" // right shift released +ScanCodeToKeyCode[0xB7] ="" // (keypad) * released +ScanCodeToKeyCode[0xB8] ="" // left alt released +ScanCodeToKeyCode[0xB9] ="" // space released +ScanCodeToKeyCode[0xBA] ="" // CapsLock released +ScanCodeToKeyCode[0xBB] ="" // F1 released +ScanCodeToKeyCode[0xBC] ="" // F2 released +ScanCodeToKeyCode[0xBD] ="" // F3 released +ScanCodeToKeyCode[0xBE] ="" // F4 released +ScanCodeToKeyCode[0xBF] ="" // F5 released +ScanCodeToKeyCode[0xC0] ="" // F6 released +ScanCodeToKeyCode[0xC1] ="" // F7 released +ScanCodeToKeyCode[0xC2] ="" // F8 released +ScanCodeToKeyCode[0xC3] ="" // F9 released +ScanCodeToKeyCode[0xC4] ="" // F10 released +ScanCodeToKeyCode[0xC5] ="" // NumberLock released +ScanCodeToKeyCode[0xC6] ="" // ScrollLock released +ScanCodeToKeyCode[0xC7] ="" // (keypad) 7 released +ScanCodeToKeyCode[0xC8] ="" // (keypad) 8 released +ScanCodeToKeyCode[0xC9] ="" // (keypad) 9 released +ScanCodeToKeyCode[0xCA] ="" // (keypad) - released +ScanCodeToKeyCode[0xCB] ="" // (keypad) 4 released +ScanCodeToKeyCode[0xCC] ="" // (keypad) 5 released +ScanCodeToKeyCode[0xCD] ="" // (keypad) 6 released +ScanCodeToKeyCode[0xCE] ="" // (keypad) + released +ScanCodeToKeyCode[0xCF] ="" // (keypad) 1 released +ScanCodeToKeyCode[0xD0] ="" // (keypad) 2 released +ScanCodeToKeyCode[0xD1] ="" // (keypad) 3 released +ScanCodeToKeyCode[0xD2] ="" // (keypad) 0 released +ScanCodeToKeyCode[0xD3] ="" // (keypad) . released +ScanCodeToKeyCode[0xD7] ="" // F11 released +ScanCodeToKeyCode[0xD8] ="" // F12 released \ No newline at end of file -- 2.39.5 From f2c8b8ac5ce8dba7fec923e708f324b7ba7e38eb Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 22 Jul 2021 20:02:47 +0100 Subject: [PATCH 020/115] Improved multiboot compliance --- .vscode/c_cpp_properties.json | 16 ++ Makefile | 2 +- src/kernel/MMU.cpp | 12 +- src/kernel/MMU.h | 1 + src/kernel/arch/i386/MMU/SlabAllocator.h | 33 +++ src/kernel/arch/i386/boot.s | 11 + src/kernel/arch/i386/tty/kterm.c | 2 +- src/kernel/kernel.cpp | 139 +++++++++--- src/kernel/kernel.h | 4 + src/kernel/multiboot.h | 274 +++++++++++++++++++++++ 10 files changed, 460 insertions(+), 34 deletions(-) create mode 100644 .vscode/c_cpp_properties.json create mode 100644 src/kernel/arch/i386/MMU/SlabAllocator.h create mode 100644 src/kernel/multiboot.h diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..862aed8 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,16 @@ +{ + "configurations": [ + { + "name": "Linux", + "includePath": [ + "${workspaceFolder}/**" + ], + "defines": [], + "compilerPath": "/usr/bin/gcc", + "cStandard": "gnu17", + "cppStandard": "gnu++14", + "intelliSenseMode": "linux-gcc-x64" + } + ], + "version": 4 +} \ No newline at end of file diff --git a/Makefile b/Makefile index aa43673..90aa8cf 100644 --- a/Makefile +++ b/Makefile @@ -24,7 +24,7 @@ all: clean build build: build_kernel run run: - $(EMULATOR) -d int -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std + $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std build_kernel: $(OBJ_LINK_LIST) diff --git a/src/kernel/MMU.cpp b/src/kernel/MMU.cpp index 96867f4..dfdd9ab 100644 --- a/src/kernel/MMU.cpp +++ b/src/kernel/MMU.cpp @@ -21,9 +21,9 @@ void MMU::enable(){ //we will fill all 1024 entries in the table, mapping 4 megabytes for(unsigned int i = 0; i < 1024; i++) { - // As the address is page aligned, it will always leave 12 bits zeroed. - // Those bits are used by the attributes ;) - first_page_table[i] = (i * 0x1000) | 3; // attributes: supervisor level, read/write, present. + // As the address is page aligned, it will always leave 12 bits zeroed. + // Those bits are used by the attributes ;) + first_page_table[i] = (i * 0x1000) | 3; // attributes: supervisor level, read/write, present. } // attributes: supervisor level, read/write, present @@ -32,4 +32,10 @@ void MMU::enable(){ loadPageDirectory(this->page_directory); enablePaging(); +} + + +uint32_t MMU::readTableEntry(int entry){ + return this->page_directory[entry]; + } \ No newline at end of file diff --git a/src/kernel/MMU.h b/src/kernel/MMU.h index cb3b7f8..df65d38 100644 --- a/src/kernel/MMU.h +++ b/src/kernel/MMU.h @@ -7,6 +7,7 @@ extern "C" void enablePaging(); class MMU { public: void enable (); + uint32_t readTableEntry(int); private: uint32_t page_directory[1024] __attribute__((aligned(4096))); diff --git a/src/kernel/arch/i386/MMU/SlabAllocator.h b/src/kernel/arch/i386/MMU/SlabAllocator.h new file mode 100644 index 0000000..b9f00df --- /dev/null +++ b/src/kernel/arch/i386/MMU/SlabAllocator.h @@ -0,0 +1,33 @@ +#pragma once +/** + * We'll need something to this effect to allocate memory in the kernel + * this will hopefully someday implement a full slab allocator + **/ +enum SlabState { + empty, + partial, + full +}; + +class CacheSlab { + const int SlabSize = 4000; + void* start = 0x0; +}; + + +class Allocator { + + public: + Allocator(); + ~Allocator(); + + void* kmalloc( int size ); + void kfree (void* address); + + private: + CacheSlab** _cache; + + + + +}; \ No newline at end of file diff --git a/src/kernel/arch/i386/boot.s b/src/kernel/arch/i386/boot.s index 2de2f8d..777501c 100644 --- a/src/kernel/arch/i386/boot.s +++ b/src/kernel/arch/i386/boot.s @@ -471,6 +471,17 @@ _start: /*Setup the stack pointer to point to the beginning of our stack */ /* I believe its a hight address growing down to lower adress for the stack on x86*/ mov $stack_top, %esp + + /*Reset EFLAGS*/ + pushl $0 + popf + + /* push the pointer to the Multiboot information structure*/ + pushl %ebx + + /* push the magic value */ + pushl %eax + call early_main cli load_gdt: diff --git a/src/kernel/arch/i386/tty/kterm.c b/src/kernel/arch/i386/tty/kterm.c index 7ec9ae1..2f2ce6f 100644 --- a/src/kernel/arch/i386/tty/kterm.c +++ b/src/kernel/arch/i386/tty/kterm.c @@ -88,7 +88,7 @@ void kterm_write(const char* data, size_t size) { } void kterm_writestring(const char* data ){ - AS_KERNEL(); + // AS_KERNEL(); kterm_write(data, strlen(data)); } diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 6764040..5087b0e 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -97,20 +97,115 @@ void test_serial(){ extern "C" { - void early_main(){ - - init_serial(); - print_serial("\033[31;42mEarly main called!\n"); - - } - - void kernel_main (void) { - - print_serial("Kernel main called!\n"); - + void early_main(unsigned long magic, unsigned long addr){ /** initialize terminal interface */ kterm_init(); + + multiboot_info_t *mbi; + + if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ + printf("Invalid magic number: 0x%x\n", (unsigned) magic); + return; + } + + /* Set MBI to the addresss of the multiboot information structure*/ + mbi = (multiboot_info_t *) addr; + + /* Print out the flags */ + printf("flags = 0x%x\n", (unsigned) mbi->flags); + + /* Are mem_* valid? */ + if ( CHECK_FLAG(mbi->flags,0)){ + printf("mem_lower = %uKB, mem_upper = %uKB\n"); + } + + /* is boot device valid ? */ + if (CHECK_FLAG (mbi->flags, 1)){ + printf("boot_device = 0x0%x\n", (unsigned) mbi->boot_device); + } + + /* is the command line passed? */ + if (CHECK_FLAG ( mbi->flags,2)){ + printf("cmdline = %s\n", (char *) mbi->cmdline); + } + + /* Are mods_* valid? */ + if(CHECK_FLAG ( mbi->flags, 3)){ + multiboot_module_t *mod; + int i; + + printf("mods count = %d, mods_addr = 0x%x\n", (int) mbi->mods_count, (int) mbi->mods_addr); + + for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ + printf(" mod start = 0x%x, mod_end = 0x%x, cmdline = %s\n", (unsigned) mod->mod_start, (unsigned) mod->mod_end, (char*) mod->cmdline); + } + } + + /* Bits 4 and 5 are mutually exclusive! */ + if (CHECK_FLAG (mbi->flags, 4) && CHECK_FLAG(mbi->flags, 5)){ + printf("Both bits 4 and 5 are set.\n"); + return; + } + + /* Is the symbol table of a.out valid? */ + if (CHECK_FLAG(mbi->flags, 4)){ + multiboot_aout_symbol_table_t *multiboot_aout_sym = &(mbi->u.aout_sym); + + printf( "multiboot_aout_symbol_table: tabsize = 0x%0x, strsize = 0x%x, addr = 0x%x\n", + (unsigned) multiboot_aout_sym->tabsize, + (unsigned) multiboot_aout_sym->strsize, + (unsigned) multiboot_aout_sym->addr); + + } + + /* Is the section header table of ELF valid? */ + if (CHECK_FLAG(mbi->flags, 5)){ + multiboot_elf_section_header_table_t *multiboot_elf_sec = &(mbi->u.elf_sec); + + printf("multiboot_elf_sec: num = %u, size = 0x%x, addr = 0x%x, shnd = 0x%x\n", + (unsigned) multiboot_elf_sec->num, (unsigned) multiboot_elf_sec->size, + (unsigned) multiboot_elf_sec->addr, (unsigned) multiboot_elf_sec->shndx); + + } + + + // AAAAAH memory map, Yes please! + /* Are mmap_* valid? */ + if (CHECK_FLAG(mbi->flags, 6)){ + multiboot_memory_map_t *mmap; + + printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", + (unsigned) mbi->mmap_addr, (unsigned) mbi->mmap_length); + + for (mmap = (multiboot_memory_map_t *) mbi->mmap_addr; + (unsigned long) mmap < mbi->mmap_addr + mbi->mmap_length; + mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + + printf( + "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", + (unsigned) mmap->size, + (unsigned) (mmap->addr >> 32), + (unsigned) (mmap->addr & 0xffffffff), + (unsigned) (mmap->len >> 32), + (unsigned) (mmap->len & 0xffffffff), + (unsigned) mmap->type); + + } + + } + + /* Draw diagonal blue line */ + if (CHECK_FLAG (mbi->flags, 12)){ + printf("Can draw!"); + } + } + + void kernel_main (void) { + + + init_serial(); + /** Setup the MMU **/ //kterm_writestring("Starting MMU...\n"); @@ -120,24 +215,10 @@ extern "C" { - - /** Wrtite stuff to the screen to test the terminal**/ - kterm_writestring("Hello world!\n"); - kterm_writestring("We got newline support!\n"); - - /** Test scrolling **/ - for(int i=0; i < 5; i++){ - delay(500); - kterm_writestring("We have implemented terminal scrolling!\n"); - } + + - - /** Test objective cpp **/ - kterm_writestring("Testing C++ object support\n"); - auto testObject = Test(); - testObject.printMe(); - - + /** test interrupt handlers **/ //asm volatile ("int $0x03"); @@ -147,7 +228,7 @@ extern "C" { while (true){ //Read time indefinetely read_rtc(); - printf( "UTC time: %2d-%2d-%2d %2d:%2d:%2d : (YY-MM-DD h:mm:ss)\r" ,year, month, day, hour, minute, second); + printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); delay(1000); } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index eed09c0..a863a97 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -4,7 +4,11 @@ extern "C" { #include "arch/i386/tty/kterm.h" } +#include "multiboot.h" #include "arch/i386/idt/idt.h" #include "MMU.h" #include "io.h" #include "time.h" + + +#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) \ No newline at end of file diff --git a/src/kernel/multiboot.h b/src/kernel/multiboot.h new file mode 100644 index 0000000..269cf9b --- /dev/null +++ b/src/kernel/multiboot.h @@ -0,0 +1,274 @@ +/* multiboot.h - Multiboot header file. */ +/* Copyright (C) 1999,2003,2007,2008,2009,2010 Free Software Foundation, Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL ANY + * DEVELOPER OR DISTRIBUTOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR + * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +#ifndef MULTIBOOT_HEADER +#define MULTIBOOT_HEADER 1 + +/* How many bytes from the start of the file we search for the header. */ +#define MULTIBOOT_SEARCH 8192 +#define MULTIBOOT_HEADER_ALIGN 4 + +/* The magic field should contain this. */ +#define MULTIBOOT_HEADER_MAGIC 0x1BADB002 + +/* This should be in %eax. */ +#define MULTIBOOT_BOOTLOADER_MAGIC 0x2BADB002 + +/* Alignment of multiboot modules. */ +#define MULTIBOOT_MOD_ALIGN 0x00001000 + +/* Alignment of the multiboot info structure. */ +#define MULTIBOOT_INFO_ALIGN 0x00000004 + +/* Flags set in the ’flags’ member of the multiboot header. */ + +/* Align all boot modules on i386 page (4KB) boundaries. */ +#define MULTIBOOT_PAGE_ALIGN 0x00000001 + +/* Must pass memory information to OS. */ +#define MULTIBOOT_MEMORY_INFO 0x00000002 + +/* Must pass video information to OS. */ +#define MULTIBOOT_VIDEO_MODE 0x00000004 + +/* This flag indicates the use of the address fields in the header. */ +#define MULTIBOOT_AOUT_KLUDGE 0x00010000 + +/* Flags to be set in the ’flags’ member of the multiboot info structure. */ + +/* is there basic lower/upper memory information? */ +#define MULTIBOOT_INFO_MEMORY 0x00000001 +/* is there a boot device set? */ +#define MULTIBOOT_INFO_BOOTDEV 0x00000002 +/* is the command-line defined? */ +#define MULTIBOOT_INFO_CMDLINE 0x00000004 +/* are there modules to do something with? */ +#define MULTIBOOT_INFO_MODS 0x00000008 + +/* These next two are mutually exclusive */ + +/* is there a symbol table loaded? */ +#define MULTIBOOT_INFO_AOUT_SYMS 0x00000010 +/* is there an ELF section header table? */ +#define MULTIBOOT_INFO_ELF_SHDR 0X00000020 + +/* is there a full memory map? */ +#define MULTIBOOT_INFO_MEM_MAP 0x00000040 + +/* Is there drive info? */ +#define MULTIBOOT_INFO_DRIVE_INFO 0x00000080 + +/* Is there a config table? */ +#define MULTIBOOT_INFO_CONFIG_TABLE 0x00000100 + +/* Is there a boot loader name? */ +#define MULTIBOOT_INFO_BOOT_LOADER_NAME 0x00000200 + +/* Is there a APM table? */ +#define MULTIBOOT_INFO_APM_TABLE 0x00000400 + +/* Is there video information? */ +#define MULTIBOOT_INFO_VBE_INFO 0x00000800 +#define MULTIBOOT_INFO_FRAMEBUFFER_INFO 0x00001000 + +#ifndef ASM_FILE + +typedef unsigned char multiboot_uint8_t; +typedef unsigned short multiboot_uint16_t; +typedef unsigned int multiboot_uint32_t; +typedef unsigned long long multiboot_uint64_t; + +struct multiboot_header +{ + /* Must be MULTIBOOT_MAGIC - see above. */ + multiboot_uint32_t magic; + + /* Feature flags. */ + multiboot_uint32_t flags; + + /* The above fields plus this one must equal 0 mod 2^32. */ + multiboot_uint32_t checksum; + + /* These are only valid if MULTIBOOT_AOUT_KLUDGE is set. */ + multiboot_uint32_t header_addr; + multiboot_uint32_t load_addr; + multiboot_uint32_t load_end_addr; + multiboot_uint32_t bss_end_addr; + multiboot_uint32_t entry_addr; + + /* These are only valid if MULTIBOOT_VIDEO_MODE is set. */ + multiboot_uint32_t mode_type; + multiboot_uint32_t width; + multiboot_uint32_t height; + multiboot_uint32_t depth; +}; + +/* The symbol table for a.out. */ +struct multiboot_aout_symbol_table +{ + multiboot_uint32_t tabsize; + multiboot_uint32_t strsize; + multiboot_uint32_t addr; + multiboot_uint32_t reserved; +}; +typedef struct multiboot_aout_symbol_table multiboot_aout_symbol_table_t; + +/* The section header table for ELF. */ +struct multiboot_elf_section_header_table +{ + multiboot_uint32_t num; + multiboot_uint32_t size; + multiboot_uint32_t addr; + multiboot_uint32_t shndx; +}; +typedef struct multiboot_elf_section_header_table multiboot_elf_section_header_table_t; + +struct multiboot_info +{ + /* Multiboot info version number */ + multiboot_uint32_t flags; + + /* Available memory from BIOS */ + multiboot_uint32_t mem_lower; + multiboot_uint32_t mem_upper; + + /* "root" partition */ + multiboot_uint32_t boot_device; + + /* Kernel command line */ + multiboot_uint32_t cmdline; + + /* Boot-Module list */ + multiboot_uint32_t mods_count; + multiboot_uint32_t mods_addr; + + union + { + multiboot_aout_symbol_table_t aout_sym; + multiboot_elf_section_header_table_t elf_sec; + } u; + + /* Memory Mapping buffer */ + multiboot_uint32_t mmap_length; + multiboot_uint32_t mmap_addr; + + /* Drive Info buffer */ + multiboot_uint32_t drives_length; + multiboot_uint32_t drives_addr; + + /* ROM configuration table */ + multiboot_uint32_t config_table; + + /* Boot Loader Name */ + multiboot_uint32_t boot_loader_name; + + /* APM table */ + multiboot_uint32_t apm_table; + + /* Video */ + multiboot_uint32_t vbe_control_info; + multiboot_uint32_t vbe_mode_info; + multiboot_uint16_t vbe_mode; + multiboot_uint16_t vbe_interface_seg; + multiboot_uint16_t vbe_interface_off; + multiboot_uint16_t vbe_interface_len; + + multiboot_uint64_t framebuffer_addr; + multiboot_uint32_t framebuffer_pitch; + multiboot_uint32_t framebuffer_width; + multiboot_uint32_t framebuffer_height; + multiboot_uint8_t framebuffer_bpp; +#define MULTIBOOT_FRAMEBUFFER_TYPE_INDEXED 0 +#define MULTIBOOT_FRAMEBUFFER_TYPE_RGB 1 +#define MULTIBOOT_FRAMEBUFFER_TYPE_EGA_TEXT 2 + multiboot_uint8_t framebuffer_type; + union + { + struct + { + multiboot_uint32_t framebuffer_palette_addr; + multiboot_uint16_t framebuffer_palette_num_colors; + }; + struct + { + multiboot_uint8_t framebuffer_red_field_position; + multiboot_uint8_t framebuffer_red_mask_size; + multiboot_uint8_t framebuffer_green_field_position; + multiboot_uint8_t framebuffer_green_mask_size; + multiboot_uint8_t framebuffer_blue_field_position; + multiboot_uint8_t framebuffer_blue_mask_size; + }; + }; +}; +typedef struct multiboot_info multiboot_info_t; + +struct multiboot_color +{ + multiboot_uint8_t red; + multiboot_uint8_t green; + multiboot_uint8_t blue; +}; + +struct multiboot_mmap_entry +{ + multiboot_uint32_t size; + multiboot_uint64_t addr; + multiboot_uint64_t len; +#define MULTIBOOT_MEMORY_AVAILABLE 1 +#define MULTIBOOT_MEMORY_RESERVED 2 +#define MULTIBOOT_MEMORY_ACPI_RECLAIMABLE 3 +#define MULTIBOOT_MEMORY_NVS 4 +#define MULTIBOOT_MEMORY_BADRAM 5 + multiboot_uint32_t type; +} __attribute__((packed)); +typedef struct multiboot_mmap_entry multiboot_memory_map_t; + +struct multiboot_mod_list +{ + /* the memory used goes from bytes ’mod_start’ to ’mod_end-1’ inclusive */ + multiboot_uint32_t mod_start; + multiboot_uint32_t mod_end; + + /* Module command line */ + multiboot_uint32_t cmdline; + + /* padding to take it to 16 bytes (must be zero) */ + multiboot_uint32_t pad; +}; +typedef struct multiboot_mod_list multiboot_module_t; + +/* APM BIOS info. */ +struct multiboot_apm_info +{ + multiboot_uint16_t version; + multiboot_uint16_t cseg; + multiboot_uint32_t offset; + multiboot_uint16_t cseg_16; + multiboot_uint16_t dseg; + multiboot_uint16_t flags; + multiboot_uint16_t cseg_len; + multiboot_uint16_t cseg_16_len; + multiboot_uint16_t dseg_len; +}; + +#endif /* ! ASM_FILE */ + +#endif /* ! MULTIBOOT_HEADER */ -- 2.39.5 From 643f2d708b98e4db546b2b215751f500c53227f0 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 22 Jul 2021 22:14:58 +0100 Subject: [PATCH 021/115] Added emulator options, Added header for VBE driver, Added CPUID function, Added demodisk.img as drive --- .gitattributes | 1 + .gitignore | 4 +- .vscode/c_cpp_properties.json | 16 ---- Makefile | 2 +- README.md | 9 +-- screenshots/.blank | 0 screenshots/multiboot.png | 3 + src/kernel/arch/i386/idt/idt.cpp | 3 + src/kernel/arch/i386/tty/kterm.c | 43 +++++++++++ src/kernel/arch/i386/tty/kterm.h | 13 +++- src/kernel/arch/i386/vga/VBE.h | 41 ++++++++++ src/kernel/cpu.h | 16 ++++ src/kernel/kernel.cpp | 129 +++---------------------------- src/kernel/kernel.h | 101 +++++++++++++++++++++++- 14 files changed, 236 insertions(+), 145 deletions(-) delete mode 100644 .vscode/c_cpp_properties.json delete mode 100644 screenshots/.blank create mode 100644 screenshots/multiboot.png create mode 100644 src/kernel/arch/i386/vga/VBE.h create mode 100644 src/kernel/cpu.h diff --git a/.gitattributes b/.gitattributes index 12b0908..b2a7b41 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ *.pdf filter=lfs diff=lfs merge=lfs -text *.png filter=lfs diff=lfs merge=lfs -text *.svg filter=lfs diff=lfs merge=lfs -text +demodisk.img filter=lfs diff=lfs merge=lfs -text diff --git a/.gitignore b/.gitignore index c795b05..a897a63 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ -build \ No newline at end of file +build +CON +.vscode diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json deleted file mode 100644 index 862aed8..0000000 --- a/.vscode/c_cpp_properties.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "configurations": [ - { - "name": "Linux", - "includePath": [ - "${workspaceFolder}/**" - ], - "defines": [], - "compilerPath": "/usr/bin/gcc", - "cStandard": "gnu17", - "cppStandard": "gnu++14", - "intelliSenseMode": "linux-gcc-x64" - } - ], - "version": 4 -} \ No newline at end of file diff --git a/Makefile b/Makefile index 90aa8cf..56af78b 100644 --- a/Makefile +++ b/Makefile @@ -24,7 +24,7 @@ all: clean build build: build_kernel run run: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std + $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial file:CON -vga std -monitor stdio -display gtk -m 2G -cpu core2duo -drive file=demodisk.img build_kernel: $(OBJ_LINK_LIST) diff --git a/README.md b/README.md index 6aa56a7..bba2564 100644 --- a/README.md +++ b/README.md @@ -10,18 +10,17 @@ ________________________ The first scrolling boot screen. 😲 - +![Interrupt handeling](screenshots/WIP_interruptHandling.png) \ W.I.P - Working on interrupt handling + +![Multiboot integration](screenshots/multiboot.png) \ +Multiboot information can be read by the kernel. ________________________ ### The goal Writing a hobby operating system to better understand the basic building blocks of any operating system. - - - - ________________________ ### Operating System Technical specs/details The operating system can print strings to the diff --git a/screenshots/.blank b/screenshots/.blank deleted file mode 100644 index e69de29..0000000 diff --git a/screenshots/multiboot.png b/screenshots/multiboot.png new file mode 100644 index 0000000..25cf7ff --- /dev/null +++ b/screenshots/multiboot.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13bb64394a1c4df50f254a7adfeda213a085b5338c44d6f61bbe2221c32e1929 +size 21530 diff --git a/src/kernel/arch/i386/idt/idt.cpp b/src/kernel/arch/i386/idt/idt.cpp index 4722109..4ab65b2 100644 --- a/src/kernel/arch/i386/idt/idt.cpp +++ b/src/kernel/arch/i386/idt/idt.cpp @@ -23,6 +23,9 @@ void irs_handler (registers regs) { printf(" Error code: %d \n", regs.err_code); } + + + } diff --git a/src/kernel/arch/i386/tty/kterm.c b/src/kernel/arch/i386/tty/kterm.c index 2f2ce6f..c7914ee 100644 --- a/src/kernel/arch/i386/tty/kterm.c +++ b/src/kernel/arch/i386/tty/kterm.c @@ -46,6 +46,48 @@ void kterm_putat (char c, uint8_t color, size_t x, size_t y ) { } +void enable_cursor (uint8_t start_cursor , uint8_t end_cursor ){ + outb(0x3D4, 0x0A); + outb(0x3D5, (inb(0x3D5) & 0xC0) | start_cursor); + + outb(0x3D4, 0x0B); + outb(0x3D5, (inb(0x3D5) & 0xE0) | end_cursor); +} + +void disable_cursor() +{ + outb(0x3D4, 0x0A); + outb(0x3D5, 0x20); +} + + +void update_cursor(int x, int y){ + uint16_t pos = y * VGA_WIDTH + x; + + outb(0x3D4, 0x0F); + outb(0x3D5, (uint8_t) (pos & 0xFF)); + outb(0x3D4, 0x0E); + outb(0x3D5, (uint8_t) ((pos >> 8) & 0xFF)); +} + +uint16_t get_cursor_position(){ + uint16_t pos = 0; + outb(0x3D4, 0x0F); + pos |= inb(0x3D5); + outb(0x3D4, 0x0E); + pos |= ((uint16_t) inb(0x3D5)) << 8; + return pos; +} + +int get_cursor_x (uint16_t cursor_pos) { + return cursor_pos % VGA_WIDTH; +} + +int get_cursor_y (uint16_t cursor_pos ) { + return cursor_pos / VGA_WIDTH; +} + + /** * With the help from: @@ -63,6 +105,7 @@ void kterm_scrollup(){ void kterm_put (char c) { if(++kterm_column == VGA_WIDTH || c == '\n' ) { + update_cursor(kterm_column , kterm_row); kterm_column = 0; if(kterm_row == VGA_HEIGHT-1 ) { kterm_scrollup(); diff --git a/src/kernel/arch/i386/tty/kterm.h b/src/kernel/arch/i386/tty/kterm.h index d9f704f..9986b51 100644 --- a/src/kernel/arch/i386/tty/kterm.h +++ b/src/kernel/arch/i386/tty/kterm.h @@ -5,12 +5,14 @@ #include #include "../vga/colors.h" - +#include "../../../io.h" void kterm_init(); +/* Kernel terminal - Colour functions*/ void kterm_resetcolor(); void kterm_setcolor(uint8_t); +/* Kernel terminal - Printing function */ void kterm_putat(char, uint8_t, size_t, size_t); void kterm_put(char); void kterm_write(const char*, size_t); @@ -18,6 +20,15 @@ void kterm_writestring(const char*); void kterm_scrollup(); +/* Kernel terminal - Cursor functions */ +void enable_cursor (uint8_t start_cursor , uint8_t end_cursor ); +void disable_cursor(); +void update_cursor(int x, int y); +uint16_t get_cursor_position(); +int get_cursor_x (uint16_t cursor_pos); +int get_cursor_y (uint16_t cursor_pos); + + void printf ( const char *format, ...); static void itoa (char *buf, int base, int d); diff --git a/src/kernel/arch/i386/vga/VBE.h b/src/kernel/arch/i386/vga/VBE.h new file mode 100644 index 0000000..8b63cd4 --- /dev/null +++ b/src/kernel/arch/i386/vga/VBE.h @@ -0,0 +1,41 @@ + +#define VBE_DISPI_IOPORT_INDEX 0x01CE +#define VBE_DISPI_IOPORT_DATA 0x01CF + +/* VBE index values*/ +#define VBE_DISPI_INDEX_ID 0x0 +#define VBE_DISPI_INDEX_XRES 0x1 +#define VBE_DISPI_INDEX_YRES 0x2 +#define VBE_DISPI_INDEX_BPP 0x3 +#define VBE_DISPI_INDEX_ENABLE 0x4 +#define VBE_DISPI_INDEX_BANK 0x5 +#define VBE_DISPI_INDEX_VIRT_WIDTH 0x6 +#define VBE_DISPI_INDEX_VIRT_HEIGHT 0x7 +#define VBE_DISPI_INDEX_X_OFFSET 0x8 +#define VBE_DISPI_INDEX_Y_OFFSET 0x9 + +/* BGA Version */ +#define VBE_DISPI_ID5 0xB0C5 +#define VBE_DISPI_ID4 0xB0C3 +#define VBE_DISPI_ID3 0xB0C2 +#define VBE_DISPI_ID2 0xB0C1 +#define VBE_DISPI_ID1 0xB0C0 + + +/* BGA BIT DEPTH */ +#define VBE_DISPI_BPP_4 0x04 +#define VBE_DISPI_BPP_8 0x08 +#define VBE_DISPI_BPP_15 0x0F +#define VBE_DISPI_BPP_16 0x10 +#define VBE_DISPI_BPP_24 0x18 +#define VBE_DISPI_BPP_32 0x20 + + + /*unsigned short BGAReadRegister(unsigned short IndexValue){ + // outpw(VBE_DISPI_IOPORT_INDEX, IndexValue); + // return inpw (VBE_DISPI_IOPORT_DATA); + } + + int BGAIsAvailable (){ + return (BGAReadRegister(VBE_DISPI_INDEX_ID) == VBE_DISPI_ID5); + }*/ diff --git a/src/kernel/cpu.h b/src/kernel/cpu.h new file mode 100644 index 0000000..4b90a9e --- /dev/null +++ b/src/kernel/cpu.h @@ -0,0 +1,16 @@ +#include // NOTE: Only available in GCC + + static int get_model(){ + int ebx, unused; + __cpuid(0, unused, ebx, unused, unused); + return ebx; + } + + enum { + CPUID_FEAT_EDX_APIC = 1 << 9 + }; + static int check_apic (){ + unsigned int eax, unused, edx; + __get_cpuid(1, &eax, &unused, &unused, &edx); + return edx & CPUID_FEAT_EDX_APIC; + } diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 5087b0e..df18683 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -1,108 +1,14 @@ #include "kernel.h" -/** - * simple delay function - **/ -void delay(int t){ - volatile int i,j; - for(i=0;iflags, 12)){ printf("Can draw!"); } + + int cpu_model = get_model(); + int local_apic = check_apic(); + printf( "CPU Model: %x, Local APIC: %D\n", cpu_model, local_apic); + } void kernel_main (void) { - init_serial(); - /** Setup the MMU **/ - //kterm_writestring("Starting MMU...\n"); - //auto mmu = MMU(); - //mmu.enable(); - //kterm_writestring("MMU enabled!\n"); - - - - - - - /** test interrupt handlers **/ - //asm volatile ("int $0x03"); - - //asm volatile ("int $0x04"); while (true){ //Read time indefinetely @@ -232,14 +127,8 @@ extern "C" { delay(1000); } - - /** Lets start using the serial port for debugging .. **/ - // Hopefully once we go into realmode or do something that - // cause the screen to go black.. this serial comms part will give - // some situational awareness - //Serial serialbus = Serial::init(); - - + + } } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index a863a97..b9b22bf 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -9,6 +9,105 @@ extern "C" { #include "MMU.h" #include "io.h" #include "time.h" +#include "cpu.h" +#include "arch/i386/vga/VBE.h" +#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) -#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) \ No newline at end of file + +/* This needs to be moved! */ +/** + * simple delay function + **/ +void delay(int t){ + volatile int i,j; + for(i=0;i Date: Sat, 23 Oct 2021 12:26:15 +0100 Subject: [PATCH 022/115] Added option to create an iso --- .gitignore | 5 +++ Makefile | 23 +++++++++--- src/grub.cfg | 3 ++ src/kernel/bootcheck.h | 73 +++++++++++++++++++++++++++++++++++++ src/kernel/kernel.cpp | 81 ++++++------------------------------------ src/kernel/kernel.h | 3 ++ 6 files changed, 114 insertions(+), 74 deletions(-) create mode 100644 src/grub.cfg create mode 100644 src/kernel/bootcheck.h diff --git a/.gitignore b/.gitignore index a897a63..3ac905f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,8 @@ build CON .vscode +isodir/ +root/ +*.iso +*.img + diff --git a/Makefile b/Makefile index 56af78b..79558ac 100644 --- a/Makefile +++ b/Makefile @@ -19,12 +19,27 @@ OBJ_LINK_LIST = $(CRTI_OBJ) $(CRTBEGIN_OBJ) $(OFILES) $(CRTEND_OBJ) $(CRTN_OBJ) INTERNAL_OBJS = $(CRTI_OBJ) $(OFILES) $(CRTN_OBJ) -all: clean build +all: clean build clean_up -build: build_kernel run +build: build_kernel -run: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial file:CON -vga std -monitor stdio -display gtk -m 2G -cpu core2duo -drive file=demodisk.img + + +clean_iso: + if [[ -a isodir/* ]] ; then rm isodir/* -d ; fi + if [ -f barinkOS.iso ] ; then rm barinkOS.iso ; fi + +iso: clean_iso build + mkdir -p isodir/boot/grub + cp build/myos.bin isodir/boot/myos.bin + cp src/grub.cfg isodir/boot/grub/grub.cfg + grub-mkrescue -o barinkOS.iso isodir + +clean_up: + rm build/*.o + +test: + $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial file:CON -vga std -monitor stdio -display gtk -m 2G -cpu core2duo build_kernel: $(OBJ_LINK_LIST) diff --git a/src/grub.cfg b/src/grub.cfg new file mode 100644 index 0000000..40431b9 --- /dev/null +++ b/src/grub.cfg @@ -0,0 +1,3 @@ +menuentry "BarinkOS"{ + multiboot /boot/myos.bin +} diff --git a/src/kernel/bootcheck.h b/src/kernel/bootcheck.h new file mode 100644 index 0000000..21268c0 --- /dev/null +++ b/src/kernel/bootcheck.h @@ -0,0 +1,73 @@ +#pragma once +#include "multiboot.h" +#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) + +extern "C" { + #include "arch/i386/tty/kterm.h" +} + + + +void CheckMBT ( multiboot_info_t* mbt ){ + /* Set MBI to the addresss of the multiboot information structure*/ + multiboot_info_t * mbi = (multiboot_info_t *) mbt; + + /* Print out the flags */ + printf("flags = 0x%x\n", (unsigned) mbi->flags); + + /* Are mem_* valid? */ + if ( CHECK_FLAG(mbi->flags,0)){ + printf("mem_lower = %uKB, mem_upper = %uKB\n"); + } + + /* is boot device valid ? */ + if (CHECK_FLAG (mbi->flags, 1)){ + printf("boot_device = 0x0%x\n", (unsigned) mbi->boot_device); + } + + /* is the command line passed? */ + if (CHECK_FLAG ( mbi->flags,2)){ + printf("cmdline = %s\n", (char *) mbi->cmdline); + } + + /* Are mods_* valid? */ + if(CHECK_FLAG ( mbi->flags, 3)){ + multiboot_module_t *mod; + int i; + + printf("mods count = %d, mods_addr = 0x%x\n", (int) mbi->mods_count, (int) mbi->mods_addr); + + for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ + printf(" mod start = 0x%x, mod_end = 0x%x, cmdline = %s\n", (unsigned) mod->mod_start, (unsigned) mod->mod_end, (char*) mod->cmdline); + } + } + + /* Bits 4 and 5 are mutually exclusive! */ + if (CHECK_FLAG (mbi->flags, 4) && CHECK_FLAG(mbi->flags, 5)){ + printf("Both bits 4 and 5 are set.\n"); + return; + } + + /* Is the symbol table of a.out valid? */ + if (CHECK_FLAG(mbi->flags, 4)){ + multiboot_aout_symbol_table_t *multiboot_aout_sym = &(mbi->u.aout_sym); + + printf( "multiboot_aout_symbol_table: tabsize = 0x%0x, strsize = 0x%x, addr = 0x%x\n", + (unsigned) multiboot_aout_sym->tabsize, + (unsigned) multiboot_aout_sym->strsize, + (unsigned) multiboot_aout_sym->addr); + + } + + /* Is the section header table of ELF valid? */ + if (CHECK_FLAG(mbi->flags, 5)){ + multiboot_elf_section_header_table_t *multiboot_elf_sec = &(mbi->u.elf_sec); + + printf("multiboot_elf_sec: num = %u, size = 0x%x, addr = 0x%x, shnd = 0x%x\n", + (unsigned) multiboot_elf_sec->num, (unsigned) multiboot_elf_sec->size, + (unsigned) multiboot_elf_sec->addr, (unsigned) multiboot_elf_sec->shndx); + + } + + +} \ No newline at end of file diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index df18683..6fee847 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -1,92 +1,33 @@ #include "kernel.h" - +#include "arch/i386/gdt/gdtc.h" extern "C" { - multiboot_info_t *mbi; void early_main(unsigned long magic, unsigned long addr){ - /** initialize terminal interface */ kterm_init(); - - - + if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ - printf("Invalid magic number: 0x%x\n", (unsigned) magic); + printf("Invalid magic number: 0x%x\n", magic); return; } - /* Set MBI to the addresss of the multiboot information structure*/ - mbi = (multiboot_info_t *) addr; + CheckMBT( (multiboot_info_t *) addr); - /* Print out the flags */ - printf("flags = 0x%x\n", (unsigned) mbi->flags); - /* Are mem_* valid? */ - if ( CHECK_FLAG(mbi->flags,0)){ - printf("mem_lower = %uKB, mem_upper = %uKB\n"); - } - - /* is boot device valid ? */ - if (CHECK_FLAG (mbi->flags, 1)){ - printf("boot_device = 0x0%x\n", (unsigned) mbi->boot_device); - } - - /* is the command line passed? */ - if (CHECK_FLAG ( mbi->flags,2)){ - printf("cmdline = %s\n", (char *) mbi->cmdline); - } - - /* Are mods_* valid? */ - if(CHECK_FLAG ( mbi->flags, 3)){ - multiboot_module_t *mod; - int i; - - printf("mods count = %d, mods_addr = 0x%x\n", (int) mbi->mods_count, (int) mbi->mods_addr); - - for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ - printf(" mod start = 0x%x, mod_end = 0x%x, cmdline = %s\n", (unsigned) mod->mod_start, (unsigned) mod->mod_end, (char*) mod->cmdline); - } - } - - /* Bits 4 and 5 are mutually exclusive! */ - if (CHECK_FLAG (mbi->flags, 4) && CHECK_FLAG(mbi->flags, 5)){ - printf("Both bits 4 and 5 are set.\n"); - return; - } - - /* Is the symbol table of a.out valid? */ - if (CHECK_FLAG(mbi->flags, 4)){ - multiboot_aout_symbol_table_t *multiboot_aout_sym = &(mbi->u.aout_sym); - - printf( "multiboot_aout_symbol_table: tabsize = 0x%0x, strsize = 0x%x, addr = 0x%x\n", - (unsigned) multiboot_aout_sym->tabsize, - (unsigned) multiboot_aout_sym->strsize, - (unsigned) multiboot_aout_sym->addr); - - } - - /* Is the section header table of ELF valid? */ - if (CHECK_FLAG(mbi->flags, 5)){ - multiboot_elf_section_header_table_t *multiboot_elf_sec = &(mbi->u.elf_sec); - - printf("multiboot_elf_sec: num = %u, size = 0x%x, addr = 0x%x, shnd = 0x%x\n", - (unsigned) multiboot_elf_sec->num, (unsigned) multiboot_elf_sec->size, - (unsigned) multiboot_elf_sec->addr, (unsigned) multiboot_elf_sec->shndx); - - } + multiboot_info_t* mbt = (multiboot_info_t*) addr; + // Map the kernel + //initPhysicalMemoryManager(); // AAAAAH memory map, Yes please! /* Are mmap_* valid? */ - if (CHECK_FLAG(mbi->flags, 6)){ - multiboot_memory_map_t *mmap; + if (CHECK_FLAG(mbt->flags, 6)){ + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", - (unsigned) mbi->mmap_addr, (unsigned) mbi->mmap_length); + (unsigned) mbt->mmap_addr, (unsigned) mbt->mmap_length); - for (mmap = (multiboot_memory_map_t *) mbi->mmap_addr; - (unsigned long) mmap < mbi->mmap_addr + mbi->mmap_length; - mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + for (mmap; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ printf( "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index b9b22bf..51fcb9a 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -2,10 +2,13 @@ extern "C" { #include "../libc/include/string.h" #include "arch/i386/tty/kterm.h" + #include "pmm.h" } #include "multiboot.h" +#include "bootcheck.h" #include "arch/i386/idt/idt.h" + #include "MMU.h" #include "io.h" #include "time.h" -- 2.39.5 From b4b615ae97207c9d672eac399d18dc377f46e4f7 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 23 Oct 2021 12:27:13 +0100 Subject: [PATCH 023/115] Checked off some todo's --- TODO.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/TODO.md b/TODO.md index 662bad3..5f9d63f 100644 --- a/TODO.md +++ b/TODO.md @@ -3,14 +3,14 @@ Setup Cross-Compiler \ Multiboot to kernel \ Printing string to the screen \ - Printing values/numbers to the screen (a.k.k itoa) \ - Extend Multiboot implementation \ + Printing values/numbers to the screen (a.k.k itoa) \ + Extend Multiboot implementation \ Output to serial port \ - Move to protected mode \ - Enabel CMOS clock \ + Move to protected mode \ + Enabel CMOS clock \ Time measurement (PIC &| PIT) \ Detect CPU speed \ - Interrupt / exception system (API) \ + Interrupt / exception system (API) \ Plan your memory map (virtual, and physical) : decide where you want the data to be. \ The heap: allocating memory at runtime (malloc and free) is almost impossible to go without. \ @@ -37,4 +37,4 @@ Basic Window server/client \ ## Support for more filesystems if I like the challenge in writing these ... FAT Filesystem \ - EXT2 Filesystem \ \ No newline at end of file + EXT2 Filesystem \ -- 2.39.5 From c9b789ed7b5383b0343df12b07e2694fa1781d11 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 2 Nov 2021 21:03:11 +0100 Subject: [PATCH 024/115] Added a bunch of new stuff no time to figure out what's what, No longer any compiler warnings --- Makefile | 5 +- src/kernel/MMU.cpp | 16 ++-- src/kernel/MMU.h | 19 ++++- src/kernel/arch/i386/boot.s | 6 +- src/kernel/arch/i386/gdt/gdtc.cpp | 6 +- src/kernel/arch/i386/gdt/gdtc.h | 2 +- src/kernel/arch/i386/idt/idt.cpp | 2 +- src/kernel/arch/i386/idt/idt.h | 1 - src/kernel/arch/i386/linker.ld | 8 +- src/kernel/arch/i386/pic/pic.h | 2 +- src/kernel/arch/i386/tty/kterm.c | 5 +- src/kernel/arch/i386/tty/kterm.h | 6 +- src/kernel/bootcheck.h | 2 +- src/kernel/cpu.h | 5 +- src/kernel/disk.h | 17 ++++ src/kernel/io.cpp | 15 ++-- src/kernel/kernel.cpp | 48 ++++++++---- src/kernel/kernel.h | 3 +- src/kernel/pci.cpp | 108 ++++++++++++++++++++++++++ src/kernel/pci.h | 58 ++++++++++++++ src/kernel/pmm.cpp | 1 + src/kernel/pmm.h | 125 ++++++++++++++++++++++++++++++ src/kernel/time.h | 4 +- src/libc/include/string.c | 9 +++ src/libc/include/string.h | 9 +-- 25 files changed, 427 insertions(+), 55 deletions(-) create mode 100644 src/kernel/disk.h create mode 100644 src/kernel/pci.cpp create mode 100644 src/kernel/pci.h create mode 100644 src/kernel/pmm.cpp create mode 100644 src/kernel/pmm.h create mode 100644 src/libc/include/string.c diff --git a/Makefile b/Makefile index 79558ac..1969454 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/MMU.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/MMU.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -79,3 +79,6 @@ $(BUILD_DIR)/idt.o: $(BUILD_DIR)/pic.o: $(CPP) -c $(SRC_DIR)/kernel/arch/i386/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/string.o: + $(CC) -c $(SRC_DIR)/libc/include/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 diff --git a/src/kernel/MMU.cpp b/src/kernel/MMU.cpp index dfdd9ab..58b3023 100644 --- a/src/kernel/MMU.cpp +++ b/src/kernel/MMU.cpp @@ -1,4 +1,5 @@ #include "MMU.h" +#include @@ -34,8 +35,13 @@ void MMU::enable(){ enablePaging(); } - -uint32_t MMU::readTableEntry(int entry){ - return this->page_directory[entry]; - -} \ No newline at end of file +/* +void IdentityPaging(uint32_t *first_pte, vaddr from, int size) +{ + from = from & 0xFFFFF000; // Discard the bits we don't want + for (; size > 0; from += 4096, first_pte++) + { + *first_pte = from | 1; // makr page present. + } +} +*/ diff --git a/src/kernel/MMU.h b/src/kernel/MMU.h index df65d38..69be7a3 100644 --- a/src/kernel/MMU.h +++ b/src/kernel/MMU.h @@ -1,14 +1,27 @@ #pragma once #include -extern "C" void loadPageDirectory (long unsigned int* addr ); +extern "C" void loadPageDirectory (uint32_t* addr ); extern "C" void enablePaging(); +typedef uintptr_t address_t; + + +#define KB 1024 + +static const int MAX_PAGES = 1024 * KB; // 4GB , 4kB/page +static volatile address_t pmem_stack[MAX_PAGES]; +static volatile address_t pmem_stack_top = MAX_PAGES; // top down allocation + + +struct page_directory_entry {}; +struct page_table_entry{}; + + class MMU { public: void enable (); - uint32_t readTableEntry(int); - + private: uint32_t page_directory[1024] __attribute__((aligned(4096))); uint32_t first_page_table[1024] __attribute__((aligned(4096))); diff --git a/src/kernel/arch/i386/boot.s b/src/kernel/arch/i386/boot.s index 777501c..096450a 100644 --- a/src/kernel/arch/i386/boot.s +++ b/src/kernel/arch/i386/boot.s @@ -21,7 +21,6 @@ stack_bottom: stack_top: .section .text - /* * Interupt handlers */ @@ -469,7 +468,7 @@ loadPageDirectory: .type _start, @function _start: /*Setup the stack pointer to point to the beginning of our stack */ - /* I believe its a hight address growing down to lower adress for the stack on x86*/ + /* I believe its a high address growing down to lower adress for the stack on x86*/ mov $stack_top, %esp /*Reset EFLAGS*/ @@ -484,6 +483,7 @@ _start: call early_main cli + load_gdt: lgdt gdt @@ -563,4 +563,4 @@ gdt_kdata: .byte 0b10010010 # 1st flags | type flags .byte 0b11001111 # 2nd flags | limit .byte 0x0 # base -gdt_end: \ No newline at end of file +gdt_end: diff --git a/src/kernel/arch/i386/gdt/gdtc.cpp b/src/kernel/arch/i386/gdt/gdtc.cpp index f21e80f..69611c2 100644 --- a/src/kernel/arch/i386/gdt/gdtc.cpp +++ b/src/kernel/arch/i386/gdt/gdtc.cpp @@ -1,5 +1,5 @@ #include "gdtc.h" - +#include "../tty/kterm.h" gdtEntry_t gdt[3]; @@ -18,8 +18,10 @@ void gdtSetGate(int num, uint64_t base, uint64_t limit, uint8_t access, } void setupGdt(){ + + printf("setupGdt is called!"); gdtPointer.limit = (sizeof(gdtEntry_t) * 3) - 1; - gdtPointer.base = &gdt; + gdtPointer.base = &gdt; gdtSetGate(0, 0, 0, 0, 0); gdtSetGate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); diff --git a/src/kernel/arch/i386/gdt/gdtc.h b/src/kernel/arch/i386/gdt/gdtc.h index 2b34997..4e8140f 100644 --- a/src/kernel/arch/i386/gdt/gdtc.h +++ b/src/kernel/arch/i386/gdt/gdtc.h @@ -1,5 +1,5 @@ #include -extern "c"{ +extern "C"{ typedef struct { uint16_t lLimit; diff --git a/src/kernel/arch/i386/idt/idt.cpp b/src/kernel/arch/i386/idt/idt.cpp index 4ab65b2..3334a3b 100644 --- a/src/kernel/arch/i386/idt/idt.cpp +++ b/src/kernel/arch/i386/idt/idt.cpp @@ -44,7 +44,7 @@ void irq_handler (registers regs) { // Keyboard interrupt !! int scan; - register int i; + /*register*/int i; // Read scancode diff --git a/src/kernel/arch/i386/idt/idt.h b/src/kernel/arch/i386/idt/idt.h index b616b85..cedb1ff 100644 --- a/src/kernel/arch/i386/idt/idt.h +++ b/src/kernel/arch/i386/idt/idt.h @@ -8,7 +8,6 @@ extern "C"{ #include "../tty/kterm.h" } -#define AS_KERNEL() ( kterm_writestring("[KERNEL]:")) extern "C" { diff --git a/src/kernel/arch/i386/linker.ld b/src/kernel/arch/i386/linker.ld index 7292df5..eb1aae8 100644 --- a/src/kernel/arch/i386/linker.ld +++ b/src/kernel/arch/i386/linker.ld @@ -6,10 +6,11 @@ ENTRY(_start) kernel image. */ SECTIONS { + /* Begin putting sections at 1 MiB, a conventional place for kernels to be loaded at by the bootloader. */ . = 1M; - + kernel_begin = .; /* First put the multiboot header, as it is required to be put very early early in the image or the bootloader won't recognize the file format. Next we'll put the .text section. */ @@ -40,4 +41,7 @@ SECTIONS /* The compiler may produce other sections, by default it will put them in a segment with the same name. Simply add stuff here as needed. */ -} \ No newline at end of file + + kernel_end = .; +} + diff --git a/src/kernel/arch/i386/pic/pic.h b/src/kernel/arch/i386/pic/pic.h index 5358f5a..3248187 100644 --- a/src/kernel/arch/i386/pic/pic.h +++ b/src/kernel/arch/i386/pic/pic.h @@ -49,7 +49,7 @@ void PIC_sendEOI (unsigned char irq); } -static uint16_t __pic_get_irq_reg(int ocw3); +//static uint16_t __pic_get_irq_reg(int ocw3); uint16_t pic_get_irr(void); uint16_t pic_get_isr(void); diff --git a/src/kernel/arch/i386/tty/kterm.c b/src/kernel/arch/i386/tty/kterm.c index c7914ee..f4bc957 100644 --- a/src/kernel/arch/i386/tty/kterm.c +++ b/src/kernel/arch/i386/tty/kterm.c @@ -1,4 +1,5 @@ #include "kterm.h" + static const size_t VGA_WIDTH = 80; static const size_t VGA_HEIGHT = 25; @@ -201,8 +202,10 @@ void printf ( const char *format, ...) { switch (c) { case 'd': - + kterm_writestring("Not implemented!!"); + break; case 'u': + break; case 'x': itoa(buf, c, *((int *) arg++)); diff --git a/src/kernel/arch/i386/tty/kterm.h b/src/kernel/arch/i386/tty/kterm.h index 9986b51..b43faa9 100644 --- a/src/kernel/arch/i386/tty/kterm.h +++ b/src/kernel/arch/i386/tty/kterm.h @@ -6,6 +6,10 @@ #include "../vga/colors.h" #include "../../../io.h" + + +#include "./../../../../libc/include/string.h" + void kterm_init(); /* Kernel terminal - Colour functions*/ @@ -31,7 +35,7 @@ int get_cursor_y (uint16_t cursor_pos); void printf ( const char *format, ...); -static void itoa (char *buf, int base, int d); +//static void itoa (char *buf, int base, int d); #define KernelTag "[Kernel]: " #define AS_KERNEL() ( kterm_setcolor(VGA_COLOR_LIGHT_BLUE),\ diff --git a/src/kernel/bootcheck.h b/src/kernel/bootcheck.h index 21268c0..3aef2ed 100644 --- a/src/kernel/bootcheck.h +++ b/src/kernel/bootcheck.h @@ -33,7 +33,7 @@ void CheckMBT ( multiboot_info_t* mbt ){ /* Are mods_* valid? */ if(CHECK_FLAG ( mbi->flags, 3)){ multiboot_module_t *mod; - int i; + uint32_t i; printf("mods count = %d, mods_addr = 0x%x\n", (int) mbi->mods_count, (int) mbi->mods_addr); diff --git a/src/kernel/cpu.h b/src/kernel/cpu.h index 4b90a9e..6e9f95a 100644 --- a/src/kernel/cpu.h +++ b/src/kernel/cpu.h @@ -1,6 +1,6 @@ #include // NOTE: Only available in GCC - - static int get_model(){ +// NOT currently usefull! +/* static int get_model(){ int ebx, unused; __cpuid(0, unused, ebx, unused, unused); return ebx; @@ -14,3 +14,4 @@ __get_cpuid(1, &eax, &unused, &unused, &edx); return edx & CPUID_FEAT_EDX_APIC; } +*/ \ No newline at end of file diff --git a/src/kernel/disk.h b/src/kernel/disk.h new file mode 100644 index 0000000..7ba3925 --- /dev/null +++ b/src/kernel/disk.h @@ -0,0 +1,17 @@ +#pragma once + +// Let's write an ATA PIO | ATA driver for now. Mostly to show that I can in theory interact with a +// storage device + +// PRIMARY_ATA_BUS +// 0x1F0 through 0x1F7 + +// SECONDARY_ATA_BUS +// 0x170 through 0x177 + +#define DEVICE_CONTROL_REGISTER 0x3F6 +#define DEVICE_CONTROL_ALTERNATE 0x376 + + +// IRQ14 Primary bus interrupt +// IRQ15 Secondary bus interrupt diff --git a/src/kernel/io.cpp b/src/kernel/io.cpp index f9ed07d..8a0861c 100644 --- a/src/kernel/io.cpp +++ b/src/kernel/io.cpp @@ -1,19 +1,24 @@ #include "io.h" unsigned char inb_p(unsigned short ){ - + // TODO: implement me! + return 0; } unsigned short inw(unsigned short ){ - +// TODO: implement me! + return 0; } unsigned short inw_p(unsigned short ){ - +// TODO: implement me! + return 0; } unsigned int inl(unsigned short ){ - +// TODO: implement me! + return 0; } unsigned int inl_p(unsigned short ){ - +// TODO: implement me! + return 0; } diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 6fee847..a04f977 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -23,12 +23,21 @@ extern "C" { /* Are mmap_* valid? */ if (CHECK_FLAG(mbt->flags, 6)){ multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; - + uint32_t memorySizeInBytes = 0; + uint32_t reservedMemoryInBytes = 0; + + printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", (unsigned) mbt->mmap_addr, (unsigned) mbt->mmap_length); - for (mmap; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ - + for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ + memorySizeInBytes += mmap->len; + } else { + reservedMemoryInBytes += mmap->len; + } + + printf( "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", (unsigned) mmap->size, @@ -39,37 +48,44 @@ extern "C" { (unsigned) mmap->type); } - + uint32_t memorySizeInGiB = memorySizeInBytes / 1073741824; + + printf("Available Memory: 0x%x bytes, 0x%x GiB\n", memorySizeInBytes, memorySizeInGiB ); + printf("Reserved Memory: 0x%x bytes\n", reservedMemoryInBytes ); } + + + + //int cpu_model = get_model(); + //int local_apic = check_apic(); + //printf( "CPU Model: %x, Local APIC: %D\n", cpu_model, local_apic); + + + /* Setup Paging and memory Managment*/ + //MMU MemoryManagementUnit = MMU(); + //MemoryManagementUnit.enable(); // Warning: Causes triple page fault + //printf("Pages available: %9d\n", pmm_available()); /* Draw diagonal blue line */ - if (CHECK_FLAG (mbi->flags, 12)){ + if (CHECK_FLAG (mbt->flags, 12)){ printf("Can draw!"); } - int cpu_model = get_model(); - int local_apic = check_apic(); - printf( "CPU Model: %x, Local APIC: %D\n", cpu_model, local_apic); + //setupGdt(); + } void kernel_main (void) { init_serial(); - - - - - while (true){ + while (false){ //Read time indefinetely read_rtc(); printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); delay(1000); } - - - } } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 51fcb9a..1c968f1 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -1,10 +1,11 @@ #pragma once extern "C" { - #include "../libc/include/string.h" + #include "arch/i386/tty/kterm.h" #include "pmm.h" } +#include "../libc/include/string.h" #include "multiboot.h" #include "bootcheck.h" #include "arch/i386/idt/idt.h" diff --git a/src/kernel/pci.cpp b/src/kernel/pci.cpp new file mode 100644 index 0000000..3f81c29 --- /dev/null +++ b/src/kernel/pci.cpp @@ -0,0 +1,108 @@ +#include "pci.h" + +uint16_t ConfigReadWord (uint8_t bus, uint8_t slot, uint8_t func, uint8_t offset){ + uint32_t address; + uint32_t lbus = (uint32_t) bus; + uint32_t lslot = (uint32_t) slot; + uint32_t lfunc = (uint32_t) func; + uint16_t tmp = 0; + + /* Create configuration address as per Figure 1 */ + address = (uint32_t) ((lbus << 16) | (lslot << 11) | (lfunc << 8) | (offset & 0xFC) |((uint32_t) 0x80000000) ); + /*write out the address */ + outl(CONFIG_ADDRESS, address); + /* read in the data */ + /* (offset & 2 ) * 8 ) = o will choosse the first word of the 32 bits register*/ + tmp = (uint16_t)((inl(CONFIG_DATA)) >> ((offset & 2) * 8) & 0xFFFF); + return (tmp); +} + +uint16_t CheckVendor (uint8_t bus, uint8_t slot) { + uint16_t vendor, device; + /* + Try and read the first configuration register. Since there ar no + vendors that == 0xFFFF, it must be a non-existent device. + */ + if((vendor = ConfigReadWord(bus, slot, 0,0)) != 0xFFFF) { + device = ConfigReadWord(bus, slot, 0,2); + // Possible read more config values ... + } return (vendor); +} + +void checkDevice (uint8_t bus, uint8_t device ) { + uint8_t function = 0; + + uint16_t vendorID = CheckVendor(bus, device); + if (vendorID == 0xFFFF) { + return; + } + + checkFunction (bus, device, function ); + headerType = getHeaderType(bus, device, function ); + if( (headerType & 0x80) != 0) { + /* It is a multi-function device, so check remaining functions */ + for (function = 1; function < 8; function++){ + if (CheckVendor(bus, device)!= 0xFFFF){ + checkFunction(bus, device, function ); + } + } + } + +} + + +void checkFunction (uint8_t bus, uint8_t device, uint8_t function ){ + uint8_t baseClass; + uint8_t subClass; + uint8_t secondaryBus; + + baseClass = getBaseClass(bus, device, function); + subClass = getSubClass (bus, device, function ); + if ( (baseClass == 0x06) && (subClass == 0x04)){ + secondaryBus = getSecondaryBus(bus,device, function); + checkBus(secondaryBus); + } +} + + +// Brute-force scan +void checkAllBuses (){ + uint16_t bus; + uint8_t device; + + for(bus = 0; bus < 256; bus++){ + for(device = 0; device < 32; device++){ + checkDevice(bus,device); + } + } +} + +// Recursive scan +void checkBus (uint8_t bus){ + uint8_t device; + + for(device = 0; device < 32; device ++){ + checkDevice(bus,device); + } +} + +void checkAllBuses(){ + uint8_t function; + uint8_t bus; + + headerType = getHeaderType(0,0,0); + if ( (headerType & 0x80) == 0 ){ + /* Single PCI host controller */ + checkBus(0); + } else{ + /* Multiple PCI host controllers */ + for (function = 0; function < 8; function++){ + if( CheckVendor(0,0) != 0xFFFF) { + break; + } + bus = function; + checkBus(bus); + } + } + +} \ No newline at end of file diff --git a/src/kernel/pci.h b/src/kernel/pci.h new file mode 100644 index 0000000..93b15ce --- /dev/null +++ b/src/kernel/pci.h @@ -0,0 +1,58 @@ +#pragma once +#include +#include "io.h" +// Configuration Space Access Mechanism #1 +#define CONFIG_ADDRESS 0xCF8 // Configuration adress that is to be accessed +#define CONFIG_DATA 0xCFC // Will do the actual configuration operation + +/* +CONFIG_ADDRESS + +32 bit register + +bit 31 Enable bit (Should CONFIG_DATA be translatedc to configuration cycles) +bit 30 - 24 Reserved +bit 23 - 16 Bus Number (Choose a specific PCI BUS) +bit 15 - 11 Device Number (Selects specific device one the pci bus) +bit 10 - 8 Function Number (Selects a specific function in a device) +bit 7 - 0 Register Offset (Offset in the configuration space of 256 Bytes ) NOTE: lowest two bits will always be zero + +*/ + + +/* +PCI Device structure + +Register offset bits 31-24 bits 23-16 bits 15-8 bits 7-0 +00 00 Device ID <---- Vendor ID <------- +01 04 Status <---- Command <------- +02 08 Class code Sub class Prog IF Revision ID +03 0C BIST Header Type Ltncy Timer Cache line Size +04 10 Base address #0 (BAR0) +05 14 Base address #1 (BAR1) +06 18 Base address #2 (BAR2) +07 1C Base address #3 (BAR3) +08 20 Base address #4 (BAR4) +09 24 Base address #5 (BAR5) +0A 28 Cardbus CIS Pointer +0B 2C Subsystem ID <------ Subsystem Vendor ID <------- +0C 30 Expansion ROM base address +0D 34 Reserved <------- Capabilities Pointer <------ +0E 38 Reserved <------- <-------- <-------- +0F 3C Max ltncy Min Grant Interrupt PIN Interrupt Line + +*/ + + +/* +The idea for now is to support the minimal things necessary to find ATA supported drives + */ + + +// Lets write some boiler plate configuration code + +uint16_t ConfigReadWord (uint8_t bus, uint8_t slot, uint8_t func, uint8_t offset); + +uint16_t CheckVendor (uint8_t bus, uint8_t slot); + +void checkDevice (uint8_t bus, uint8_t device ); \ No newline at end of file diff --git a/src/kernel/pmm.cpp b/src/kernel/pmm.cpp new file mode 100644 index 0000000..4b9d66f --- /dev/null +++ b/src/kernel/pmm.cpp @@ -0,0 +1 @@ +#include "pmm.h" diff --git a/src/kernel/pmm.h b/src/kernel/pmm.h new file mode 100644 index 0000000..7f3265c --- /dev/null +++ b/src/kernel/pmm.h @@ -0,0 +1,125 @@ +#pragma once +#include +// Lets assume we have 2 gigabytes of memory +// NOTE: We should really detect how much memory we have +#define KiloByte 1024 // bytes +#define MegaByte 1048576 // bytes +#define GigaByte 1073741824 // bytes +#define MemorySize 2147483648 // bytes + +const uint32_t bitmapSize = MemorySize / 8; + +extern void *kernel_begin; +extern void *kernel_end; +struct __attribute__((packed)) PMSegment { + void* address; + uint32_t size; + PMSegment* Next; +}; + + +static PMSegment pmStart; +static uint32_t AvailablePhysicalMemory; +static uint32_t AllocatedMemorySize; + +void initPhysicalMemoryManager(){ + AvailablePhysicalMemory = MemorySize; + AllocatedMemorySize = 0; + + // Map the kernel + PMSegment KernelSegment = PMSegment(); + printf("end of kernel: 0x%x\n", &kernel_end); + printf("start of kernel: 0x%x\n", &kernel_begin); + printf("pointer to kernel: 0x%x\n", &KernelSegment); + + pmStart = KernelSegment; + KernelSegment.address = kernel_begin; + KernelSegment.size = &kernel_end - &kernel_begin; + AllocatedMemorySize += KernelSegment.size; + KernelSegment.Next = 0; + + // make sure We allocate space for ourselves + /*PMSegment start = PMSegment(); + start.address = KernelSegment.address + KernelSegment.size ; + start.size = (MemorySize / sizeof(PMSegment) ) + sizeof (uint32_t) * 2; + */ + + //KernelSegment.Next = &start; + //AllocatedMemorySize += start.size; +} + +void printMemorySegments() +{ + printf("Memory Segments:\n"); + printf( "Start Segment: [addr: 0x%x, size: 0x%x, Next: 0x%x]\n" ,pmStart.address, pmStart.size, pmStart.Next); + printf("----------------------------\n"); +} + + +void pmem_free (void* address){ + + PMSegment* before = 0; + PMSegment* current = &pmStart; + + printf("Address of pmStart : 0x%x\n", pmStart); + printf("Looking for segment with address: 0x%x \n", address ); + printf("Address of pmStart(a.k.a current) : 0x%x \n", current); + while( current ) + { + //printf("address of current segment 0x%x\n", current->address ); + if ( current->address == address ) { + // this is the address we want to free + printf("Segment found!! Segment address: 0x%x \n", current->address); + if ( current->Next && before ){ + before->Next = current->Next; + }else{ + before->Next = 0; + } + // TODO: Clean memory [ Something like memset to zeroes] + printf("Removing segment of size: 0x%x\n", current->size); + AllocatedMemorySize -= current->size; + break; + } + + before = current; + current = current->Next; + + } + +} + +void* pmem_alloc ( uint32_t size ){ + // Get the last segment + PMSegment* lastSegment = &pmStart; + + while (lastSegment ) { + if( lastSegment->Next == 0){ + break; + } + lastSegment = lastSegment->Next; + } + + printf("LastSegment is for address: 0x%x\n", lastSegment->address); + + + // So now we have the last segment available + PMSegment newSegment = PMSegment(); + newSegment.address = (PMSegment*)((uint32_t)lastSegment->address + lastSegment->size +1); + + printf("NewSegment for Address: 0x%x\n", newSegment.address); + + newSegment.size = size; + + lastSegment->Next = &newSegment; + + if ( AllocatedMemorySize + newSegment.size > AvailablePhysicalMemory){ + // No segment available of this size + /// ERROR!! + return 0; + } + AllocatedMemorySize += newSegment.size; + + return newSegment.address; + + +} \ No newline at end of file diff --git a/src/kernel/time.h b/src/kernel/time.h index 6a098b7..c301bc8 100644 --- a/src/kernel/time.h +++ b/src/kernel/time.h @@ -49,6 +49,8 @@ void read_rtc() { year = get_RTC_register(0x09); if(century_register != 0) { century = get_RTC_register(century_register); + } else { + century = 21; } do { @@ -141,7 +143,7 @@ void WriteTOCMOS(unsigned char array[]) asm("cli\n\t" // Clear interrupts "mov al,index\n\t" // move index address "out 0x70,al\n\t" // copy address to CMOS register - /* some kind of real delay here is probably best + // some kind of real delay here is probably best "mov al,tvalue\n\t" // move value to al "out 0x71,al\n\t" // write 1 byte to CMOS "sti\n\\t" ); // Enable interrupts diff --git a/src/libc/include/string.c b/src/libc/include/string.c new file mode 100644 index 0000000..60b96b8 --- /dev/null +++ b/src/libc/include/string.c @@ -0,0 +1,9 @@ +#include "string.h" + +size_t strlen(const char* str) { + size_t len = 0; + while(str[len]){ + len++; + } + return len; +} \ No newline at end of file diff --git a/src/libc/include/string.h b/src/libc/include/string.h index 579c72a..90329e9 100644 --- a/src/libc/include/string.h +++ b/src/libc/include/string.h @@ -1,8 +1,3 @@ +#pragma once #include -size_t strlen(const char* str){ - size_t len = 0; - while(str[len]){ - len++; - } - return len; -} \ No newline at end of file +size_t strlen(const char* str); -- 2.39.5 From bdcf9e66f82945c9d0bd9f1bcbd78bc0d1eb016b Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 2 Nov 2021 21:15:00 +0100 Subject: [PATCH 025/115] Small adjustment in directory structure of memory and bootloader files in kernel --- Makefile | 6 +- src/kernel/bootcheck.h | 2 +- src/kernel/{ => bootloader}/multiboot.h | 0 src/kernel/kernel.h | 5 +- .../{MMU.cpp => memory/PageDirectory.cpp} | 4 +- src/kernel/{MMU.h => memory/PageDirectory.h} | 2 +- src/kernel/memory/PageFramAllocator.cpp | 1 + src/kernel/memory/PageFrameAllocator.h | 8 ++ .../{arch/i386/MMU => memory}/SlabAllocator.h | 0 src/kernel/pmm.cpp | 1 - src/kernel/pmm.h | 125 ------------------ 11 files changed, 17 insertions(+), 137 deletions(-) rename src/kernel/{ => bootloader}/multiboot.h (100%) rename src/kernel/{MMU.cpp => memory/PageDirectory.cpp} (95%) rename src/kernel/{MMU.h => memory/PageDirectory.h} (96%) create mode 100644 src/kernel/memory/PageFramAllocator.cpp create mode 100644 src/kernel/memory/PageFrameAllocator.h rename src/kernel/{arch/i386/MMU => memory}/SlabAllocator.h (100%) delete mode 100644 src/kernel/pmm.cpp delete mode 100644 src/kernel/pmm.h diff --git a/Makefile b/Makefile index 1969454..da1419f 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/MMU.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -71,8 +71,8 @@ $(BUILD_DIR)/crtn.o: $(BUILD_DIR)/io.o: $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti -$(BUILD_DIR)/MMU.o: - $(CPP) -c $(SRC_DIR)/kernel/MMU.cpp -o $(BUILD_DIR)/MMU.o $(CFLAGS) -fno-exceptions -fno-rtti +$(BUILD_DIR)/PageDirectory.o: + $(CPP) -c $(SRC_DIR)/kernel/memory/PageDirectory.cpp -o $(BUILD_DIR)/PageDirectory.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/idt.o: $(CPP) -c $(SRC_DIR)/kernel/arch/i386/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/bootcheck.h b/src/kernel/bootcheck.h index 3aef2ed..890c4f8 100644 --- a/src/kernel/bootcheck.h +++ b/src/kernel/bootcheck.h @@ -1,5 +1,5 @@ #pragma once -#include "multiboot.h" +#include "bootloader/multiboot.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) extern "C" { diff --git a/src/kernel/multiboot.h b/src/kernel/bootloader/multiboot.h similarity index 100% rename from src/kernel/multiboot.h rename to src/kernel/bootloader/multiboot.h diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 1c968f1..445e8fa 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -1,16 +1,13 @@ #pragma once extern "C" { - #include "arch/i386/tty/kterm.h" - #include "pmm.h" } #include "../libc/include/string.h" -#include "multiboot.h" +#include "./bootloader/multiboot.h" #include "bootcheck.h" #include "arch/i386/idt/idt.h" -#include "MMU.h" #include "io.h" #include "time.h" #include "cpu.h" diff --git a/src/kernel/MMU.cpp b/src/kernel/memory/PageDirectory.cpp similarity index 95% rename from src/kernel/MMU.cpp rename to src/kernel/memory/PageDirectory.cpp index 58b3023..ca7a6d5 100644 --- a/src/kernel/MMU.cpp +++ b/src/kernel/memory/PageDirectory.cpp @@ -1,9 +1,9 @@ -#include "MMU.h" +#include "PageDirectory.h" #include -void MMU::enable(){ +void PageDirectory::enable(){ //set each entry to not present int i; diff --git a/src/kernel/MMU.h b/src/kernel/memory/PageDirectory.h similarity index 96% rename from src/kernel/MMU.h rename to src/kernel/memory/PageDirectory.h index 69be7a3..a2863d3 100644 --- a/src/kernel/MMU.h +++ b/src/kernel/memory/PageDirectory.h @@ -18,7 +18,7 @@ struct page_table_entry{}; -class MMU { +class PageDirectory { public: void enable (); diff --git a/src/kernel/memory/PageFramAllocator.cpp b/src/kernel/memory/PageFramAllocator.cpp new file mode 100644 index 0000000..b690689 --- /dev/null +++ b/src/kernel/memory/PageFramAllocator.cpp @@ -0,0 +1 @@ +#include "PageFrameAllocator.h" diff --git a/src/kernel/memory/PageFrameAllocator.h b/src/kernel/memory/PageFrameAllocator.h new file mode 100644 index 0000000..56d4871 --- /dev/null +++ b/src/kernel/memory/PageFrameAllocator.h @@ -0,0 +1,8 @@ +#pragma once +#include + + + +extern void *kernel_begin; +extern void *kernel_end; + diff --git a/src/kernel/arch/i386/MMU/SlabAllocator.h b/src/kernel/memory/SlabAllocator.h similarity index 100% rename from src/kernel/arch/i386/MMU/SlabAllocator.h rename to src/kernel/memory/SlabAllocator.h diff --git a/src/kernel/pmm.cpp b/src/kernel/pmm.cpp deleted file mode 100644 index 4b9d66f..0000000 --- a/src/kernel/pmm.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "pmm.h" diff --git a/src/kernel/pmm.h b/src/kernel/pmm.h deleted file mode 100644 index 7f3265c..0000000 --- a/src/kernel/pmm.h +++ /dev/null @@ -1,125 +0,0 @@ -#pragma once -#include -// Lets assume we have 2 gigabytes of memory -// NOTE: We should really detect how much memory we have -#define KiloByte 1024 // bytes -#define MegaByte 1048576 // bytes -#define GigaByte 1073741824 // bytes -#define MemorySize 2147483648 // bytes - -const uint32_t bitmapSize = MemorySize / 8; - -extern void *kernel_begin; -extern void *kernel_end; -struct __attribute__((packed)) PMSegment { - void* address; - uint32_t size; - PMSegment* Next; -}; - - -static PMSegment pmStart; -static uint32_t AvailablePhysicalMemory; -static uint32_t AllocatedMemorySize; - -void initPhysicalMemoryManager(){ - AvailablePhysicalMemory = MemorySize; - AllocatedMemorySize = 0; - - // Map the kernel - PMSegment KernelSegment = PMSegment(); - printf("end of kernel: 0x%x\n", &kernel_end); - printf("start of kernel: 0x%x\n", &kernel_begin); - printf("pointer to kernel: 0x%x\n", &KernelSegment); - - pmStart = KernelSegment; - KernelSegment.address = kernel_begin; - KernelSegment.size = &kernel_end - &kernel_begin; - AllocatedMemorySize += KernelSegment.size; - KernelSegment.Next = 0; - - // make sure We allocate space for ourselves - /*PMSegment start = PMSegment(); - start.address = KernelSegment.address + KernelSegment.size ; - start.size = (MemorySize / sizeof(PMSegment) ) + sizeof (uint32_t) * 2; - */ - - //KernelSegment.Next = &start; - //AllocatedMemorySize += start.size; -} - -void printMemorySegments() -{ - printf("Memory Segments:\n"); - printf( "Start Segment: [addr: 0x%x, size: 0x%x, Next: 0x%x]\n" ,pmStart.address, pmStart.size, pmStart.Next); - printf("----------------------------\n"); -} - - -void pmem_free (void* address){ - - PMSegment* before = 0; - PMSegment* current = &pmStart; - - printf("Address of pmStart : 0x%x\n", pmStart); - printf("Looking for segment with address: 0x%x \n", address ); - printf("Address of pmStart(a.k.a current) : 0x%x \n", current); - while( current ) - { - //printf("address of current segment 0x%x\n", current->address ); - if ( current->address == address ) { - // this is the address we want to free - printf("Segment found!! Segment address: 0x%x \n", current->address); - if ( current->Next && before ){ - before->Next = current->Next; - }else{ - before->Next = 0; - } - // TODO: Clean memory [ Something like memset to zeroes] - printf("Removing segment of size: 0x%x\n", current->size); - AllocatedMemorySize -= current->size; - break; - } - - before = current; - current = current->Next; - - } - -} - -void* pmem_alloc ( uint32_t size ){ - // Get the last segment - PMSegment* lastSegment = &pmStart; - - while (lastSegment ) { - if( lastSegment->Next == 0){ - break; - } - lastSegment = lastSegment->Next; - } - - printf("LastSegment is for address: 0x%x\n", lastSegment->address); - - - // So now we have the last segment available - PMSegment newSegment = PMSegment(); - newSegment.address = (PMSegment*)((uint32_t)lastSegment->address + lastSegment->size +1); - - printf("NewSegment for Address: 0x%x\n", newSegment.address); - - newSegment.size = size; - - lastSegment->Next = &newSegment; - - if ( AllocatedMemorySize + newSegment.size > AvailablePhysicalMemory){ - // No segment available of this size - /// ERROR!! - return 0; - } - AllocatedMemorySize += newSegment.size; - - return newSegment.address; - - -} \ No newline at end of file -- 2.39.5 From d455735ea28bd9ecf0c48f5168e00d2a92f4df7a Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 2 Nov 2021 21:44:50 +0100 Subject: [PATCH 026/115] Modified screenshot?? --- screenshots/WIP_interruptHandling.png | Bin 16282 -> 130 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/screenshots/WIP_interruptHandling.png b/screenshots/WIP_interruptHandling.png index cc9c89ed85437e6a10451f6fc4bb91c6af6cc3be..6c22b50cae707ad433fbe054584cc07bd5240685 100644 GIT binary patch literal 130 zcmWN?%MrpL6ac_GRnUOpPndM`eh4!v8NnQ^UiY$>yk{RT-PStiVa&a++oR6yfBWD@ z<7wt8WG<&hXFVJEln<=P5{P2R&gSBTAk#&jO^p@Sho)#W|BPozRu3(w6wJJIaKsJROE+pfaBcK&+pd(|6jbQ zJ9+YCne#+TprqZv%4C$5!cJg%dU^;n(z+{AdVOST*k^g4N~O9Fm)o24i_n0_Vnn2* za)N?_Mo=adOD|P95F3=J%>l~@^b&?>PP<8=EK1ABK;gdNu1cuTh=_bN+Hq}kbab|< zsi_7B&W}~hYi%+nG%QS?jRoB4p@yZUWjr`{1>LL%aYK^u`3*DPA@BQU&^fOqtsPtvG5#Ug!XO(d-&c*D>~`y6}O~x zzj!fqmijgRbgrXt(w-_ucbxECR10xF+hRM|!P9sA&EoEbZt~&AqIYwrV3?vON@#!H zaU(-!|Ne!&Z5_mZOZKHbL!9FwasKWMTl$=qFhNpr|0YRsY5ggnX%X)C z=+!P%_PSAjLp-lg#SFD^%o~op(5t`X{b(4ru}MtMVxnmEG@(3Z@fN#b$#x#p4-UpV zR*0J)m9z#C;g=Jg-&)&kClwwDoE8I~evp2NTgL5*S+!m2h!@w0;+B_97gbOwq>za) zJW?=T-lx3c+Obpzs&!Ik-NA+`yp28Gdu7I=FVmvhKob2uZElx6lUOt3Te~|s(re-8 ztzD3_W-%GZI!@!SaNEd|cMV z$ojD)vAfj87l$DV+pBm=!mi{qd^yB>FZqyAaWH?Ax{#LLKe*eE9Zd>^xg-~IvlCJL zgl9e1v!B)gJ&zg?0tUmT=RJKIj2o#pkC zfz5qllq3fo?8w0D&4&)ZvCA!pCDqJ$3z`%kyqUTQ_%~Pyjcs=aDx`HGmUKFjWDR4? zHrX&k_8ke5S}V6dEc;0g+bxfFuT&la7L`_&@zl5LVU$4|JCauM}!Veh9 zk&ZX)6t_}NiruzNM+)LJEYXQ*U8eRv@e3)14DKAgiy;n#JNvt^(JJOy_iB{8&+iP2 zGZCx4bxDEAySeh8f+`1&0YRc&N)ceZd2YL~xpn_G1WUH*N=D&@>mJ;_JA*_jjl4MA z59(U3J3Pp2I+p4Ys_0o~5P=c5oX3mpsvxM8yRumgh|rqhO*rzd1%do8pea|N3xPex>N%cRyB}Sbi^h!2#PWoe*uh= zny#9yN9R*kwmI3HIxXhX(cZaP8;e<%T8g?nH3tzJL1=`bh4&Wg`Danc7t4GkX=HZk zvGeEDuU2b>I1cBykLW>$)V!a3*CELYVW_lX+pjh)u|D5)g!gu~ zMYo}Y=Z%LP`wQpF%JeIQ%s-)QQVNm=waC*d6)?S?&!dw}NT>UQzP%M2j&Rv`hqiIdszZ`|nALYS%g9k5Y9JI%Z$+Zc{X-Fd=DXZxUH zWdA&3>Mc+5iyZM(8;!UjZ|@y?l8AR?IIBf&Gk-GVv&lY}yVgusd)GlSfWF*(M zQ%2J@LP2|-T0WNx_n4=`{8AnLc5SdWy4xxMkWZ+m+5S zeh|rr!p8u!ba9(b)&qT7Fzbejjwqi3w;MO;pMjgt$G}_z#WCcTexnV-qm&>C-Y+!%E7p z{c86<>Xvog3E3!Rk<2q|6#-{*4JrQ;=TVGwkcOUZV0MEcHRYTQNhQzVJEz?QF_gYA zB5XBF9^SyaE`G(&d-PF~`~k}Ca|}g`3B;3yK5rc4@Bv%xN+UG}9X6ZC zv0sflM0L$tF3V|_md7ZRiB)zT-yh?_<=|gJ!V8x{Ln zM|>lP;a{0H4*mYzWuvZ3@$N2!u8A-R2|TC|+z__l_@+-Z%^efoM-9Jd!Qa5^mON9e zRVMCRr*C>reU))rJDZZ=J8KIqnwh|kVNJ@oo}aT_l{eIJZ4Qk1Ho4egfvT&U2iLK& zRpD@8$%f2Ph&AO)5&n-PV_z_XcZWqKo zZ)PVpTMO155C@BfR%NDEcwe@9^o(WK>Qtk4GYhLN#ilX5tB`{J9xJjKeChh&a#hrA z&u-sZ-=fSp*XjApE_n&7gR%HK-uahD%KPz0WzUL0;4Wcs5bN>*xy6Qxl3{im(I^|u zs4W}Mk}VVLF2Ueey*s|@VxCS8Q9I&o#3ag%BSzfA3e80Fn7ZWeS7R~=>^x*abn+*Y zI*M(Wzze+u)r#3w*+Rld&3+j5bHy^EkTnAZk@V9|*+26eF01@AK2AoonL5D^+k zaz*L1?Lo4j8VJyP((^tm$K+Sjq~l9r8aj2;tRfas4i;&Q345VONYmv4-TqYT^~M2< zu~1EM%g9on_n8ZV-geD&sG+wGi>)o6ONZ679Vv}a|UL!-Xgr^|8=pl|^?A>}Ri zETn3O94aymQmB1BAI;nej}CD%GiQmji7OgB?B5)!H`L4tjaP^W;$h6v3w(lG8-Lau zQS#jEc5gW0v%N*XFrhi@`<0Q#3fr$J25S0U^TL-b9)#<{Ch5@@HO36tI1QUlk`~QY z7jaD3`(X%DK6$0}G&rXcCjp~p z^Y?1l_v{gL-Qk>NSG47WerB{c&c$nE&ZZ3F^L(%msRxZG5|B0$wss2=2udwSe{{s9 zq2;E#b=_UdGO9DlYiAZ+cJ-3HJx%ZmTm14Dhfv};XHv0-t7sl__KxPxWrIsd}9Wu#y~O#wfcqeqi`>K%P*FAIAs>C#C(yt8bQ z!6o}3yPQ(3@9{j0uGfNc%-q6Rg;c|?g{YG}Fc*#IimPYC_GTtz7TB2P z!`7{zxg4gt4=pPrM$a0~mqf6l=YFy3UsOdCr-%xlZVn@gJAI~bgYazI!QI&kvexjL zsJv&t2ZbN4(r7Qgnoq{mEI&(1K_u(`o~c-vRup8bm9+>Xd{ zl5>ayv0mo+fdr{$(xLfBHaG=;R?z}!kx$|wG0!?=H;LscAsB@l9ISOS)zsFmj&7A1 zzXv0GuaDV#`C<%ytkCRFRCM*F)b1#C3|D3Drg-1O*X@byceE(>dA&Gr^j;4A&3>o| z%6~xC*>ARzoS)m&-ce=B+%H4!lT*l%Jj3Y~hpUR@3!Cw2-_CE@u5KxQ(hC24`2^sEQ=Pq2(h;ym=2<&_4c)j8Keg zA7lo^$EPv2C&8mIcaIxyaY_eqZRUs&leosngp6*P!ZP>z6SCWf0FdgT-7xmO;msnO zbv{VRy5$qqrA(Wm9hJFav@@^Wyonm=<{$5`zFQIENfx#&A)FP6vp? z#C#?>D_5gId}{AF;O`=3KecFilab8Fs@eQXQf=v?1r zx&g1+2-2}qzh-t{GacJE;_Mbyw~7l}7e=t_{FK2&}4Lpc^H z=h1e(0n<}YY_jiX^AlK-LgIoSy5*|guAkjw@|7by_e7#9ajzm&_w5+v+)XWTEy-Mk z88dC~z7w4VM0T$ln%+pE>@zsf0!sRPykkY&#R~M_(io=GGCGd10DzuLkxCxw{4#f%w7aU=g|!4oIWY|MlC-RRA?kLVZ4u~x7r?EnzK zSWf3=%*6oj-D$jj!GJ|6u|(Z)o(~rED*!0y<30pO1eAs&tUl${_X$g4LT z1B2rGZ5mReY26dm^_^QL$ADDghd=9{TSs34tUs%uME4sT#i3?wD$U7#+_`2Ie6IR$ zYw%-lBBCUxM>oHdnnZ;RCIH}(YMgbd>OH6|=X;3eEx}^dFy`hQ-4X(dKia58f2IR0 z#&RNi&x!SjTM7>La+&PTU$y%T=kDIUJ9NmO2azf)C_wByn2rp;xS%MMJUXGR7&rlu(X6yb zN?gXZFe;dDA07i{;n5$RjG~MDaclzP+bXk!$!@qQXAb~~nLH*d#psJ_OC~9@daFRaPQ?r6Hqn3&rvA=7J}d4- zQv46P3m3AH7q_1?aK$Q{M9mZ+^mD(s8f9k0CP=XZKrkWlY3D73UB(l$H#g_2a*WnC zrh06cS#kpy7-O(gB?eM!CV_N~nZmXval|Aj z39=AY>_Jsp_6QjISWXKAKy!Xgz!82wqo;qCs!>Fd0D!5~KR$8#eC}V1=D*>C?|mpi z;Q3r}CD-?~3{22G|6H*Ef(!NQSdWBo3Iaq8kEu2$2y={;8ct@d>IWx~D)*1jfNMoY z89j-(>iR9s{iQ4Eq>KYkRi%VB2LZ|XJri9vfLEt89arx`NiK-nnnE7jdi^4_WuFc@ z2mo!Wrvq)^q{Z8gug2D1n%xs^r1Q#oEw_9Z&kuRM@PW4 zxg^?-`Fr1bdQwKvYw6?N09fX0bkIfLKym{VI*6Bl~RM(T570iZuO zBOqOO`aQCpdS4lZfb$dM=hB8Y@|+?s1+KGpVUXs*=(#Pppl?y1WRx6@Qtc(3hHt#6 z+4f&m<(Iu{Ij{KhQcoL!kj(LyyMVIL6gkDe0CA@Y>7Je zeAdEuhZuA-UZD7v47i6tW=RSi%$vtSUGE z0_2!$=s0SAJuV+y0!HFm?!QE2VCBbNFoQk&=yZfebfA<5ZvFvE$l_8VMW$ip%%$pM z_x?mCcIW(?mx`bNK1gp3HzcUjL*%u*kT1`2WZ&#s^=+OwyPV=HFi{d-+phoE2-M|- z|1&6~R*yaDZCamPpH>=C^F-T@@3y7|nRK|)2m&dh_8G4{A#rd=EEXY^ZtQv3M@u}e z#K4GDYUPU5mZhphzjAY@ZyyAMPFJNPd2;_(b$*T@ax2t*{LXX+`fYl0NJwTWgK4s7 zPm5Jh>y(t5NMOX{+AMAR@xiJU#t8C2RHv({NenLSiIC{&GE-rWneM?DEgV{OtzvewW0JIx%iHgfq1;>+g&bE3Ipl;8OpK+N5h-NG zAO@Y`Y&>3^%mHgJv{dsc$bm(3C0E845al%<82bsECTm4f5btMLp)a%qC)$R%1@Daz z&j1BrR(u!F96o+i4YR2)Nw{#FLx96U;iIv~70q9R7lvHyG~}$3Q!;RQ_eBdVwL)?W z$mRsheCTyg2J2y}Wuz+b1r4&FJFpt3$FicQ-65gtoIRw6B^NV;WeMxt=SkH1MVKi# z0@my-(K9b}WNTR^{t-Rf0=~qTXwc1;S+2d~C=#I6ixJJ50O6b6&_- zs6b6@=JwT@U%(}&pUqM3i;O*Klli*!UG>Y`S|zYKe5Mv`&1}Q_+t}0o*7E@bT%*N;_v>0pbHkYykbAMEW84 z{XZp1sYT^0<}HE_J5?*(eDIO;xBuc~)vs&b$>P%qNc+f=rE0ar|LGFdZU;MfG1YU+~aHhMjhw%Nv%xv3? zG%y-8qCU?nO9Iwe?-crS7IMJ82X)0p;jU^9Zc5G1)L0Z}hvDfX@XnD>=r|g^A?brn z7}qg=c49G4(oAK!5JIKd^eO$bDszR-PZ;48UyG1OCiJd=iVL(w$lhHXr72}gUdr%( zjwko{X@-o*xSCF$E9GK_sN>e`X6$!Ho#(1^Vp01o#hm?x2(F`3QTB{1-Ptq-Emh3& z1y-AypVlrJKWSU@8C&y>ELeUmH`7h^dCqJ&EMY4`#TfvP^wmI6Yj?WDp_Ye1V~hQM z-F~#=wEn3b+vxP_;nNYMrO7z&`W`1mUnTM}n-BDXmDyHFp}x(z`h?r-1db@V<4S&S zIJ=XKC*GVL`k+<>dy>fWVd-sT*e(4Z#mSPkvxEx{7888ydwq-0$`)O#J=_c7o)b~C zkLnaavhpRX2%g%Qd8sySJ@76&1ZyJ47c>gf`HcSb=~EB=rbEu-P!j;)xOUVFa9J(_ zc&|FelDmChiacO=x&FmK<6(Dpw6WgKr>lF9D!9A!TTL$=olDBfJOtaU>oMl~7?LI( z_)SU}41kYHs$6LxbW8EG$=&;LKENx|Ov6G50gYNtBZkoNH+ex2wJwHF`>`Eby`3 zmXR*iBi9*o-a7}XzalPW)q*)ipIQ6J$I2;DASCofD*>)aPtIg8cp zhFu;Gd}V>9u zV`U0w@riQx{N>>b%{$%qi64!(vhs%l@5H~^(n2^10%F>K6e!G?1PeXhFaM+ux|xe7 zVrOEVr*1m$8{sv5TM{?=oqEb!wH0UfgXQf_k)EdEQI}k|uMl8Y`?(8~&RVQihRe^% zwPN6N{Cv|lqLlEIHD@{$VrOy}dSWOtmgZJuuc*6iX}&GILCwU2r(f5^JZ94sx<`nc zxM343`1P62TC|OgrNy)^F3d@9Urt{b7{XpK0-d2^Xvg zY;PF?ZtRw`4$*7H&G6)+`6ADe2YR3Ik+Cswl#J!6;efb`gV;$BX!$u`F1243HXR6m z@XCx~LN3Tn@}r${?szz*M(u8epA%S4#m!_p5F5mk`6jmZeLirmmU!*=cBnf==jLU?k8Ehg3wevuA2B^y&N zB>cP9ElE+Yh#40@-!1(~X*VwpX!uM%Br->F_*m*W&3q?-^h%T=b$7+*e5ycn3`j)Y z|8l1b$ZI$!=B;VUd(wY;Y>Qcm@%~Y%4bc81DnH+8%3gdM;~Zk*CsY%pPV%4$4VKS^ z=v2#%FI^KJ?_A5lSS4f>R4*oYC%?kyPswYlCQs}Hw=xYY?ijULvH8UD+Z3tO0v4hj zN~$Qh>7Qaq8qq_Dh2xq8L{3Y=kZUC=U@M**_d-BmB5!CQp{$YLpXwU_@*Xy;9V=-@ zQb_zJQ1fE`HSAbw&>4-?3Hq-&q`frt-|pRm7H2XdC6KsyK6{?ea;>5N##5ro<-@7c z%Z3ZK6D3U(E{PejjjcuIy*U!ji>BMbt?&i48R7^p00_vNB0G+Ns@(ibTr|d6_79no@=MtYLM| z0%{nTg&KG&OL;{?tXXU1rja(0PeaaG#2D>^j4jzSuarySB=279k}f+)hPFgkK%k*G zG$UZ7uhVc*{0?igYUK09e1`ADHOKYVYMF5OPNcIkV?)Bw`6O-@k_q5t8jQET#L zU1MTx0j!_-?h1E%4W*S61Xqjer`>D_o?{K}Pw5xpugs`rRDXJUQ=QSHU zr!1g0;g_zPz@#=<;wjK~%4|lftZ;0uC~nwVUDo%@IjJ~+`s&&*!qj{;zGfUT&0)3A zY}?c*>RIPwvCgyLqH}d?2jy^yobObpjkxGR^Emk_u_s0&g)mt?OG#_|nis)x3WeZ8 zc=B-V;+}*D%P$8$hRUfScCN-OuSdDvjm{K~A)DWm!_|HG>LVAkK2eRn(e(+x+wCG} zVIQfyze)#KIYHmh%wGN&2ap0sV1U&h%-dfe*6ZX$M(fmXuH)(=fY^mPFxY=uravpg zpYNOogKpP^n*3OE9fRo2<5(W)EvVT?4o+S4p!K@wfmB5a4slwM>___6FPWMPE<4Mt zv342C;Z_d5wu%ao2k@rSuk~es?MT~`GS5*HSe~zH0>w^l@sdVQPodc!bug^AlyOPqeVczURpX0tI}|i=+?Fi5t765UB^VfLrcgTd7|g zo4y+d4;(x3=?hMu6t+HQe{h9 z&N7wXjCw?DlG3_CI?u(TomXio@7U9g;`o7U(VyPQ9l|(;Ww&i34$U)8bAPM%L$ERd z?;)US5valItuk{VP%hrB!c&jFo|xfp0qQ83Tni)tPxfQiBHAQ%RzElqiqQhE4vPX0 zKWXuo=B(Wn->!FnBm65{#}g}kQ&KWm@&pi7 zrdy)ptNUROh9{~LIYtnSUUX)|fyjxS=TV&V5gx#;*S&nKN)@T?CuSA)%xP|E)Zrg+ z0s#EChI6TW(L^O0D_9RC9vHW(Iy?^e{&%9sV^8La%Bh)#gq%Kv>7v2Z2?mYL$~Ah z@?F|N3FMu^d92AqX_IAGGqJe0yi60z&e;k0bH3?N;weT-fn;O-qi&zEPM9^1$f@BI z{Tf03R+o$O;#zWG6Ac)NikwxkeR)EL(J_Fcd;d5oPTah*h%N3!HFt{_{hUmU-Q))( zaDstVW7pwH++3$Di+Qw6^Y`=1#Ybvkj`?HBi*JwOaya1>;(41oqZfRAV7}0B*b?lz z)yJJtjXQ0V6ls$3s?=Xw(S#v!g*?ywoYgi{02xQk>iiu{S7-@a^xQNjcBzgD@L#jS z1{K}J-{T|bOQj`;1aoPD3>jJcL0xt5-gN~7%XhGZ@-wPB7DyJXz-mTr?>#=S9N!kl z8IHY!nKXflJmQkH5RvhIN#R>is@FY!e!F`z{(IUsG&dut&By^%eN*^^$CS1v_(AH> z4FO3p@4TM7wqdPjxPawS^ZIchNAjoB!o>jTgE5^0tGeH(4-cB>72;t9;3`=$jnmdaJL z-Rrna5O@Clj+j?A*jh8+mK)HhV!HDd&eQPWgMppxo6N9Gbk@5;h+t*DNhPGn?1yvO zV1_)0A>Ak}<~NQ^eg#W+(sv=PDrF?wiPEJE!-`@Wpj#}ie614-iW4OFKg0h$U3u4CSXWHEOD$TRql_~Ay{RR(J~ zL`Ei88mo?o8100&-VmIA6#3kCgp(w88B`Gs1|R`rI>F{2X1E)q3fvwh$)Lcs1Li-i z=}QHJg;uxWW$mDNbcUc*6m-McmolY+jBQjjiJHZRks65N_Tyly-j^G_kN`Gg37z7? zhKm$aJpnI}dX@^Y;rBDDY>Jxlbnco0%?^Bnhuj!(+x*SVLcz@I zp!z%dQHdr;5+4jU7hOwf(>Q7<^5=eh^6IRpftL?nYO;9hWI5ay^?Kb zK3)n=e#?$@-udy4NANf6n0tVdu***tX^1Ke^7zokT8cK~$=s-vO&IR8Z{Yy^(=Pp? zdJ&RNfr9@}GC9wkxRHV2;+Pz48H_ng78$oLB8wG{l6%G>&lwmEb%NedeoR)Gxx7bG(f#S5I|44ai0@& zHgBl%RjVeyMbOZ`@VuuNwIrPXhtL-nI#66G0Slc1wStK6maKMyk%_v;^KUw+YSar_|J7< zvg5roR-o$wV@y;jFF$=~2T2n|MDyYY%!c~x+l73a**#cewjf3F06;3_`kJUs9k}0& zJ)_#^s$Dz@YD`^x5;}9Yo-l^zQP0%1Z1J%=+xHG;pb{^_6Ia&NEHz;)9yinQ!R&-E zJySFjOD<^R|E_sj?0vMxD=1Zn2E_SX>$1_+=iKn{{sLNr9ZgS4LYW5^k2AnJ|YLwTSA}o@fySCx%q7cCeAo^ zf(}9Qlo(Bz8>oGH=x1jT@`Aute19tcAKDN~_F{Nw*%J+Z0eb;NKV*fxChAUGwshYn zsF}FrfwPuDiDWO%Gg0EpJSV^}7Op)bS>3kfQRM(RG_ZQ6D(Loqsk2|#%2hRWxkS;Y zc6WDg9tJ;W2auDwtKkXa?c~PF$U(x2ru5C`tb`?QZ{DBO|CL&RQ~8%LM;Xe9Ce}BE>_X z-U1G4<+p6@)2Qm+0vZ--{K}PO9e5iHa5iRDYbv@eR>qO&a8nT7fj(7`$b9%fpgaBa zPbo3I#k4HPY}B;kW%!VqP$8s`7R#mPKF2S(Swep*rZUoveBK9g)sP{obCe_9w(d3H z@BInPI@l%mSjl>)orl6V;~odf_5GH-b$uvp243;Ih6O>wd3BrB@al+2Hm0uwd*p;*=CB6{HT&pgfW%J2O5b62kCK5jW%Cmp{{R}i< zcWpJ$c5wL`kZKO<;j=(S-Mq&AE-c2=U6FOjo(Os>@xl^HV*qaw`Ca^!%f z!Zh!ZwezpWzd;f@uGc`lh}+7x^~?)Y5(aHP>1}>LBSg0e19n;<8?00Dd~rDmB{tP& z)~L3`?|gsyG%E@x{D<{+_*g-cu-3Hg8|15Nk}-WAH@6ui^m|&HGn_2_i@*8%+<=?& z+`nl&xhk-DN|7C&SV{lu**|nX2FDbxo3{M)8MQ*Wwde~DM4Z6a%r_C}{zhjjdF!G* zE>@H6s?iA{XQM&o<_~(vsPZ=Do=RWmuICz)R9qBJANr8b`$QJ6^-_4(R^911J6 zh0wGL(k0kYahA!L#5|reV-^v^gXAu4r@QRDcf$?lGAkoQZwo%$C{Qc@BQ!cW=xT4E zi>{b_grjXQBdA6SeuM z@Hd_k8m89}6s$pVG0t}~8ZRj<{BTLji7QCpPO7bli2>$a2!C#h6AQiy??RgBjKD)u zk>_FC62}04HfgSIU_LAWB+lddN3I5FZ=XIb*3C8G%>p*6{PZ#Y76yYs-L0bkX#P>) z6og&IY#9BBwA1bxRHj647$I?y2Jf6~6Jok>VB1Z#%T!2KD87W#f>iwK3?TM@!ymoh z?bIU8sOllL1t%J~3OPyMjpk7;{TmsjYBN^>rPF~Pe_6)IEdI2NX*ibe4!45Bv?dp; z(0H3`TjdT}^RR7sljOi2A#zgI~Y63N|3D5F9$|=YWnQyCS>&x?mjT!#n8i zyg{LOuS&(7eo~XLpx5NT!H>WTun&1Y^F4jIrmc$2Td8?3;>1)?rU@Lk2{GZVkN=p- zhF=qRMRR-Dns%KHa&ry_uYdf}y{kZc`rpjr|0M{SfRE5EgDg;}NH_tO^F?Jh_dNTY z$JLbtzzTiC7E*&ihGwAdzu&}WY~mtM{)IqQ|7!$VU!jp?B9v=se)R_h08eK}#F6zpJll&vo!dyq|*b*3rzaIu^D>0sGv_3m$NzH{`V?o<;Q?SMwrMDMm4ypN2Ae7K>A`0L6 zVvN`)uDy;)_KaNFtt!|m;{suFEj6I=PD(YKL6TFdOnm?Y0Q6~OC7luk!!0cmpQH1> zQ}dPa5a^`wY2*fK*#5RMlOvJD_G4``dei8tMmy*#Jn3X`jHO(0p1~GQv^7$PSImY# zZVvOxvI9z`mqclj{@Df<5OI;n{Z|)MV5Z$?DD>AYMxT}9l~qvW4&j;>?b7;-LO(Ip z=29`9`c7Z-Zp$dy^5af2EeP(=g`kqTw8 zL0l~#4?oKtXB9@G*G&RJNK6&fPP5C>?%ZXi)R0%#ntH-|6jok;eVJK{_9Lg|t?QO$ zH5mtB!)hHs&eWz0R$WJ2Dy%Ev)cQDi>SNKO&3^sv{h5b@{}EW|d`fZ?VQDV@Gi3^u?qhUd(rJ^9)T>Z0($ z`^~M-&pF#i8C)%@8RkmPu*~{e%J&WfVMM&KnDAi?uPnE<_a&UN@p9aTQW}Up(fU$A zY6S>r{=$%ac_HWzb)H&Jzj=wxqm$&APjRu%%5!qQ)2-OLM*^qYM{}q97OREFkdcNp zR*f{w0uP}D9%}vUsrz659^|Lv`?Im?CvE>98uR}B*DC-2uz%8v|9>a{yWceZKM*Ac Zino Date: Wed, 3 Nov 2021 20:03:38 +0100 Subject: [PATCH 027/115] Split up boot.s into multiple assembly definitions, Started page frame allocator implementation, kterm definition is now considered c plus plus --- Makefile | 9 +- src/kernel/arch/i386/boot.S | 89 +++ src/kernel/arch/i386/boot.s | 566 ------------------ src/kernel/arch/i386/gdt/gdt.s | 37 ++ src/kernel/arch/i386/idt/idt.h | 4 +- src/kernel/arch/i386/idt/idt.s | 6 + src/kernel/arch/i386/irq_table.s | 138 +++++ src/kernel/arch/i386/irs_table.s | 256 ++++++++ src/kernel/arch/i386/paging.s | 20 + .../arch/i386/tty/{kterm.c => kterm.cpp} | 4 +- src/kernel/arch/i386/tty/kterm.h | 5 +- src/kernel/bootcheck.h | 4 +- src/kernel/kernel.cpp | 56 +- src/kernel/kernel.h | 103 +--- src/kernel/memory/PageFramAllocator.cpp | 1 - src/kernel/memory/PageFrameAllocator.cpp | 38 ++ src/kernel/memory/PageFrameAllocator.h | 14 +- src/kernel/serial.h | 70 +++ 18 files changed, 695 insertions(+), 725 deletions(-) create mode 100644 src/kernel/arch/i386/boot.S delete mode 100644 src/kernel/arch/i386/boot.s create mode 100644 src/kernel/arch/i386/gdt/gdt.s create mode 100644 src/kernel/arch/i386/idt/idt.s create mode 100644 src/kernel/arch/i386/irq_table.s create mode 100644 src/kernel/arch/i386/irs_table.s create mode 100644 src/kernel/arch/i386/paging.s rename src/kernel/arch/i386/tty/{kterm.c => kterm.cpp} (97%) delete mode 100644 src/kernel/memory/PageFramAllocator.cpp create mode 100644 src/kernel/memory/PageFrameAllocator.cpp create mode 100644 src/kernel/serial.h diff --git a/Makefile b/Makefile index da1419f..e3010f6 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PageFrameAllocator.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -57,10 +57,10 @@ $(BUILD_DIR)/kernel.o: $(CPP) -c $(SRC_DIR)/kernel/kernel.cpp -o $(BUILD_DIR)/kernel.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/kterm.o: - $(CC) -c $(SRC_DIR)/kernel/arch/i386/tty/kterm.c -o $(BUILD_DIR)/kterm.o $(CFLAGS) -std=gnu99 + $(CPP) -c $(SRC_DIR)/kernel/arch/i386/tty/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/boot.o: - $(AS) $(SRC_DIR)/kernel/arch/i386/boot.s -o $(BUILD_DIR)/boot.o + $(AS) $(SRC_DIR)/kernel/arch/i386/boot.S -o $(BUILD_DIR)/boot.o $(BUILD_DIR)/crti.o: $(AS) $(SRC_DIR)/kernel/arch/i386/crti.s -o $(BUILD_DIR)/crti.o @@ -82,3 +82,6 @@ $(BUILD_DIR)/pic.o: $(BUILD_DIR)/string.o: $(CC) -c $(SRC_DIR)/libc/include/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 + +$(BUILD_DIR)/PageFrameAllocator.o: + $(CPP) -c $(SRC_DIR)/kernel/memory/PageFrameAllocator.cpp -o $(BUILD_DIR)/PageFrameAllocator.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/arch/i386/boot.S b/src/kernel/arch/i386/boot.S new file mode 100644 index 0000000..5f5ba72 --- /dev/null +++ b/src/kernel/arch/i386/boot.S @@ -0,0 +1,89 @@ +/* + * Multiboot + */ +.set ALIGN, 1<<0 /* align loaded modules on page boundaries */ +.set MEMINFO, 1<<1 /* provide memory map */ +.set FLAGS, ALIGN | MEMINFO /* this is the Multiboot 'flag' field */ +.set MAGIC, 0x1BADB002 /* 'magic number' lets bootloader find the header */ +.set CHECKSUM, -(MAGIC + FLAGS) /* checksum of above, to prove we are multiboot */ + +.section .multiboot +.align 4 +.long MAGIC +.long FLAGS +.long CHECKSUM + + +.section .bss +.align 16 +stack_bottom: +.skip 16384 # 16 KiB +stack_top: + +.section .text +.include "./src/kernel/arch/i386/irs_table.s" +.include "./src/kernel/arch/i386/irq_table.s" +.include "./src/kernel/arch/i386/idt/idt.s" +.include "./src/kernel/arch/i386/paging.s" + + +.global _start +.type _start, @function +_start: + /*Setup the stack pointer to point to the beginning of our stack */ + /* I believe its a high address growing down to lower adress for the stack on x86*/ + mov $stack_top, %esp + + /*Reset EFLAGS*/ + pushl $0 + popf + + /* push the pointer to the Multiboot information structure*/ + pushl %ebx + + /* push the magic value */ + pushl %eax + + call early_main + cli + + load_gdt: + lgdt gdt + + # set the segment selecters + + movw $0x10, %ax + movw %ax, %ds + movw %ax, %es + movw %ax, %fs + movw %ax, %gs + movw %ax, %ss + ljmp $0x08, $flush + + flush: + + + #load idt + call init_idt + sti + + # Try enable A20 + # mov $0x2401, %ax + # int $0x15 + + + # enable protected mode + mov %cr0, %eax + or $1, %eax + mov %eax, %cr0 + + + call kernel_main + + + cli + 1: hlt + jmp 1b + + +.include "./src/kernel/arch/i386/gdt/gdt.s" diff --git a/src/kernel/arch/i386/boot.s b/src/kernel/arch/i386/boot.s deleted file mode 100644 index 096450a..0000000 --- a/src/kernel/arch/i386/boot.s +++ /dev/null @@ -1,566 +0,0 @@ -/* - * Multiboot - */ -.set ALIGN, 1<<0 /* align loaded modules on page boundaries */ -.set MEMINFO, 1<<1 /* provide memory map */ -.set FLAGS, ALIGN | MEMINFO /* this is the Multiboot 'flag' field */ -.set MAGIC, 0x1BADB002 /* 'magic number' lets bootloader find the header */ -.set CHECKSUM, -(MAGIC + FLAGS) /* checksum of above, to prove we are multiboot */ - -.section .multiboot -.align 4 -.long MAGIC -.long FLAGS -.long CHECKSUM - - -.section .bss -.align 16 -stack_bottom: -.skip 16384 # 16 KiB -stack_top: - -.section .text -/* -* Interupt handlers -*/ -# NOTE: I have no clue how I should use these macros. -# Have tried to use them in a myriad of ways, none would actually work -.macro irs_NoErrCode code:req - .globl irs\code - irs\code: - cli - pushb $0 - pushb \code - jmp irs_common -.endm - -.macro irs_ErrCode code - .globl irs\code - irs\code: - cli - pushb \code - jmp irs_common -.endm - -.globl irs0 -irs0: - cli - push $0 - push $0 - jmp irs_common - -.globl irs1 -irs1: - cli - push $0 - push $1 - jmp irs_common - -.globl irs2 -irs2: - cli - push $0 - push $2 - jmp irs_common - -.globl irs3 -irs3: - cli - push $0 - push $3 - jmp irs_common - -.globl irs4 -irs4: - cli - push $0 - push $4 - jmp irs_common - -.globl irs5 -irs5: - cli - push $0 - push $5 - jmp irs_common - -.globl irs6 -irs6: - cli - push $0 - push $6 - jmp irs_common - -.globl irs7 -irs7: - cli - push $0 - push $7 - jmp irs_common - -.globl irs8 -irs8: - cli - push $0 - push $8 - jmp irs_common - -.globl irs9 -irs9: - cli - push $0 - push $9 - jmp irs_common - -.globl irs10 -irs10: - cli - push $0 - push $10 - jmp irs_common - -.globl irs11 -irs11: - cli - push $0 - push $11 - jmp irs_common - -.globl irs12 -irs12: - cli - push $0 - push $12 - jmp irs_common - -.globl irs13 -irs13: - cli - push $13 - jmp irs_common - -.globl irs14 -irs14: - cli - push $0 - push $14 - jmp irs_common - -.globl irs15 -irs15: - cli - push $0 - push $15 - jmp irs_common - -.globl irs16 -irs16: - cli - push $0 - push $16 - jmp irs_common - -.globl irs17 -irs17: - cli - push $0 - push $17 - jmp irs_common - -.globl irs18 -irs18: - cli - push $0 - push $18 - jmp irs_common - -.globl irs19 -irs19: - cli - push $0 - push $19 - jmp irs_common - -.globl irs20 -irs20: - cli - push $0 - push $20 - jmp irs_common - -.globl irs21 -irs21: - cli - push $0 - push $21 - jmp irs_common - -.globl irs22 -irs22: - cli - push $0 - push $22 - jmp irs_common - -.globl irs23 -irs23: - cli - push $0 - push $23 - jmp irs_common - -.globl irs24 -irs24: - cli - push $0 - push $24 - jmp irs_common - -.globl irs25 -irs25: - cli - push $0 - push $25 - jmp irs_common - -.globl irs26 -irs26: - cli - push $0 - push $26 - jmp irs_common - -.globl irs27 -irs27: - cli - push $0 - push $27 - jmp irs_common - -.globl irs28 -irs28: - cli - push $0 - push $28 - jmp irs_common - -.globl irs29 -irs29: - cli - push $0 - push $29 - jmp irs_common - -.globl irs30 -irs30: - cli - push $0 - push $30 - jmp irs_common - -.globl irs31 -irs31: - cli - push $0 - push $31 - jmp irs_common - - - -.globl irq0 -irq0: - cli - push $0 - push $0 - jmp irq_common - -.globl irq1 -irq1: - cli - push $0 - push $1 - jmp irq_common - -.globl irq2 -irq2: - cli - push $0 - push $2 - jmp irq_common - -.globl irq3 -irq3: - cli - push $0 - push $3 - jmp irq_common - -.globl irq4 -irq4: - cli - push $0 - push $4 - jmp irq_common - -.globl irq5 -irq5: - cli - push $0 - push $5 - jmp irq_common - -.globl irq6 -irq6: - cli - push $0 - push $6 - jmp irq_common - -.globl irq7 -irq7: - cli - push $0 - push $7 - jmp irq_common - -.globl irq8 -irq8: - cli - push $0 - push $8 - jmp irq_common - -.globl irq9 -irq9: - cli - push $0 - push $9 - jmp irq_common - -.globl irq10 -irq10: - cli - push $0 - push $10 - jmp irq_common - -.globl irq11 -irq11: - cli - push $0 - push $11 - jmp irq_common - - -.globl irq12 -irq12: - cli - push $0 - push $12 - jmp irq_common - -.globl irq13 -irq13: - cli - push $0 - push $13 - jmp irq_common - -.globl irq14 -irq14: - cli - push $0 - push $14 - jmp irq_common - -.globl irq15 -irq15: - cli - push $0 - push $15 - jmp irq_common - -irq_common: - pusha - - mov %ds, %ax - push %eax - - mov $0x10, %ax - mov %ax, %ds - mov %ax, %es - mov %ax, %fs - mov %ax, %gs - - call irq_handler - - pop %eax - - mov %ax, %ds - mov %ax, %es - mov %ax, %fs - mov %ax, %gs - - popa - add $8, %esp # cleans push error and irs code - sti - iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP - - -irs_common: - pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax - - - mov %ds, %ax - push %eax - - /* load the kernel data segment descriptor*/ - - mov $0x10, %ax - mov %ax, %ds - mov %ax, %es - mov %ax, %fs - mov %ax, %gs - - call irs_handler - - pop %eax - - mov %ax, %ds - mov %ax, %es - mov %ax, %fs - mov %ax, %gs - - popa - add $8, %esp # cleans push error and irs code - sti - iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP - -.globl idt_flush -idt_flush: - mov 4(%esp), %eax - lidt (%eax) - ret - -.globl enablePaging -enablePaging: - push %ebp - mov %esp, %ebp - mov %cr0, %eax - or $0x80000000, %eax - mov %eax, %cr0 - mov %ebp, %esp - pop %ebp - ret - -.globl loadPageDirectory -loadPageDirectory: - push %ebp - mov %esp, %ebp - mov 8(%esp), %eax - mov %eax, %cr3 - mov %ebp, %esp - pop %ebp - ret - -.global _start -.type _start, @function -_start: - /*Setup the stack pointer to point to the beginning of our stack */ - /* I believe its a high address growing down to lower adress for the stack on x86*/ - mov $stack_top, %esp - - /*Reset EFLAGS*/ - pushl $0 - popf - - /* push the pointer to the Multiboot information structure*/ - pushl %ebx - - /* push the magic value */ - pushl %eax - - call early_main - cli - - load_gdt: - lgdt gdt - - # set the segment selecters - - movw $0x10, %ax - movw %ax, %ds - movw %ax, %es - movw %ax, %fs - movw %ax, %gs - movw %ax, %ss - ljmp $0x08, $flush - - flush: - - - #load idt - call init_idt - sti - - # Try enable A20 - # mov $0x2401, %ax - # int $0x15 - - - # enable protected mode - mov %cr0, %eax - or $1, %eax - mov %eax, %cr0 - - - call kernel_main - - - cli - 1: hlt - jmp 1b - - - - - /* Tell processor to use our gdt*/ - gdt: - .word (gdt_end - gdt_start -1) # Size of the GDT in bytes minus 1 for math reasons - .int gdt_start # linear address of our GDT - - - - -.att_syntax - - -.size _start, . - _start - - -/* -* Create the GDT -*/ -.section .data -gdt_start: -gdt_null: -.long 0x0 -.long 0x0 - -gdt_kcode: -.word 0xFFFF # limit -.word 0x0 # base -.byte 0x0 # base -.byte 0b10011010 # 1st flags | type flags -.byte 0b11001111 # 2nd flags | limit -.byte 0x0 # base - -gdt_kdata: -.word 0xFFFF # limit -.word 0x0 # base -.byte 0x0 # base -.byte 0b10010010 # 1st flags | type flags -.byte 0b11001111 # 2nd flags | limit -.byte 0x0 # base -gdt_end: diff --git a/src/kernel/arch/i386/gdt/gdt.s b/src/kernel/arch/i386/gdt/gdt.s new file mode 100644 index 0000000..066cd1f --- /dev/null +++ b/src/kernel/arch/i386/gdt/gdt.s @@ -0,0 +1,37 @@ +/* Tell processor to use our gdt*/ +gdt: + .word (gdt_end - gdt_start -1) # Size of the GDT in bytes minus 1 for math reasons + .int gdt_start # linear address of our GDT + + +.att_syntax + + +.size _start, . - _start + + +/* +* Create the GDT +*/ +.section .data +gdt_start: +gdt_null: +.long 0x0 +.long 0x0 + +gdt_kcode: +.word 0xFFFF # limit +.word 0x0 # base +.byte 0x0 # base +.byte 0b10011010 # 1st flags | type flags +.byte 0b11001111 # 2nd flags | limit +.byte 0x0 # base + +gdt_kdata: +.word 0xFFFF # limit +.word 0x0 # base +.byte 0x0 # base +.byte 0b10010010 # 1st flags | type flags +.byte 0b11001111 # 2nd flags | limit +.byte 0x0 # base +gdt_end: diff --git a/src/kernel/arch/i386/idt/idt.h b/src/kernel/arch/i386/idt/idt.h index cedb1ff..04173d3 100644 --- a/src/kernel/arch/i386/idt/idt.h +++ b/src/kernel/arch/i386/idt/idt.h @@ -5,9 +5,7 @@ #include "../vga/colors.h" #include "../pic/pic.h" -extern "C"{ - #include "../tty/kterm.h" -} +#include "../tty/kterm.h" extern "C" { diff --git a/src/kernel/arch/i386/idt/idt.s b/src/kernel/arch/i386/idt/idt.s new file mode 100644 index 0000000..5e19912 --- /dev/null +++ b/src/kernel/arch/i386/idt/idt.s @@ -0,0 +1,6 @@ + +.globl idt_flush +idt_flush: + mov 4(%esp), %eax + lidt (%eax) + ret diff --git a/src/kernel/arch/i386/irq_table.s b/src/kernel/arch/i386/irq_table.s new file mode 100644 index 0000000..fac477d --- /dev/null +++ b/src/kernel/arch/i386/irq_table.s @@ -0,0 +1,138 @@ +.globl irq0 +irq0: + cli + push $0 + push $0 + jmp irq_common + +.globl irq1 +irq1: + cli + push $0 + push $1 + jmp irq_common + +.globl irq2 +irq2: + cli + push $0 + push $2 + jmp irq_common + +.globl irq3 +irq3: + cli + push $0 + push $3 + jmp irq_common + +.globl irq4 +irq4: + cli + push $0 + push $4 + jmp irq_common + +.globl irq5 +irq5: + cli + push $0 + push $5 + jmp irq_common + +.globl irq6 +irq6: + cli + push $0 + push $6 + jmp irq_common + +.globl irq7 +irq7: + cli + push $0 + push $7 + jmp irq_common + +.globl irq8 +irq8: + cli + push $0 + push $8 + jmp irq_common + +.globl irq9 +irq9: + cli + push $0 + push $9 + jmp irq_common + +.globl irq10 +irq10: + cli + push $0 + push $10 + jmp irq_common + +.globl irq11 +irq11: + cli + push $0 + push $11 + jmp irq_common + + +.globl irq12 +irq12: + cli + push $0 + push $12 + jmp irq_common + +.globl irq13 +irq13: + cli + push $0 + push $13 + jmp irq_common + +.globl irq14 +irq14: + cli + push $0 + push $14 + jmp irq_common + +.globl irq15 +irq15: + cli + push $0 + push $15 + jmp irq_common + +irq_common: + pusha + + mov %ds, %ax + push %eax + + mov $0x10, %ax + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + call irq_handler + + pop %eax + + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + popa + add $8, %esp # cleans push error and irs code + sti + iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP diff --git a/src/kernel/arch/i386/irs_table.s b/src/kernel/arch/i386/irs_table.s new file mode 100644 index 0000000..8e7c6de --- /dev/null +++ b/src/kernel/arch/i386/irs_table.s @@ -0,0 +1,256 @@ +/* +* Interupt handlers +*/ + +.globl irs0 +irs0: + cli + push $0 + push $0 + jmp irs_common + +.globl irs1 +irs1: + cli + push $0 + push $1 + jmp irs_common + +.globl irs2 +irs2: + cli + push $0 + push $2 + jmp irs_common + +.globl irs3 +irs3: + cli + push $0 + push $3 + jmp irs_common + +.globl irs4 +irs4: + cli + push $0 + push $4 + jmp irs_common + +.globl irs5 +irs5: + cli + push $0 + push $5 + jmp irs_common + +.globl irs6 +irs6: + cli + push $0 + push $6 + jmp irs_common + +.globl irs7 +irs7: + cli + push $0 + push $7 + jmp irs_common + +.globl irs8 +irs8: + cli + push $0 + push $8 + jmp irs_common + +.globl irs9 +irs9: + cli + push $0 + push $9 + jmp irs_common + +.globl irs10 +irs10: + cli + push $0 + push $10 + jmp irs_common + +.globl irs11 +irs11: + cli + push $0 + push $11 + jmp irs_common + +.globl irs12 +irs12: + cli + push $0 + push $12 + jmp irs_common + +.globl irs13 +irs13: + cli + push $13 + jmp irs_common + +.globl irs14 +irs14: + cli + push $0 + push $14 + jmp irs_common + +.globl irs15 +irs15: + cli + push $0 + push $15 + jmp irs_common + +.globl irs16 +irs16: + cli + push $0 + push $16 + jmp irs_common + +.globl irs17 +irs17: + cli + push $0 + push $17 + jmp irs_common + +.globl irs18 +irs18: + cli + push $0 + push $18 + jmp irs_common + +.globl irs19 +irs19: + cli + push $0 + push $19 + jmp irs_common + +.globl irs20 +irs20: + cli + push $0 + push $20 + jmp irs_common + +.globl irs21 +irs21: + cli + push $0 + push $21 + jmp irs_common + +.globl irs22 +irs22: + cli + push $0 + push $22 + jmp irs_common + +.globl irs23 +irs23: + cli + push $0 + push $23 + jmp irs_common + +.globl irs24 +irs24: + cli + push $0 + push $24 + jmp irs_common + +.globl irs25 +irs25: + cli + push $0 + push $25 + jmp irs_common + +.globl irs26 +irs26: + cli + push $0 + push $26 + jmp irs_common + +.globl irs27 +irs27: + cli + push $0 + push $27 + jmp irs_common + +.globl irs28 +irs28: + cli + push $0 + push $28 + jmp irs_common + +.globl irs29 +irs29: + cli + push $0 + push $29 + jmp irs_common + +.globl irs30 +irs30: + cli + push $0 + push $30 + jmp irs_common + +.globl irs31 +irs31: + cli + push $0 + push $31 + jmp irs_common + + +irs_common: + pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax + + + mov %ds, %ax + push %eax + + /* load the kernel data segment descriptor*/ + + mov $0x10, %ax + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + call irs_handler + + pop %eax + + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + + popa + add $8, %esp # cleans push error and irs code + sti + iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP diff --git a/src/kernel/arch/i386/paging.s b/src/kernel/arch/i386/paging.s new file mode 100644 index 0000000..fa25003 --- /dev/null +++ b/src/kernel/arch/i386/paging.s @@ -0,0 +1,20 @@ +.globl enablePaging +enablePaging: + push %ebp + mov %esp, %ebp + mov %cr0, %eax + or $0x80000000, %eax + mov %eax, %cr0 + mov %ebp, %esp + pop %ebp + ret + +.globl loadPageDirectory +loadPageDirectory: + push %ebp + mov %esp, %ebp + mov 8(%esp), %eax + mov %eax, %cr3 + mov %ebp, %esp + pop %ebp + ret diff --git a/src/kernel/arch/i386/tty/kterm.c b/src/kernel/arch/i386/tty/kterm.cpp similarity index 97% rename from src/kernel/arch/i386/tty/kterm.c rename to src/kernel/arch/i386/tty/kterm.cpp index f4bc957..94bc3f1 100644 --- a/src/kernel/arch/i386/tty/kterm.c +++ b/src/kernel/arch/i386/tty/kterm.cpp @@ -202,10 +202,8 @@ void printf ( const char *format, ...) { switch (c) { case 'd': - kterm_writestring("Not implemented!!"); - break; + case 'u': - break; case 'x': itoa(buf, c, *((int *) arg++)); diff --git a/src/kernel/arch/i386/tty/kterm.h b/src/kernel/arch/i386/tty/kterm.h index b43faa9..7d2ace6 100644 --- a/src/kernel/arch/i386/tty/kterm.h +++ b/src/kernel/arch/i386/tty/kterm.h @@ -7,8 +7,9 @@ #include "../vga/colors.h" #include "../../../io.h" - -#include "./../../../../libc/include/string.h" +extern "C"{ + #include "./../../../../libc/include/string.h" +} void kterm_init(); diff --git a/src/kernel/bootcheck.h b/src/kernel/bootcheck.h index 890c4f8..c7b7796 100644 --- a/src/kernel/bootcheck.h +++ b/src/kernel/bootcheck.h @@ -2,9 +2,7 @@ #include "bootloader/multiboot.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) -extern "C" { - #include "arch/i386/tty/kterm.h" -} +#include "arch/i386/tty/kterm.h" diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index a04f977..f3658b2 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -1,8 +1,7 @@ #include "kernel.h" -#include "arch/i386/gdt/gdtc.h" -extern "C" { +#include "memory/PageFrameAllocator.h" - void early_main(unsigned long magic, unsigned long addr){ + extern "C" void early_main(unsigned long magic, unsigned long addr){ /** initialize terminal interface */ kterm_init(); @@ -13,58 +12,13 @@ extern "C" { CheckMBT( (multiboot_info_t *) addr); - multiboot_info_t* mbt = (multiboot_info_t*) addr; - // Map the kernel - //initPhysicalMemoryManager(); - - // AAAAAH memory map, Yes please! /* Are mmap_* valid? */ if (CHECK_FLAG(mbt->flags, 6)){ - multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; - uint32_t memorySizeInBytes = 0; - uint32_t reservedMemoryInBytes = 0; + mapMultibootMemoryMap(mbt); - - printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", - (unsigned) mbt->mmap_addr, (unsigned) mbt->mmap_length); - - for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ - if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ - memorySizeInBytes += mmap->len; - } else { - reservedMemoryInBytes += mmap->len; - } - - - printf( - "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", - (unsigned) mmap->size, - (unsigned) (mmap->addr >> 32), - (unsigned) (mmap->addr & 0xffffffff), - (unsigned) (mmap->len >> 32), - (unsigned) (mmap->len & 0xffffffff), - (unsigned) mmap->type); - - } - uint32_t memorySizeInGiB = memorySizeInBytes / 1073741824; - - printf("Available Memory: 0x%x bytes, 0x%x GiB\n", memorySizeInBytes, memorySizeInGiB ); - printf("Reserved Memory: 0x%x bytes\n", reservedMemoryInBytes ); } - - - - //int cpu_model = get_model(); - //int local_apic = check_apic(); - //printf( "CPU Model: %x, Local APIC: %D\n", cpu_model, local_apic); - - - /* Setup Paging and memory Managment*/ - //MMU MemoryManagementUnit = MMU(); - //MemoryManagementUnit.enable(); // Warning: Causes triple page fault - //printf("Pages available: %9d\n", pmm_available()); /* Draw diagonal blue line */ if (CHECK_FLAG (mbt->flags, 12)){ @@ -76,7 +30,7 @@ extern "C" { } - void kernel_main (void) { + extern "C" void kernel_main (void) { init_serial(); @@ -88,4 +42,4 @@ extern "C" { } } -} + diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 445e8fa..bf2fdd9 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -1,19 +1,24 @@ -#pragma once -extern "C" { - #include "arch/i386/tty/kterm.h" +#pragma once +extern "C"{ + #include "../libc/include/string.h" } +#include "arch/i386/vga/VBE.h" +#include "arch/i386/tty/kterm.h" -#include "../libc/include/string.h" #include "./bootloader/multiboot.h" + #include "bootcheck.h" + +#include "arch/i386/gdt/gdtc.h" #include "arch/i386/idt/idt.h" #include "io.h" #include "time.h" #include "cpu.h" -#include "arch/i386/vga/VBE.h" -#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) +#include "serial.h" +#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) +#define PANIC(message) { return; } /* This needs to be moved! */ @@ -26,89 +31,3 @@ void delay(int t){ for(j=0;j<25000;j++) asm("NOP"); } - -class Test { - public: - Test(); - void printMe(); - ~Test(); -}; - -Test::Test(){ - kterm_writestring("Create a test object\n"); -}; - -void Test::printMe(){ - kterm_writestring("testObject.printMe()\n"); -} - -Test::~Test(){ - kterm_writestring("Destroy testObject! Bye bye\n"); -} - -#define PORT 0x3f8 -static int init_serial() { - outb(PORT + 1, 0x00); // Disable all interrupts - outb(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor) - outb(PORT + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud - outb(PORT + 1, 0x00); // (hi byte) - outb(PORT + 3, 0x03); // 8 bits, no parity, one stop bit - outb(PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold - outb(PORT + 4, 0x0B); // IRQs enabled, RTS/DSR set - outb(PORT + 4, 0x1E); // Set in loopback mode, test the serial chip - outb(PORT + 0, 0xAE); // Test serial chip (send byte 0xAE and check if serial returns same byte) - - // Check if serial is faulty (i.e: not same byte as sent) - if(inb(PORT + 0) != 0xAE) { - return 1; - } - - // If serial is not faulty set it in normal operation mode - // (not-loopback with IRQs enabled and OUT#1 and OUT#2 bits enabled) - outb(PORT + 4, 0x0F); - return 0; -} - -int is_transmit_empty() { - return inb(PORT + 5) & 0x20; -} - -void write_serial(char a) { - while (is_transmit_empty() == 0); - - outb(PORT,a); -} - -int serial_received() { - return inb(PORT + 5) & 1; -} - -char read_serial() { - while (serial_received() == 0); - - return inb(PORT); -} - -void print_serial(const char* string ){ - for(size_t i = 0; i < strlen(string); i ++){ - write_serial(string[i]); - } -} - -void test_serial(){ - /** Serial test **/ - kterm_writestring("Writing to COM1 serial port:"); - init_serial(); - write_serial('A'); - write_serial('B'); - write_serial('C'); - write_serial('D'); - write_serial('E'); - - char Character_received = read_serial(); - kterm_writestring("\n"); - kterm_writestring("received from COM 1: \n"); - kterm_put(Character_received); - - kterm_writestring("\n"); -} diff --git a/src/kernel/memory/PageFramAllocator.cpp b/src/kernel/memory/PageFramAllocator.cpp deleted file mode 100644 index b690689..0000000 --- a/src/kernel/memory/PageFramAllocator.cpp +++ /dev/null @@ -1 +0,0 @@ -#include "PageFrameAllocator.h" diff --git a/src/kernel/memory/PageFrameAllocator.cpp b/src/kernel/memory/PageFrameAllocator.cpp new file mode 100644 index 0000000..f34c282 --- /dev/null +++ b/src/kernel/memory/PageFrameAllocator.cpp @@ -0,0 +1,38 @@ +#include "PageFrameAllocator.h" + + +MemoryInfo memInfo {}; +void mapMultibootMemoryMap( multiboot_info_t *mbt){ + printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", + (unsigned) mbt->mmap_addr, (unsigned) mbt->mmap_length); + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; + + for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + + if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ + memInfo.memorySizeInBytes += mmap->len; + } else { + memInfo.reservedMemoryInBytes += mmap->len; + } + + print_Multiboot_memory_Map(mmap); + + } + uint32_t memorySizeInGiB = memInfo.memorySizeInBytes / 1073741824; + + printf("Available Memory: 0x%x bytes, 0x%x GiB\n", memInfo.memorySizeInBytes, memorySizeInGiB ); + printf("Reserved Memory: 0x%x bytes\n", memInfo.reservedMemoryInBytes ); + +} + +void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap){ + printf( + "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", + (unsigned) mmap->size, + (unsigned) (mmap->addr >> 32), + (unsigned) (mmap->addr & 0xffffffff), + (unsigned) (mmap->len >> 32), + (unsigned) (mmap->len & 0xffffffff), + (unsigned) mmap->type + ); +} \ No newline at end of file diff --git a/src/kernel/memory/PageFrameAllocator.h b/src/kernel/memory/PageFrameAllocator.h index 56d4871..2b19180 100644 --- a/src/kernel/memory/PageFrameAllocator.h +++ b/src/kernel/memory/PageFrameAllocator.h @@ -1,8 +1,20 @@ #pragma once -#include +#include "../arch/i386/tty/kterm.h" +#include +#include "../bootloader/multiboot.h" + +struct MemoryInfo{ + uint32_t memorySizeInBytes = 0; + uint32_t reservedMemoryInBytes = 0; +}; extern void *kernel_begin; extern void *kernel_end; + + + +void print_Multiboot_memory_Map(multiboot_memory_map_t*); +void mapMultibootMemoryMap(multiboot_info_t*); \ No newline at end of file diff --git a/src/kernel/serial.h b/src/kernel/serial.h new file mode 100644 index 0000000..b14db96 --- /dev/null +++ b/src/kernel/serial.h @@ -0,0 +1,70 @@ +#pragma once + +#include "arch/i386/tty/kterm.h" +#include "io.h" +#define PORT 0x3f8 +static int init_serial() { + outb(PORT + 1, 0x00); // Disable all interrupts + outb(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor) + outb(PORT + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud + outb(PORT + 1, 0x00); // (hi byte) + outb(PORT + 3, 0x03); // 8 bits, no parity, one stop bit + outb(PORT + 2, 0xC7); // Enable FIFO, clear them, with 14-byte threshold + outb(PORT + 4, 0x0B); // IRQs enabled, RTS/DSR set + outb(PORT + 4, 0x1E); // Set in loopback mode, test the serial chip + outb(PORT + 0, 0xAE); // Test serial chip (send byte 0xAE and check if serial returns same byte) + + // Check if serial is faulty (i.e: not same byte as sent) + if(inb(PORT + 0) != 0xAE) { + return 1; + } + + // If serial is not faulty set it in normal operation mode + // (not-loopback with IRQs enabled and OUT#1 and OUT#2 bits enabled) + outb(PORT + 4, 0x0F); + return 0; +} + +int is_transmit_empty() { + return inb(PORT + 5) & 0x20; +} + +void write_serial(char a) { + while (is_transmit_empty() == 0); + + outb(PORT,a); +} + +int serial_received() { + return inb(PORT + 5) & 1; +} + +char read_serial() { + while (serial_received() == 0); + + return inb(PORT); +} + +void print_serial(const char* string ){ + for(size_t i = 0; i < strlen(string); i ++){ + write_serial(string[i]); + } +} + +void test_serial(){ + /** Serial test **/ + kterm_writestring("Writing to COM1 serial port:"); + init_serial(); + write_serial('A'); + write_serial('B'); + write_serial('C'); + write_serial('D'); + write_serial('E'); + + char Character_received = read_serial(); + kterm_writestring("\n"); + kterm_writestring("received from COM 1: \n"); + kterm_put(Character_received); + + kterm_writestring("\n"); +} -- 2.39.5 From 5fb55367caa61c14dbb3401522e53c45a2c008b5 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 6 Nov 2021 16:27:13 +0100 Subject: [PATCH 028/115] Implementation of simplistic physical memory manager --- Makefile | 6 +- src/kernel/bootcheck.h | 5 + src/kernel/kernel.cpp | 16 +-- src/kernel/kernel.h | 2 +- src/kernel/kstructures/bitmap.h | 40 +++++++ src/kernel/memory/PhysicalMemoryManager.cpp | 118 ++++++++++++++++++++ src/kernel/memory/PhysicalMemoryManager.h | 34 ++++++ src/libc/include/mem.h | 8 ++ 8 files changed, 218 insertions(+), 11 deletions(-) create mode 100644 src/kernel/kstructures/bitmap.h create mode 100644 src/kernel/memory/PhysicalMemoryManager.cpp create mode 100644 src/kernel/memory/PhysicalMemoryManager.h create mode 100644 src/libc/include/mem.h diff --git a/Makefile b/Makefile index e3010f6..3c7ccbe 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PageFrameAllocator.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -83,5 +83,5 @@ $(BUILD_DIR)/pic.o: $(BUILD_DIR)/string.o: $(CC) -c $(SRC_DIR)/libc/include/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 -$(BUILD_DIR)/PageFrameAllocator.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/PageFrameAllocator.cpp -o $(BUILD_DIR)/PageFrameAllocator.o $(CFLAGS) -fno-exceptions -fno-rtti +$(BUILD_DIR)/PhysicalMemoryManager.o: + $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/bootcheck.h b/src/kernel/bootcheck.h index c7b7796..6fbe49b 100644 --- a/src/kernel/bootcheck.h +++ b/src/kernel/bootcheck.h @@ -67,5 +67,10 @@ void CheckMBT ( multiboot_info_t* mbt ){ } + /* Draw diagonal blue line */ + if (CHECK_FLAG (mbt->flags, 12)){ + printf("Can draw!"); + } + } \ No newline at end of file diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index f3658b2..2a80224 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -1,6 +1,6 @@ #include "kernel.h" -#include "memory/PageFrameAllocator.h" - +#define GB4 524288 +#define GB2 262144 extern "C" void early_main(unsigned long magic, unsigned long addr){ /** initialize terminal interface */ kterm_init(); @@ -16,14 +16,16 @@ /* Are mmap_* valid? */ if (CHECK_FLAG(mbt->flags, 6)){ - mapMultibootMemoryMap(mbt); + PhysicalMemoryManager_initialise( mbt->mmap_addr, GB2/* Seriously dangerous hardcoded memory value*/); + PhysicalMemoryManager_initialise_available_regions(mbt->mmap_addr, mbt->mmap_addr + mbt->mmap_length); + PhysicalMemoryManager_deinitialise_kernel(); + extern uint8_t* kernel_begin; + extern uint8_t* kernel_end; + printf("Kernel MemoryMap:\n"); + printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); } - /* Draw diagonal blue line */ - if (CHECK_FLAG (mbt->flags, 12)){ - printf("Can draw!"); - } //setupGdt(); diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index bf2fdd9..2c61697 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -6,8 +6,8 @@ extern "C"{ #include "arch/i386/tty/kterm.h" #include "./bootloader/multiboot.h" - #include "bootcheck.h" +#include "memory/PhysicalMemoryManager.h" #include "arch/i386/gdt/gdtc.h" #include "arch/i386/idt/idt.h" diff --git a/src/kernel/kstructures/bitmap.h b/src/kernel/kstructures/bitmap.h new file mode 100644 index 0000000..e4487fe --- /dev/null +++ b/src/kernel/kstructures/bitmap.h @@ -0,0 +1,40 @@ +#pragma once +#include +#include + + +inline void bitmap_set( uint32_t* map , int index ) +{ + map[index/32] |= (1 << (index % 32)); +} + +inline void bitmap_unset(uint32_t* map , int index) +{ + map[index/32] &= ~(1 << (index % 32)); +} + +inline int bitmap_first_unset( uint32_t* map , int size) +{ + uint32_t rem_bits = size % 32; + for(uint32_t i = 0; i < size/32; i++) + { + if(map[i] != 0xFFFFFFFF){ + for(int j = 0; j < 32; j++){ + if(!(map[i] & (1<< j))){ + return (i*32) + j; + } + } + } + } + + if(rem_bits){ + for(uint32_t j = 0; j < rem_bits; j++){ + if(!(map[size/32] & (1 << j ))){ + return size + j; // Original author divided size by 32 and then multiplied it by 32 which is a net zero calculation ?!? + } + } + } + + return -1; + +} diff --git a/src/kernel/memory/PhysicalMemoryManager.cpp b/src/kernel/memory/PhysicalMemoryManager.cpp new file mode 100644 index 0000000..8e894ba --- /dev/null +++ b/src/kernel/memory/PhysicalMemoryManager.cpp @@ -0,0 +1,118 @@ +#include "PhysicalMemoryManager.h" + +size_t mem_size = 0; +int used_blocks = 0; +size_t max_blocks = 0; +uint32_t* pmmap = 0; +size_t pmmap_size = 0; + + +void PhysicalMemoryManager_initialise(uint32_t physicalmemorymap_address, size_t size ) +{ + mem_size = size; + max_blocks = KB_TO_BLOCKS(mem_size); + + used_blocks = max_blocks; + + pmmap = (uint32_t*) physicalmemorymap_address; + + if(max_blocks % BLOCKS_PER_WORD) + pmmap_size++; + + memset(pmmap, 0xFF, pmmap_size); +} + +void PhysicalMemoryManager_region_initialise(uint32_t base, size_t size) +{ + size_t blocks = size /BLOCK_SIZE; + uint32_t align = base / BLOCK_SIZE; + + for(size_t i = 0 ; i < blocks; i ++) + { + bitmap_unset(pmmap, align++); + used_blocks--; + } + + bitmap_set(pmmap, 0); + +} + +void PhysicalMemoryManager_region_deinitialise(uint32_t base, size_t size ) +{ + size_t blocks = size / BLOCK_SIZE; + uint32_t align = base / BLOCK_SIZE; + + for(size_t i = 0 ; i < blocks; i++ ) + { + bitmap_set(pmmap, align++); + used_blocks++; + } + + +} + +void PhysicalMemoryManager_initialise_available_regions(uint32_t mmap_, uint32_t mmap_end_) +{ + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*)mmap_; + multiboot_memory_map_t *mmap_end= (multiboot_memory_map_t*) mmap_end_; + + for(int i = 0; mmap < mmap_end ; mmap++, i++) + { + if(mmap->type == MULTIBOOT_MEMORY_AVAILABLE) + { + PhysicalMemoryManager_region_initialise((uint32_t) mmap->addr, (size_t) mmap->len); + } + } + +} + +void PhysicalMemoryManager_deinitialise_kernel() +{ + extern uint8_t kernel_begin; + extern uint8_t kernel_end; + + size_t kernel_size = (size_t) &kernel_end - (size_t) &kernel_begin; + + uint32_t pmmap_size_aligned = pmmap_size; + if(!IS_ALIGNED(pmmap_size_aligned, BLOCK_SIZE)) + { + pmmap_size_aligned = ALIGN(pmmap_size_aligned, BLOCK_SIZE); + } + + PhysicalMemoryManager_region_deinitialise((uint32_t) &kernel_begin, kernel_size); + PhysicalMemoryManager_region_deinitialise((uint32_t) &kernel_end, pmmap_size_aligned); + +} + +void* PhysicalMemoryManager_allocate_block() +{ + if(used_blocks - max_blocks <= 0) + { + return 0; + } + + int p_index = bitmap_first_unset(pmmap, p_index ); + + if(p_index == -1){ + return 0; + } + + bitmap_set(pmmap, p_index); + used_blocks++; + + return (void*) (BLOCK_SIZE * p_index); +} + +void PhysicalMemoryManager_free_block(void* p){ + if(p==0){ + return ; + } + + uint32_t p_addr = (uint32_t) p; + + int index = p_addr / BLOCK_SIZE; + bitmap_unset(pmmap, index); + + used_blocks--; + +} \ No newline at end of file diff --git a/src/kernel/memory/PhysicalMemoryManager.h b/src/kernel/memory/PhysicalMemoryManager.h new file mode 100644 index 0000000..3adc1eb --- /dev/null +++ b/src/kernel/memory/PhysicalMemoryManager.h @@ -0,0 +1,34 @@ +#pragma once + +#include "../bootloader/multiboot.h" +#include +#include +#include "../../libc/include/mem.h" +#include "../kstructures/bitmap.h" + + +#define BLOCK_SIZE 4092 +#define BLOCKS_PER_WORD 32 + +#define KB_TO_BLOCKS(x) (((x) * 1024 ) / BLOCK_SIZE) +#define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) +#define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) + + +extern void PhysicalMemoryManager_initialise(uint32_t, size_t); + +extern void PhysicalMemoryManager_region_initialise(uint32_t, size_t); +extern void PhysicalMemoryManager_region_deinitialise(uint32_t,size_t); + +extern void PhysicalMemoryManager_initialise_available_regions(uint32_t, uint32_t); +extern void PhysicalMemoryManager_deinitialise_kernel(); + +extern void* PhysicalMemoryManager_allocate_block(); +extern void PhysicalMemoryManager_free_block(void* p); + + +extern size_t mem_size; +extern int used_blocks; +extern size_t max_blocks; +extern uint32_t* pmmap; +extern size_t pmmap_size ; \ No newline at end of file diff --git a/src/libc/include/mem.h b/src/libc/include/mem.h new file mode 100644 index 0000000..62c4318 --- /dev/null +++ b/src/libc/include/mem.h @@ -0,0 +1,8 @@ +inline void* memset (void* ptr, int value, size_t num){ + for( int i = 0; i < num; i++ ) + { + int* data = (int*)ptr+ i; + *data = value; + } + return ptr; +} -- 2.39.5 From 32909aaed9b709a5692c79861b708cdd3942cf17 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 6 Nov 2021 21:56:42 +0100 Subject: [PATCH 029/115] GDT is running again --- Makefile | 6 +++++- src/kernel/arch/i386/boot.S | 2 +- src/kernel/arch/i386/gdt/gdtc.cpp | 10 +++++----- src/kernel/arch/i386/gdt/gdtc.h | 8 +++++--- src/kernel/kernel.cpp | 7 ++++--- 5 files changed, 20 insertions(+), 13 deletions(-) diff --git a/Makefile b/Makefile index 3c7ccbe..c287066 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -77,6 +77,10 @@ $(BUILD_DIR)/PageDirectory.o: $(BUILD_DIR)/idt.o: $(CPP) -c $(SRC_DIR)/kernel/arch/i386/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti +$(BUILD_DIR)/gdtc.o: + $(CPP) -c $(SRC_DIR)/kernel/arch/i386/gdt/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti + + $(BUILD_DIR)/pic.o: $(CPP) -c $(SRC_DIR)/kernel/arch/i386/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/arch/i386/boot.S b/src/kernel/arch/i386/boot.S index 5f5ba72..edfd9a4 100644 --- a/src/kernel/arch/i386/boot.S +++ b/src/kernel/arch/i386/boot.S @@ -46,7 +46,7 @@ _start: call early_main cli - + .global load_gdt load_gdt: lgdt gdt diff --git a/src/kernel/arch/i386/gdt/gdtc.cpp b/src/kernel/arch/i386/gdt/gdtc.cpp index 69611c2..d806112 100644 --- a/src/kernel/arch/i386/gdt/gdtc.cpp +++ b/src/kernel/arch/i386/gdt/gdtc.cpp @@ -2,6 +2,8 @@ #include "../tty/kterm.h" gdtEntry_t gdt[3]; +gdtSegmentPointer gdtPointer{}; + void gdtSetGate(int num, uint64_t base, uint64_t limit, uint8_t access, @@ -18,14 +20,12 @@ void gdtSetGate(int num, uint64_t base, uint64_t limit, uint8_t access, } void setupGdt(){ - - printf("setupGdt is called!"); gdtPointer.limit = (sizeof(gdtEntry_t) * 3) - 1; - gdtPointer.base = &gdt; + gdtPointer.base = (uint32_t) &gdt; gdtSetGate(0, 0, 0, 0, 0); gdtSetGate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); gdtSetGate(2, 0, 0xFFFFFFFF, 0x92, 0xCF); - - loadGdt(); + printf("call to load gdt\n"); + load_gdt(); } diff --git a/src/kernel/arch/i386/gdt/gdtc.h b/src/kernel/arch/i386/gdt/gdtc.h index 4e8140f..517a98a 100644 --- a/src/kernel/arch/i386/gdt/gdtc.h +++ b/src/kernel/arch/i386/gdt/gdtc.h @@ -10,11 +10,13 @@ typedef struct { uint8_t hBase; } gdtEntry_t; -struct { +struct gdtSegmentPointer { uint16_t limit; uint32_t base; -} gdtPointer; +}; -extern void loadGdt(); +extern gdtSegmentPointer gdtPointer; + +extern void load_gdt(); void setupGdt(); } \ No newline at end of file diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 2a80224..72e5622 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -26,17 +26,18 @@ printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); } - - //setupGdt(); + printf("Call to setupGdt!\n"); + setupGdt(); } extern "C" void kernel_main (void) { + printf("call to init serial\n"); init_serial(); - while (false){ + while (true){ //Read time indefinetely read_rtc(); printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); -- 2.39.5 From 3a87b742244ff6d9e2f078b06c6a8939233e90fd Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 16 Nov 2021 13:57:15 +0100 Subject: [PATCH 030/115] Renaming/Moving stuff into a different file structure --- Makefile | 16 +++--- src/kernel/{arch/i386 => }/boot.S | 49 +++---------------- src/kernel/bootcheck.h | 2 +- src/kernel/{arch/i386 => }/crti.s | 0 src/kernel/{arch/i386 => }/crtn.s | 0 src/kernel/{arch/i386 => }/gdt/gdt.s | 40 ++++++++++++++- src/kernel/{arch/i386 => }/gdt/gdtc.cpp | 0 src/kernel/{arch/i386 => }/gdt/gdtc.h | 0 src/kernel/{arch/i386 => }/idt/idt.cpp | 0 src/kernel/{arch/i386 => }/idt/idt.h | 0 src/kernel/{arch/i386 => }/idt/idt.s | 0 .../{arch/i386 => }/idt/scancodes/set1.h | 0 src/kernel/{arch/i386 => }/irq_table.s | 0 src/kernel/{arch/i386 => }/irs_table.s | 0 src/kernel/kernel.cpp | 3 ++ src/kernel/kernel.h | 8 +-- src/kernel/{arch/i386 => }/linker.ld | 0 src/kernel/memory/PageDirectory.cpp | 2 +- src/kernel/{arch/i386 => }/paging.s | 0 src/kernel/{arch/i386 => }/pic/pic.cpp | 0 src/kernel/{arch/i386 => }/pic/pic.h | 2 +- src/kernel/{arch/i386 => }/ports/serial.cpp | 0 src/kernel/{arch/i386 => }/ports/serial.h | 0 src/kernel/serial.h | 2 +- src/kernel/{arch/i386 => }/tty/kterm.cpp | 0 src/kernel/{arch/i386 => }/tty/kterm.h | 4 +- src/kernel/{arch/i386 => }/vga/VBE.h | 0 src/kernel/{arch/i386 => }/vga/colors.h | 0 28 files changed, 66 insertions(+), 62 deletions(-) rename src/kernel/{arch/i386 => }/boot.S (58%) rename src/kernel/{arch/i386 => }/crti.s (100%) rename src/kernel/{arch/i386 => }/crtn.s (100%) rename src/kernel/{arch/i386 => }/gdt/gdt.s (63%) rename src/kernel/{arch/i386 => }/gdt/gdtc.cpp (100%) rename src/kernel/{arch/i386 => }/gdt/gdtc.h (100%) rename src/kernel/{arch/i386 => }/idt/idt.cpp (100%) rename src/kernel/{arch/i386 => }/idt/idt.h (100%) rename src/kernel/{arch/i386 => }/idt/idt.s (100%) rename src/kernel/{arch/i386 => }/idt/scancodes/set1.h (100%) rename src/kernel/{arch/i386 => }/irq_table.s (100%) rename src/kernel/{arch/i386 => }/irs_table.s (100%) rename src/kernel/{arch/i386 => }/linker.ld (100%) rename src/kernel/{arch/i386 => }/paging.s (100%) rename src/kernel/{arch/i386 => }/pic/pic.cpp (100%) rename src/kernel/{arch/i386 => }/pic/pic.h (95%) rename src/kernel/{arch/i386 => }/ports/serial.cpp (100%) rename src/kernel/{arch/i386 => }/ports/serial.h (100%) rename src/kernel/{arch/i386 => }/tty/kterm.cpp (100%) rename src/kernel/{arch/i386 => }/tty/kterm.h (93%) rename src/kernel/{arch/i386 => }/vga/VBE.h (100%) rename src/kernel/{arch/i386 => }/vga/colors.h (100%) diff --git a/Makefile b/Makefile index c287066..d983334 100644 --- a/Makefile +++ b/Makefile @@ -43,7 +43,7 @@ test: build_kernel: $(OBJ_LINK_LIST) - $(CC) -T $(SRC_DIR)/kernel/arch/i386/linker.ld -o $(BUILD_DIR)/myos.bin \ + $(CC) -T $(SRC_DIR)/kernel//linker.ld -o $(BUILD_DIR)/myos.bin \ -ffreestanding -O2 -nostdlib $(OBJ_LINK_LIST) -lgcc build_x86_64: @@ -57,16 +57,16 @@ $(BUILD_DIR)/kernel.o: $(CPP) -c $(SRC_DIR)/kernel/kernel.cpp -o $(BUILD_DIR)/kernel.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/kterm.o: - $(CPP) -c $(SRC_DIR)/kernel/arch/i386/tty/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/tty/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/boot.o: - $(AS) $(SRC_DIR)/kernel/arch/i386/boot.S -o $(BUILD_DIR)/boot.o + $(AS) $(SRC_DIR)/kernel//boot.S -o $(BUILD_DIR)/boot.o $(BUILD_DIR)/crti.o: - $(AS) $(SRC_DIR)/kernel/arch/i386/crti.s -o $(BUILD_DIR)/crti.o + $(AS) $(SRC_DIR)/kernel/crti.s -o $(BUILD_DIR)/crti.o $(BUILD_DIR)/crtn.o: - $(AS) $(SRC_DIR)/kernel/arch/i386/crtn.s -o $(BUILD_DIR)/crtn.o + $(AS) $(SRC_DIR)/kernel/crtn.s -o $(BUILD_DIR)/crtn.o $(BUILD_DIR)/io.o: $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -75,14 +75,14 @@ $(BUILD_DIR)/PageDirectory.o: $(CPP) -c $(SRC_DIR)/kernel/memory/PageDirectory.cpp -o $(BUILD_DIR)/PageDirectory.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/idt.o: - $(CPP) -c $(SRC_DIR)/kernel/arch/i386/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/gdtc.o: - $(CPP) -c $(SRC_DIR)/kernel/arch/i386/gdt/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/gdt/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pic.o: - $(CPP) -c $(SRC_DIR)/kernel/arch/i386/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/string.o: $(CC) -c $(SRC_DIR)/libc/include/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 diff --git a/src/kernel/arch/i386/boot.S b/src/kernel/boot.S similarity index 58% rename from src/kernel/arch/i386/boot.S rename to src/kernel/boot.S index edfd9a4..f9ea085 100644 --- a/src/kernel/arch/i386/boot.S +++ b/src/kernel/boot.S @@ -21,10 +21,10 @@ stack_bottom: stack_top: .section .text -.include "./src/kernel/arch/i386/irs_table.s" -.include "./src/kernel/arch/i386/irq_table.s" -.include "./src/kernel/arch/i386/idt/idt.s" -.include "./src/kernel/arch/i386/paging.s" +.include "./src/kernel/irs_table.s" +.include "./src/kernel/irq_table.s" +.include "./src/kernel/idt/idt.s" +.include "./src/kernel/paging.s" .global _start @@ -46,44 +46,7 @@ _start: call early_main cli - .global load_gdt - load_gdt: - lgdt gdt - - # set the segment selecters - - movw $0x10, %ax - movw %ax, %ds - movw %ax, %es - movw %ax, %fs - movw %ax, %gs - movw %ax, %ss - ljmp $0x08, $flush - - flush: - - - #load idt - call init_idt - sti - - # Try enable A20 - # mov $0x2401, %ax - # int $0x15 - - - # enable protected mode - mov %cr0, %eax - or $1, %eax - mov %eax, %cr0 - - - call kernel_main - - - cli - 1: hlt - jmp 1b + -.include "./src/kernel/arch/i386/gdt/gdt.s" +.include "./src/kernel/gdt/gdt.s" diff --git a/src/kernel/bootcheck.h b/src/kernel/bootcheck.h index 6fbe49b..028eeba 100644 --- a/src/kernel/bootcheck.h +++ b/src/kernel/bootcheck.h @@ -2,7 +2,7 @@ #include "bootloader/multiboot.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) -#include "arch/i386/tty/kterm.h" +#include "tty/kterm.h" diff --git a/src/kernel/arch/i386/crti.s b/src/kernel/crti.s similarity index 100% rename from src/kernel/arch/i386/crti.s rename to src/kernel/crti.s diff --git a/src/kernel/arch/i386/crtn.s b/src/kernel/crtn.s similarity index 100% rename from src/kernel/arch/i386/crtn.s rename to src/kernel/crtn.s diff --git a/src/kernel/arch/i386/gdt/gdt.s b/src/kernel/gdt/gdt.s similarity index 63% rename from src/kernel/arch/i386/gdt/gdt.s rename to src/kernel/gdt/gdt.s index 066cd1f..25f7cd5 100644 --- a/src/kernel/arch/i386/gdt/gdt.s +++ b/src/kernel/gdt/gdt.s @@ -6,10 +6,48 @@ gdt: .att_syntax +.global load_gdt + load_gdt: + lgdt gdt + + # set the segment selecters + + movw $0x10, %ax + movw %ax, %ds + movw %ax, %es + movw %ax, %fs + movw %ax, %gs + movw %ax, %ss + ljmp $0x08, $flush + + flush: + + + #load idt + call init_idt + sti + + # Try enable A20 + # mov $0x2401, %ax + # int $0x15 + + + # enable protected mode + mov %cr0, %eax + or $1, %eax + mov %eax, %cr0 + + + call kernel_main + + + cli + 1: hlt + jmp 1b + .size _start, . - _start - /* * Create the GDT */ diff --git a/src/kernel/arch/i386/gdt/gdtc.cpp b/src/kernel/gdt/gdtc.cpp similarity index 100% rename from src/kernel/arch/i386/gdt/gdtc.cpp rename to src/kernel/gdt/gdtc.cpp diff --git a/src/kernel/arch/i386/gdt/gdtc.h b/src/kernel/gdt/gdtc.h similarity index 100% rename from src/kernel/arch/i386/gdt/gdtc.h rename to src/kernel/gdt/gdtc.h diff --git a/src/kernel/arch/i386/idt/idt.cpp b/src/kernel/idt/idt.cpp similarity index 100% rename from src/kernel/arch/i386/idt/idt.cpp rename to src/kernel/idt/idt.cpp diff --git a/src/kernel/arch/i386/idt/idt.h b/src/kernel/idt/idt.h similarity index 100% rename from src/kernel/arch/i386/idt/idt.h rename to src/kernel/idt/idt.h diff --git a/src/kernel/arch/i386/idt/idt.s b/src/kernel/idt/idt.s similarity index 100% rename from src/kernel/arch/i386/idt/idt.s rename to src/kernel/idt/idt.s diff --git a/src/kernel/arch/i386/idt/scancodes/set1.h b/src/kernel/idt/scancodes/set1.h similarity index 100% rename from src/kernel/arch/i386/idt/scancodes/set1.h rename to src/kernel/idt/scancodes/set1.h diff --git a/src/kernel/arch/i386/irq_table.s b/src/kernel/irq_table.s similarity index 100% rename from src/kernel/arch/i386/irq_table.s rename to src/kernel/irq_table.s diff --git a/src/kernel/arch/i386/irs_table.s b/src/kernel/irs_table.s similarity index 100% rename from src/kernel/arch/i386/irs_table.s rename to src/kernel/irs_table.s diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 72e5622..cb338d2 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -43,6 +43,9 @@ printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); delay(1000); } + + + } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 2c61697..f82f5da 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -2,15 +2,15 @@ extern "C"{ #include "../libc/include/string.h" } -#include "arch/i386/vga/VBE.h" -#include "arch/i386/tty/kterm.h" +#include "vga/VBE.h" +#include "tty/kterm.h" #include "./bootloader/multiboot.h" #include "bootcheck.h" #include "memory/PhysicalMemoryManager.h" -#include "arch/i386/gdt/gdtc.h" -#include "arch/i386/idt/idt.h" +#include "gdt/gdtc.h" +#include "idt/idt.h" #include "io.h" #include "time.h" diff --git a/src/kernel/arch/i386/linker.ld b/src/kernel/linker.ld similarity index 100% rename from src/kernel/arch/i386/linker.ld rename to src/kernel/linker.ld diff --git a/src/kernel/memory/PageDirectory.cpp b/src/kernel/memory/PageDirectory.cpp index ca7a6d5..f740680 100644 --- a/src/kernel/memory/PageDirectory.cpp +++ b/src/kernel/memory/PageDirectory.cpp @@ -4,7 +4,7 @@ void PageDirectory::enable(){ - + // https://wiki.osdev.org/Setting_Up_Paging //set each entry to not present int i; for(i = 0; i < 1024; i++) diff --git a/src/kernel/arch/i386/paging.s b/src/kernel/paging.s similarity index 100% rename from src/kernel/arch/i386/paging.s rename to src/kernel/paging.s diff --git a/src/kernel/arch/i386/pic/pic.cpp b/src/kernel/pic/pic.cpp similarity index 100% rename from src/kernel/arch/i386/pic/pic.cpp rename to src/kernel/pic/pic.cpp diff --git a/src/kernel/arch/i386/pic/pic.h b/src/kernel/pic/pic.h similarity index 95% rename from src/kernel/arch/i386/pic/pic.h rename to src/kernel/pic/pic.h index 3248187..9560cea 100644 --- a/src/kernel/arch/i386/pic/pic.h +++ b/src/kernel/pic/pic.h @@ -1,5 +1,5 @@ #pragma once -#include "../../../io.h" +#include "../io.h" #define PIC1 0x20 /* IO base address for master PIC */ #define PIC2 0xA0 /* IO base address for slave PIC */ diff --git a/src/kernel/arch/i386/ports/serial.cpp b/src/kernel/ports/serial.cpp similarity index 100% rename from src/kernel/arch/i386/ports/serial.cpp rename to src/kernel/ports/serial.cpp diff --git a/src/kernel/arch/i386/ports/serial.h b/src/kernel/ports/serial.h similarity index 100% rename from src/kernel/arch/i386/ports/serial.h rename to src/kernel/ports/serial.h diff --git a/src/kernel/serial.h b/src/kernel/serial.h index b14db96..ecc82db 100644 --- a/src/kernel/serial.h +++ b/src/kernel/serial.h @@ -1,6 +1,6 @@ #pragma once -#include "arch/i386/tty/kterm.h" +#include "tty/kterm.h" #include "io.h" #define PORT 0x3f8 static int init_serial() { diff --git a/src/kernel/arch/i386/tty/kterm.cpp b/src/kernel/tty/kterm.cpp similarity index 100% rename from src/kernel/arch/i386/tty/kterm.cpp rename to src/kernel/tty/kterm.cpp diff --git a/src/kernel/arch/i386/tty/kterm.h b/src/kernel/tty/kterm.h similarity index 93% rename from src/kernel/arch/i386/tty/kterm.h rename to src/kernel/tty/kterm.h index 7d2ace6..4f048d0 100644 --- a/src/kernel/arch/i386/tty/kterm.h +++ b/src/kernel/tty/kterm.h @@ -5,10 +5,10 @@ #include #include "../vga/colors.h" -#include "../../../io.h" +#include "../io.h" extern "C"{ - #include "./../../../../libc/include/string.h" + #include "./../../libc/include/string.h" } void kterm_init(); diff --git a/src/kernel/arch/i386/vga/VBE.h b/src/kernel/vga/VBE.h similarity index 100% rename from src/kernel/arch/i386/vga/VBE.h rename to src/kernel/vga/VBE.h diff --git a/src/kernel/arch/i386/vga/colors.h b/src/kernel/vga/colors.h similarity index 100% rename from src/kernel/arch/i386/vga/colors.h rename to src/kernel/vga/colors.h -- 2.39.5 From 88c519658649edcd647eb30917a57b12e73d7591 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 16 Nov 2021 21:17:49 +0100 Subject: [PATCH 031/115] Rewritten GDT logic --- src/kernel/boot.S | 26 ++++++++++++++ src/kernel/gdt/gdt.s | 74 +++++---------------------------------- src/kernel/gdt/gdtc.cpp | 76 ++++++++++++++++++++++++++++------------- src/kernel/gdt/gdtc.h | 39 ++++++++++++--------- src/kernel/kernel.cpp | 3 +- 5 files changed, 111 insertions(+), 107 deletions(-) diff --git a/src/kernel/boot.S b/src/kernel/boot.S index f9ea085..0c79b10 100644 --- a/src/kernel/boot.S +++ b/src/kernel/boot.S @@ -50,3 +50,29 @@ _start: .include "./src/kernel/gdt/gdt.s" + + loadIDT: + #load idt + call init_idt + sti + + # Try enable A20 + # mov $0x2401, %ax + # int $0x15 + + + # enable protected mode + mov %cr0, %eax + or $1, %eax + mov %eax, %cr0 + + + call kernel_main + + + cli + 1: hlt + jmp 1b + + +.size _start, . - _start \ No newline at end of file diff --git a/src/kernel/gdt/gdt.s b/src/kernel/gdt/gdt.s index 25f7cd5..95859c2 100644 --- a/src/kernel/gdt/gdt.s +++ b/src/kernel/gdt/gdt.s @@ -1,75 +1,19 @@ -/* Tell processor to use our gdt*/ -gdt: - .word (gdt_end - gdt_start -1) # Size of the GDT in bytes minus 1 for math reasons - .int gdt_start # linear address of our GDT +.global LoadGlobalDescriptorTable - -.att_syntax + LoadGlobalDescriptorTable: + lgdt gdtDescriptor -.global load_gdt - load_gdt: - lgdt gdt - - # set the segment selecters - - movw $0x10, %ax + movw $16, %ax movw %ax, %ds movw %ax, %es movw %ax, %fs movw %ax, %gs movw %ax, %ss - ljmp $0x08, $flush - flush: - + jmp $8,$flush + + flush: + ret - #load idt - call init_idt - sti - - # Try enable A20 - # mov $0x2401, %ax - # int $0x15 + - - # enable protected mode - mov %cr0, %eax - or $1, %eax - mov %eax, %cr0 - - - call kernel_main - - - cli - 1: hlt - jmp 1b - - -.size _start, . - _start - -/* -* Create the GDT -*/ -.section .data -gdt_start: -gdt_null: -.long 0x0 -.long 0x0 - -gdt_kcode: -.word 0xFFFF # limit -.word 0x0 # base -.byte 0x0 # base -.byte 0b10011010 # 1st flags | type flags -.byte 0b11001111 # 2nd flags | limit -.byte 0x0 # base - -gdt_kdata: -.word 0xFFFF # limit -.word 0x0 # base -.byte 0x0 # base -.byte 0b10010010 # 1st flags | type flags -.byte 0b11001111 # 2nd flags | limit -.byte 0x0 # base -gdt_end: diff --git a/src/kernel/gdt/gdtc.cpp b/src/kernel/gdt/gdtc.cpp index d806112..f2624bf 100644 --- a/src/kernel/gdt/gdtc.cpp +++ b/src/kernel/gdt/gdtc.cpp @@ -1,31 +1,61 @@ #include "gdtc.h" #include "../tty/kterm.h" - -gdtEntry_t gdt[3]; -gdtSegmentPointer gdtPointer{}; + +#define NULL_SEGMENT 0 +#define KERNEL_CODE_SEGMENT 1 +#define KERNEL_DATA_SEGMENT 2 +#define USER_CODE_SEGMENT 3 +#define USER_DATA_SEGMENT 4 + +SegmentDescriptor GlobalDescriptorTable[5]; +GlobalDescriptorTableDescriptor gdtDescriptor; + +void add_descriptor(int which , unsigned long base, unsigned long limit, unsigned char access, unsigned char granularity ){ + GlobalDescriptorTable[which].base_low = (base & 0xFFFF ); + GlobalDescriptorTable[which].base_middle = (base >> 6) & 0xFF; + GlobalDescriptorTable[which].base_high = (base >> 24) & 0xFF; + + GlobalDescriptorTable[which].limit_low = (limit & 0xFFFF); + GlobalDescriptorTable[which].granularity = ((limit >> 16) & 0x0F); + + GlobalDescriptorTable[which].granularity |= (granularity & 0xF0); + GlobalDescriptorTable[which].access = access; - -void gdtSetGate(int num, uint64_t base, uint64_t limit, uint8_t access, - uint8_t gran){ - gdt[num].lBase = (base & 0xFFFF); - gdt[num].mBase = (base >> 16) & 0xFF; - gdt[num].hBase = (base >> 24) & 0xFF; - - gdt[num].lLimit = (limit & 0xFFFF); - gdt[num].granularity = ((limit >> 16) & 0x0F); - - gdt[num].granularity |= (gran & 0xF0); - gdt[num].access = access; } -void setupGdt(){ - gdtPointer.limit = (sizeof(gdtEntry_t) * 3) - 1; - gdtPointer.base = (uint32_t) &gdt; - gdtSetGate(0, 0, 0, 0, 0); - gdtSetGate(1, 0, 0xFFFFFFFF, 0x9A, 0xCF); - gdtSetGate(2, 0, 0xFFFFFFFF, 0x92, 0xCF); - printf("call to load gdt\n"); - load_gdt(); + + +void initGDT(){ + + // NULL segment + add_descriptor(NULL_SEGMENT, 0,0,0,0); + + // Kernel Code Segment + add_descriptor(KERNEL_CODE_SEGMENT, 0, 0xFFFFFFFF, 0x9A, 0xCF); + + // Kernel Data Segment + add_descriptor(KERNEL_DATA_SEGMENT, 0, 0xFFFFFFFF, 0x92, 0xCF); + + // User Code Segment + // TODO: + + // User Data Segement + // TODO: + + // init Gdt Descriptor + gdtDescriptor.limit = ((sizeof(SegmentDescriptor ) * 5 ) - 1); + gdtDescriptor.base = (unsigned int) &GlobalDescriptorTable; + + + + LoadGlobalDescriptorTable(); + + while (true) + asm volatile("hlt"); + + + + } diff --git a/src/kernel/gdt/gdtc.h b/src/kernel/gdt/gdtc.h index 517a98a..548bc5e 100644 --- a/src/kernel/gdt/gdtc.h +++ b/src/kernel/gdt/gdtc.h @@ -1,22 +1,27 @@ #include -extern "C"{ -typedef struct { - uint16_t lLimit; - uint16_t lBase; - uint8_t mBase; - uint8_t access; - uint8_t granularity; - uint8_t hBase; -} gdtEntry_t; -struct gdtSegmentPointer { - uint16_t limit; - uint32_t base; -}; +struct SegmentDescriptor { + unsigned short limit_low; + unsigned short base_low; + unsigned char base_middle; + unsigned char access; + unsigned char granularity; + unsigned char base_high; +}__attribute__((packed)); -extern gdtSegmentPointer gdtPointer; -extern void load_gdt(); -void setupGdt(); -} \ No newline at end of file +struct GlobalDescriptorTableDescriptor{ + unsigned short limit; + unsigned int base; +}__attribute__((packed)); + +extern SegmentDescriptor GlobalDescriptorTable[]; +extern GlobalDescriptorTableDescriptor gdtDescriptor; + + +void add_descriptor(int which , unsigned long base, unsigned long limit, unsigned char access, unsigned char granularity ); + + +extern "C" void LoadGlobalDescriptorTable(); +void initGDT(); diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index cb338d2..d30350d 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -26,8 +26,7 @@ printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); } - printf("Call to setupGdt!\n"); - setupGdt(); + initGDT(); } -- 2.39.5 From ba043ef31bfeb5352ad468acc239e1e46082e864 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 22 Nov 2021 20:01:12 +0100 Subject: [PATCH 032/115] Small improvements on Makefile, TODO.md has been renamed to features.md --- Makefile | 26 +++++++++++--------------- TODO.md => features.md | 14 +++++++------- todo.md | 0 3 files changed, 18 insertions(+), 22 deletions(-) rename TODO.md => features.md (80%) create mode 100644 todo.md diff --git a/Makefile b/Makefile index d983334..afa65c7 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -19,30 +19,26 @@ OBJ_LINK_LIST = $(CRTI_OBJ) $(CRTBEGIN_OBJ) $(OFILES) $(CRTEND_OBJ) $(CRTN_OBJ) INTERNAL_OBJS = $(CRTI_OBJ) $(OFILES) $(CRTN_OBJ) -all: clean build clean_up +all: clean build -build: build_kernel +build: build_kernel iso clean_iso: - if [[ -a isodir/* ]] ; then rm isodir/* -d ; fi - if [ -f barinkOS.iso ] ; then rm barinkOS.iso ; fi + if [[ -a isodir/boot ]] ; then rm root/boot -rd ; fi + if [ -f build/barinkOS.iso ] ; then rm build/barinkOS.iso ; fi -iso: clean_iso build - mkdir -p isodir/boot/grub - cp build/myos.bin isodir/boot/myos.bin - cp src/grub.cfg isodir/boot/grub/grub.cfg - grub-mkrescue -o barinkOS.iso isodir +iso: clean_iso clean build + mkdir -p root/boot/grub + cp build/myos.bin root/boot/myos.bin + cp src/grub.cfg root/boot/grub/grub.cfg + grub-mkrescue -o build/barinkOS.iso root -clean_up: - rm build/*.o - test: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial file:CON -vga std -monitor stdio -display gtk -m 2G -cpu core2duo + $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -monitor stdio -display gtk -m 2G -cpu core2duo build_kernel: $(OBJ_LINK_LIST) - $(CC) -T $(SRC_DIR)/kernel//linker.ld -o $(BUILD_DIR)/myos.bin \ -ffreestanding -O2 -nostdlib $(OBJ_LINK_LIST) -lgcc diff --git a/TODO.md b/features.md similarity index 80% rename from TODO.md rename to features.md index 5f9d63f..53b1cf0 100644 --- a/TODO.md +++ b/features.md @@ -12,7 +12,7 @@ Detect CPU speed \ Interrupt / exception system (API) \ - Plan your memory map (virtual, and physical) : decide where you want the data to be. \ + Plan your memory map (virtual, and physical) : decide where you want the data to be. \ The heap: allocating memory at runtime (malloc and free) is almost impossible to go without. \ Enable SIMD Extensions (SSE) @@ -23,13 +23,13 @@ ACPI support ( Or some other basic way to support shutdown, reboot and possibly hibernation ) \ ATAPI support \ Keyboard support ( P/S2 Keyboard) \ - Memory Management (MMU)\ - Preemptive multi tasking - Processes + Memory Management (MMU) + Preemptive multi tasking \ + Processes \ Threads Scheduling (SRV2 Unix OR Priority Based Round Robin) \ - System V ABI compliance (partially) - POSIX compliance (partially) + System V ABI compliance (partially) \ + POSIX compliance (partially) \ RPC - for interprocess communication \ Sync primitives - Semaphores, Mutexes, spinlocks et al. \ Basic Terminal \ @@ -37,4 +37,4 @@ Basic Window server/client \ ## Support for more filesystems if I like the challenge in writing these ... FAT Filesystem \ - EXT2 Filesystem \ + EXT2 Filesystem diff --git a/todo.md b/todo.md new file mode 100644 index 0000000..e69de29 -- 2.39.5 From 23ede25ed61a7f242b5d855e06eb002f6d07e2e5 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 22 Nov 2021 20:04:14 +0100 Subject: [PATCH 033/115] Small changes to reflect renaming in readme.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bba2564..ee97592 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,8 @@ screen. The terminal/screen has scrolling so the latest messages are visible on ________________________ ### Planning -[See TODO](TODO.md) - +[See TODO](todo.md) \ +[See Features](features.md) ________________________ ### Docs [Intro](docs/Intro.md) \ -- 2.39.5 From ec654143c6625e27c27ea812d581fb73cc7fa932 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 25 Nov 2021 22:05:16 +0100 Subject: [PATCH 034/115] Basic PCI Enumeration --- Makefile | 7 ++- src/kernel/gdt/gdtc.cpp | 4 -- src/kernel/io.cpp | 12 ++-- src/kernel/io.h | 8 +-- src/kernel/kernel.cpp | 81 ++++++++++++++++++++++++-- src/kernel/kernel.h | 2 + src/kernel/pci.cpp | 122 +++++++--------------------------------- src/kernel/pci.h | 55 +++--------------- 8 files changed, 120 insertions(+), 171 deletions(-) diff --git a/Makefile b/Makefile index afa65c7..c553ba1 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -36,7 +36,7 @@ iso: clean_iso clean build grub-mkrescue -o build/barinkOS.iso root test: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -monitor stdio -display gtk -m 2G -cpu core2duo + $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo build_kernel: $(OBJ_LINK_LIST) $(CC) -T $(SRC_DIR)/kernel//linker.ld -o $(BUILD_DIR)/myos.bin \ @@ -85,3 +85,6 @@ $(BUILD_DIR)/string.o: $(BUILD_DIR)/PhysicalMemoryManager.o: $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/pci.o: + $(CPP) -c $(SRC_DIR)/kernel/pci.cpp -o $(BUILD_DIR)/pci.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/gdt/gdtc.cpp b/src/kernel/gdt/gdtc.cpp index f2624bf..d02d0fd 100644 --- a/src/kernel/gdt/gdtc.cpp +++ b/src/kernel/gdt/gdtc.cpp @@ -52,10 +52,6 @@ void initGDT(){ LoadGlobalDescriptorTable(); - while (true) - asm volatile("hlt"); - - } diff --git a/src/kernel/io.cpp b/src/kernel/io.cpp index 8a0861c..80e16d3 100644 --- a/src/kernel/io.cpp +++ b/src/kernel/io.cpp @@ -12,9 +12,10 @@ unsigned short inw_p(unsigned short ){ // TODO: implement me! return 0; } -unsigned int inl(unsigned short ){ -// TODO: implement me! - return 0; +uint32_t inl( int port ){ + unsigned int data; + asm volatile ("inl %w1, %0": "=a" (data): "d" (port)); + return data; } unsigned int inl_p(unsigned short ){ // TODO: implement me! @@ -31,9 +32,12 @@ void outw(unsigned short , unsigned short ){ void outw_p(unsigned short , unsigned short ){ } -void outl(unsigned int , unsigned short ){ +void outl( int port , uint32_t data ){ + asm volatile ("outl %0, %1" :: "a" (data), "dn"(port)); } + + void outl_p(unsigned int , unsigned short ){ } diff --git a/src/kernel/io.h b/src/kernel/io.h index c7fd561..094d595 100644 --- a/src/kernel/io.h +++ b/src/kernel/io.h @@ -12,21 +12,17 @@ static inline uint8_t inb(uint16_t port) unsigned char inb_p(unsigned short port); unsigned short inw(unsigned short port); unsigned short inw_p(unsigned short port); -unsigned int inl(unsigned short port); +uint32_t inl( int port ); unsigned int inl_p(unsigned short port); static inline void outb(uint16_t port, uint8_t val) { asm volatile ( "outb %0, %1" : : "a"(val), "Nd"(port) ); - /* There's an outb %al, $imm8 encoding, for compile-time constant port numbers that fit in 8b. (N constraint). - * Wider immediate constants would be truncated at assemble-time (e.g. "i" constraint). - * The outb %al, %dx encoding is the only option for all other cases. - * %1 expands to %dx because port is a uint16_t. %w1 could be used if we had the port number a wider C type */ } void outb_p(unsigned char value, unsigned short port); void outw(unsigned short value, unsigned short port); void outw_p(unsigned short value, unsigned short port); -void outl(unsigned int value, unsigned short port); +void outl( int port , uint32_t data ); void outl_p(unsigned int value, unsigned short port); void insb(unsigned short port, void *addr, diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index d30350d..03654bf 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -1,15 +1,20 @@ #include "kernel.h" #define GB4 524288 #define GB2 262144 + +int memcmp( const void* ptr1, const void* ptr2, size_t num); + +extern "C" void kernel_main (void); + extern "C" void early_main(unsigned long magic, unsigned long addr){ - /** initialize terminal interface */ + /** initialize terminal interface */ kterm_init(); - + if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ printf("Invalid magic number: 0x%x\n", magic); return; } - + CheckMBT( (multiboot_info_t *) addr); multiboot_info_t* mbt = (multiboot_info_t*) addr; @@ -27,19 +32,83 @@ } initGDT(); + + + + kernel_main(); + } + + int memcmp( const void* ptr1, const void* ptr2, size_t num) + { + const unsigned char * cs = (const unsigned char*) ptr1; + const unsigned char * ct = (const unsigned char*) ptr2; + + + for (int i = 0 ; i < num ; i++, cs++, ct++ ){ + if( *cs < *ct){ + return -1; + } else if( *cs > *ct){ + return 1; + } + } + + return 0; - } extern "C" void kernel_main (void) { printf("call to init serial\n"); init_serial(); + print_serial("Serial port initialized!"); + + // Enumerate the PCI bus + + int devicesFound = 0; + // loop through all possible busses, devices and their functions; + for( int bus = 0 ; bus < 256 ; bus++) + { + + for(int device = 0; device < 32 ; device ++) + { + for ( int function = 0; function < 8; function++) + { + + uint64_t DeviceIdentify = ConfigReadWord(bus, device, function,0x0); + uint32_t VendorID = DeviceIdentify & 0xFFFF; + uint32_t DeviceID = DeviceIdentify >> 16; + + + + if( DeviceID != 0xFFFF){ + printf("bus: %d, device: %d, function %d \n"); + printf("Device found!\n"); + printf("DeviceID: 0x%x, VendorID: 0x%x\n", DeviceID, VendorID); + + uint32_t classcodes = ConfigReadWord(bus, device, function, 0x8); + uint32_t classData = classcodes >> 16; // We only care for the last 2 bytes! + uint32_t deviceClass = classData >> 8; + uint32_t subclass = classData & 0xFF; + + printf(" class: %d, subClass: %d\n\n", deviceClass, subclass); + devicesFound++; + + } + + + + } + + } + + } + + printf("Found %d devices!", devicesFound); while (true){ //Read time indefinetely - read_rtc(); - printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); + //read_rtc(); + //printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); delay(1000); } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index f82f5da..ff76ffa 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -16,6 +16,8 @@ extern "C"{ #include "time.h" #include "cpu.h" #include "serial.h" +#include "pci.h" + #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) #define PANIC(message) { return; } diff --git a/src/kernel/pci.cpp b/src/kernel/pci.cpp index 3f81c29..a579fbd 100644 --- a/src/kernel/pci.cpp +++ b/src/kernel/pci.cpp @@ -1,108 +1,28 @@ #include "pci.h" +#include "tty/kterm.h" +#define PCI_BUS_ADDR_SHIFT 16 +#define PCI_DEVICE_ADDR_SHIFT 11 +#define PCI_FUNCTION_ADDR_SHIFT 8 +#define PCI_ENABLE_ADDR_SHIFT 31 -uint16_t ConfigReadWord (uint8_t bus, uint8_t slot, uint8_t func, uint8_t offset){ + + +uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offset){ uint32_t address; - uint32_t lbus = (uint32_t) bus; - uint32_t lslot = (uint32_t) slot; - uint32_t lfunc = (uint32_t) func; - uint16_t tmp = 0; - /* Create configuration address as per Figure 1 */ - address = (uint32_t) ((lbus << 16) | (lslot << 11) | (lfunc << 8) | (offset & 0xFC) |((uint32_t) 0x80000000) ); - /*write out the address */ + address = (uint32_t) ( + ((uint32_t) 1 << PCI_ENABLE_ADDR_SHIFT) | + ((uint32_t)bus << PCI_BUS_ADDR_SHIFT) | + ((uint32_t)device << PCI_DEVICE_ADDR_SHIFT) | + ((uint32_t)func << PCI_FUNCTION_ADDR_SHIFT) | + offset ); + // printf("PCI address read 0x%x", address); + + + outl(CONFIG_ADDRESS, address); - /* read in the data */ - /* (offset & 2 ) * 8 ) = o will choosse the first word of the 32 bits register*/ - tmp = (uint16_t)((inl(CONFIG_DATA)) >> ((offset & 2) * 8) & 0xFFFF); - return (tmp); + + + return inl(CONFIG_DATA); } -uint16_t CheckVendor (uint8_t bus, uint8_t slot) { - uint16_t vendor, device; - /* - Try and read the first configuration register. Since there ar no - vendors that == 0xFFFF, it must be a non-existent device. - */ - if((vendor = ConfigReadWord(bus, slot, 0,0)) != 0xFFFF) { - device = ConfigReadWord(bus, slot, 0,2); - // Possible read more config values ... - } return (vendor); -} - -void checkDevice (uint8_t bus, uint8_t device ) { - uint8_t function = 0; - - uint16_t vendorID = CheckVendor(bus, device); - if (vendorID == 0xFFFF) { - return; - } - - checkFunction (bus, device, function ); - headerType = getHeaderType(bus, device, function ); - if( (headerType & 0x80) != 0) { - /* It is a multi-function device, so check remaining functions */ - for (function = 1; function < 8; function++){ - if (CheckVendor(bus, device)!= 0xFFFF){ - checkFunction(bus, device, function ); - } - } - } - -} - - -void checkFunction (uint8_t bus, uint8_t device, uint8_t function ){ - uint8_t baseClass; - uint8_t subClass; - uint8_t secondaryBus; - - baseClass = getBaseClass(bus, device, function); - subClass = getSubClass (bus, device, function ); - if ( (baseClass == 0x06) && (subClass == 0x04)){ - secondaryBus = getSecondaryBus(bus,device, function); - checkBus(secondaryBus); - } -} - - -// Brute-force scan -void checkAllBuses (){ - uint16_t bus; - uint8_t device; - - for(bus = 0; bus < 256; bus++){ - for(device = 0; device < 32; device++){ - checkDevice(bus,device); - } - } -} - -// Recursive scan -void checkBus (uint8_t bus){ - uint8_t device; - - for(device = 0; device < 32; device ++){ - checkDevice(bus,device); - } -} - -void checkAllBuses(){ - uint8_t function; - uint8_t bus; - - headerType = getHeaderType(0,0,0); - if ( (headerType & 0x80) == 0 ){ - /* Single PCI host controller */ - checkBus(0); - } else{ - /* Multiple PCI host controllers */ - for (function = 0; function < 8; function++){ - if( CheckVendor(0,0) != 0xFFFF) { - break; - } - bus = function; - checkBus(bus); - } - } - -} \ No newline at end of file diff --git a/src/kernel/pci.h b/src/kernel/pci.h index 93b15ce..7f5ed47 100644 --- a/src/kernel/pci.h +++ b/src/kernel/pci.h @@ -5,54 +5,13 @@ #define CONFIG_ADDRESS 0xCF8 // Configuration adress that is to be accessed #define CONFIG_DATA 0xCFC // Will do the actual configuration operation -/* -CONFIG_ADDRESS - -32 bit register - -bit 31 Enable bit (Should CONFIG_DATA be translatedc to configuration cycles) -bit 30 - 24 Reserved -bit 23 - 16 Bus Number (Choose a specific PCI BUS) -bit 15 - 11 Device Number (Selects specific device one the pci bus) -bit 10 - 8 Function Number (Selects a specific function in a device) -bit 7 - 0 Register Offset (Offset in the configuration space of 256 Bytes ) NOTE: lowest two bits will always be zero - -*/ +uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offset); -/* -PCI Device structure +inline uint16_t getVendorID(uint8_t bus, uint8_t device, uint8_t function ){ + return ConfigReadWord ( bus , device, function, 0); +} -Register offset bits 31-24 bits 23-16 bits 15-8 bits 7-0 -00 00 Device ID <---- Vendor ID <------- -01 04 Status <---- Command <------- -02 08 Class code Sub class Prog IF Revision ID -03 0C BIST Header Type Ltncy Timer Cache line Size -04 10 Base address #0 (BAR0) -05 14 Base address #1 (BAR1) -06 18 Base address #2 (BAR2) -07 1C Base address #3 (BAR3) -08 20 Base address #4 (BAR4) -09 24 Base address #5 (BAR5) -0A 28 Cardbus CIS Pointer -0B 2C Subsystem ID <------ Subsystem Vendor ID <------- -0C 30 Expansion ROM base address -0D 34 Reserved <------- Capabilities Pointer <------ -0E 38 Reserved <------- <-------- <-------- -0F 3C Max ltncy Min Grant Interrupt PIN Interrupt Line - -*/ - - -/* -The idea for now is to support the minimal things necessary to find ATA supported drives - */ - - -// Lets write some boiler plate configuration code - -uint16_t ConfigReadWord (uint8_t bus, uint8_t slot, uint8_t func, uint8_t offset); - -uint16_t CheckVendor (uint8_t bus, uint8_t slot); - -void checkDevice (uint8_t bus, uint8_t device ); \ No newline at end of file +inline uint16_t getDeviceID(uint8_t bus, uint8_t device, uint8_t function ){ + return ConfigReadWord(bus, device, function , 16); +} -- 2.39.5 From 5089da5e9e01cc217f8c5533d649296543285215 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 28 Nov 2021 16:46:16 +0100 Subject: [PATCH 035/115] PCI: Improved syntax of PCI enumeration, Added a PCI information storage class and structs --- Makefile | 19 +++- src/kernel/kernel.cpp | 47 +--------- src/kernel/kernel.h | 1 + src/kernel/pci.cpp | 177 ++++++++++++++++++++++++++++++++++- src/kernel/pci.h | 30 ++++-- src/kernel/pci/pciDevice.cpp | 7 ++ src/kernel/pci/pciDevice.h | 36 +++++++ 7 files changed, 264 insertions(+), 53 deletions(-) create mode 100644 src/kernel/pci/pciDevice.cpp create mode 100644 src/kernel/pci/pciDevice.h diff --git a/Makefile b/Makefile index c553ba1..365f8be 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,21 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES = \ +$(BUILD_DIR)/boot.o \ +$(BUILD_DIR)/kterm.o \ +$(BUILD_DIR)/kernel.o \ +$(BUILD_DIR)/PhysicalMemoryManager.o \ +$(BUILD_DIR)/io.o \ +$(BUILD_DIR)/PageDirectory.o \ +$(BUILD_DIR)/gdtc.o \ +$(BUILD_DIR)/idt.o \ +$(BUILD_DIR)/pci.o \ +$(BUILD_DIR)/pic.o \ +$(BUILD_DIR)/string.o \ +$(BUILD_DIR)/pcidevice.o + + SRC_DIR = src BUILD_DIR = build @@ -88,3 +102,6 @@ $(BUILD_DIR)/PhysicalMemoryManager.o: $(BUILD_DIR)/pci.o: $(CPP) -c $(SRC_DIR)/kernel/pci.cpp -o $(BUILD_DIR)/pci.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/pcidevice.o: + $(CPP) -c $(SRC_DIR)/kernel/pci/pciDevice.cpp -o $(BUILD_DIR)/pcidevice.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 03654bf..8157292 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -62,53 +62,16 @@ extern "C" void kernel_main (void); init_serial(); print_serial("Serial port initialized!"); + + // Enumerate the PCI bus - - int devicesFound = 0; - // loop through all possible busses, devices and their functions; - for( int bus = 0 ; bus < 256 ; bus++) - { - - for(int device = 0; device < 32 ; device ++) - { - for ( int function = 0; function < 8; function++) - { - - uint64_t DeviceIdentify = ConfigReadWord(bus, device, function,0x0); - uint32_t VendorID = DeviceIdentify & 0xFFFF; - uint32_t DeviceID = DeviceIdentify >> 16; + PCI_Enumerate(); - - if( DeviceID != 0xFFFF){ - printf("bus: %d, device: %d, function %d \n"); - printf("Device found!\n"); - printf("DeviceID: 0x%x, VendorID: 0x%x\n", DeviceID, VendorID); - - uint32_t classcodes = ConfigReadWord(bus, device, function, 0x8); - uint32_t classData = classcodes >> 16; // We only care for the last 2 bytes! - uint32_t deviceClass = classData >> 8; - uint32_t subclass = classData & 0xFF; - - printf(" class: %d, subClass: %d\n\n", deviceClass, subclass); - devicesFound++; - - } - - - - } - - } - - } - - printf("Found %d devices!", devicesFound); - while (true){ //Read time indefinetely - //read_rtc(); - //printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); + read_rtc(); + printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); delay(1000); } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index ff76ffa..cb9755a 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -19,6 +19,7 @@ extern "C"{ #include "pci.h" + #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) #define PANIC(message) { return; } diff --git a/src/kernel/pci.cpp b/src/kernel/pci.cpp index a579fbd..e2d213c 100644 --- a/src/kernel/pci.cpp +++ b/src/kernel/pci.cpp @@ -1,11 +1,119 @@ #include "pci.h" -#include "tty/kterm.h" + #define PCI_BUS_ADDR_SHIFT 16 #define PCI_DEVICE_ADDR_SHIFT 11 #define PCI_FUNCTION_ADDR_SHIFT 8 #define PCI_ENABLE_ADDR_SHIFT 31 +const char* GetClassCodeName (uint64_t ClassCode ) { + + switch (ClassCode) + { + case 0x0 : + return "Unclassified"; + break; + case 0x1: + return "Mass Storage Controller"; + break; + + case 0x2: + return "Network Controller"; + break; + + case 0x3: + return "Display Controller"; + break; + + case 0x4: + return "Multimedia Controller"; + break; + + case 0x5: + return "Memory Controller"; + break; + + case 0x6: + return "Bridge"; + break; + + case 0x7 : + return "Simple Communication Controller"; + break; + + case 0x8: + return "Base System Peripheral"; + break; + + case 0x9: + return "Input Device Controller"; + break; + + case 0xA: + return "Docking station"; + break; + case 0xB: + return "Processor"; + break; + + case 0xC: + return "Serial Bus Controller"; + break; + + case 0xD: + return "Wireless Controller"; + break; + + case 0xE: + return "Intelligent Controller"; + break; + + case 0xF: + return "Satellite Communication Controller"; + break; + + case 0x10: + return "Encryption Controller"; + break; + + case 0x11: + return "Signal Processing Controller"; + break; + + case 0x12: + return "Processing Accelerator"; + break; + + case 0x13: + return "Non-Essential Instrumentation"; + break; + + default: + return "Unknown"; + break; + } + +} + +const char* getVendor( uint64_t VendorID){ + switch (VendorID) + { + case 0x8086: + return "Intel Corporation"; + break; + + default: + return "Vendor Unkown"; + break; + } +} + + + +uint32_t ConfigReadWord ( PCIBusAddress& PCIDeviceAddress , uint8_t offset){ + outl(CONFIG_ADDRESS , PCIDeviceAddress.getAddress() | offset ); + return inl(CONFIG_DATA); +} uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offset){ uint32_t address; @@ -16,9 +124,6 @@ uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offs ((uint32_t)device << PCI_DEVICE_ADDR_SHIFT) | ((uint32_t)func << PCI_FUNCTION_ADDR_SHIFT) | offset ); - // printf("PCI address read 0x%x", address); - - outl(CONFIG_ADDRESS, address); @@ -26,3 +131,67 @@ uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offs return inl(CONFIG_DATA); } + + +uint8_t GetHeaderType( PCIBusAddress& PCIDeviceAddress ){ + uint32_t header_information = ConfigReadWord(PCIDeviceAddress , 0xC); + return (uint8_t) ( + (header_information >> 16) //Get higher half + & 0x00FF ); // Select the last two bytes +} + +uint16_t GetClassCodes( PCIBusAddress& PCIDeviceAddress ){ + uint32_t classcodes = ConfigReadWord(PCIDeviceAddress, 0x8); + return (uint16_t)((uint32_t)classcodes >> 16); + +} + +void PCI_Enumerate(){ + int devicesFound = 0; + // loop through all possible busses, devices and their functions; + for( int bus = 0 ; bus < 256 ; bus++) + { + + for(int device = 0; device < 32 ; device ++) + { + + + int function = 0; + + //uint64_t DeviceIdentify = ConfigReadWord(bus, device, function,0x0); + uint32_t VendorID = GetDevice(bus, device, function) & 0xFFFF; + uint32_t DeviceID = GetDevice(bus, device, function) >> 16; + + + + if( DeviceID != 0xFFFF){ + printf("Device found!\n"); + printf("Bus: %d, Device: %d, function: %d \n", bus, device, function); + printf("DeviceID: 0x%x, VendorID: %s\n", DeviceID, getVendor(VendorID) ); + + // iterate over the functions if it is a multi function device! + if( false ){ + for ( function ++ ; function < 8; function++) + { + + } + } + + PCIBusAddress busAddress = + PCIBusAddress{bus, device, function }; + + uint8_t header_type = GetHeaderType(busAddress); + printf( "Header type: 0x%x\n", header_type); + + uint16_t deviceClasses = GetClassCodes(busAddress); + printf(" class: %s, subClass: %d\n\n", + (deviceClasses >>8) > 0x13 ? "Unknown": GetClassCodeName((deviceClasses >>8)), deviceClasses & 0xFF); + + devicesFound++; + } + } + + } + + printf("Found %d PCI devices!\n", devicesFound); +} diff --git a/src/kernel/pci.h b/src/kernel/pci.h index 7f5ed47..137f950 100644 --- a/src/kernel/pci.h +++ b/src/kernel/pci.h @@ -1,17 +1,35 @@ #pragma once #include #include "io.h" +#include "tty/kterm.h" +#include "pci/pciDevice.h" + // Configuration Space Access Mechanism #1 #define CONFIG_ADDRESS 0xCF8 // Configuration adress that is to be accessed #define CONFIG_DATA 0xCFC // Will do the actual configuration operation +extern const char* ClassCodeTable [0x13]; + + + +// Note: this could be used to make the api for receiving PCI class codes a bit +// nicer. +struct ClassCodes { + uint8_t ClassCode; + uint8_t DeviceClass; +}__attribute__((packed)); + uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offset); +uint32_t ConfigReadWord ( PCIBusAddress& PCIDeviceAddress , uint8_t offset); + inline uint64_t GetDevice (int bus, int device, int function ){ + return ConfigReadWord(bus, device, function,0x0); + } -inline uint16_t getVendorID(uint8_t bus, uint8_t device, uint8_t function ){ - return ConfigReadWord ( bus , device, function, 0); -} +uint8_t GetHeaderType( PCIBusAddress& PCIDeviceAddress ); -inline uint16_t getDeviceID(uint8_t bus, uint8_t device, uint8_t function ){ - return ConfigReadWord(bus, device, function , 16); -} +uint16_t GetClassCodes( PCIBusAddress& PICDeviceAddress ); +const char* getVendor( uint64_t VendorID); +const char* GetClassCodeName (uint64_t ClassCode ); + +void PCI_Enumerate(); \ No newline at end of file diff --git a/src/kernel/pci/pciDevice.cpp b/src/kernel/pci/pciDevice.cpp new file mode 100644 index 0000000..e4507fb --- /dev/null +++ b/src/kernel/pci/pciDevice.cpp @@ -0,0 +1,7 @@ + #include "pciDevice.h" + +// NOTE: we would really like to return a pointer +// to the newly created PCIBusAddress struct; + PCIBusAddress const PCIDevice::PCIAddress(){ + return PCIBusAddress{bus ,device, function}; + } \ No newline at end of file diff --git a/src/kernel/pci/pciDevice.h b/src/kernel/pci/pciDevice.h new file mode 100644 index 0000000..adc52f0 --- /dev/null +++ b/src/kernel/pci/pciDevice.h @@ -0,0 +1,36 @@ +#pragma once +#include + +/* +* PCI devices API +*/ +struct PCIBusAddress{ + + int bus ; + int device ; + int function[8]; + + + uint32_t getAddress( int deviceFunction = 0 ){ + return ((uint32_t) 1 << 31) | + ((uint32_t) bus << 16) | + ((uint32_t) device << 11)| + ((uint32_t) function[deviceFunction] << 8) | + 0x0000; + + }; +}; + +class PCIDevice { + public : + PCIDevice (PCIBusAddress* , int ); + ~PCIDevice(); + PCIBusAddress const PCIAddress(); + + private: + int bus; + int device; + int function; + int headerType; + +}; -- 2.39.5 From 08b97af86318a9f53397154aedbcf6be7a9e149c Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 28 Nov 2021 21:07:05 +0100 Subject: [PATCH 036/115] PCI: enumeration code cleanup --- src/kernel/pci.cpp | 105 +++++++++++++++++++++++++++---------- src/kernel/pci/pciDevice.h | 26 +++++++-- 2 files changed, 99 insertions(+), 32 deletions(-) diff --git a/src/kernel/pci.cpp b/src/kernel/pci.cpp index e2d213c..ae5c62c 100644 --- a/src/kernel/pci.cpp +++ b/src/kernel/pci.cpp @@ -95,17 +95,30 @@ const char* GetClassCodeName (uint64_t ClassCode ) { } -const char* getVendor( uint64_t VendorID){ +const char* getVendor( uint32_t VendorID){ switch (VendorID) { - case 0x8086: - return "Intel Corporation"; - break; - - default: - return "Vendor Unkown"; - break; + case 0x8086: + return "Intel Corporation"; + break; + + case 0x10DE: + return "NVIDIA Corporation"; + break; + + case 0x1022: + return "Advanced Micro Devices, Inc.[AMD]"; + break; + + case 0x1002: + return "Advanced Micor Devices, Inc.[AMD/ATI]"; + break; + + default: + return "Vendor Unkown"; + break; } + } @@ -136,8 +149,9 @@ uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offs uint8_t GetHeaderType( PCIBusAddress& PCIDeviceAddress ){ uint32_t header_information = ConfigReadWord(PCIDeviceAddress , 0xC); return (uint8_t) ( - (header_information >> 16) //Get higher half - & 0x00FF ); // Select the last two bytes + ((header_information >> 16) //Get higher half + & 0x00FF) // Select the last two bytes + & 0x7F ); // Mask bit 7 as it indicates if the device is a mulit function device! } uint16_t GetClassCodes( PCIBusAddress& PCIDeviceAddress ){ @@ -146,6 +160,39 @@ uint16_t GetClassCodes( PCIBusAddress& PCIDeviceAddress ){ } +bool IsMultiFunctionDevice(PCIBusAddress& PCIDeviceAddress){ + uint32_t header_information = ConfigReadWord(PCIDeviceAddress, 0xC); + return (((header_information>>16) + & 0x80) + >> 7 ); +} + + + + +void PrintPCIDeviceInfo (PCIBusAddress& PCIDeviceAddress) +{ + uint32_t DeviceID = (GetDevice(PCIDeviceAddress.bus, PCIDeviceAddress.device, PCIDeviceAddress.function) >> 16); + uint32_t VendorID = GetDevice(PCIDeviceAddress.bus, PCIDeviceAddress.device, PCIDeviceAddress.function) & 0xFFFF; + printf("Device found!\n"); + printf("Bus: %d, Device: %d, function: %d \n", PCIDeviceAddress.bus, PCIDeviceAddress.device, PCIDeviceAddress.function); + printf("DeviceID: 0x%x, Vendor: %s\n", + DeviceID + , getVendor(VendorID) ); + + + + + uint8_t header_type = GetHeaderType(PCIDeviceAddress); + printf( "Header type: 0x%x\n", header_type); + + uint16_t deviceClasses = GetClassCodes(PCIDeviceAddress); + printf("class: %s, subClass: %d\n\n", GetClassCodeName((deviceClasses >>8)), deviceClasses & 0xFF); + +} + + + void PCI_Enumerate(){ int devicesFound = 0; // loop through all possible busses, devices and their functions; @@ -159,33 +206,35 @@ void PCI_Enumerate(){ int function = 0; //uint64_t DeviceIdentify = ConfigReadWord(bus, device, function,0x0); - uint32_t VendorID = GetDevice(bus, device, function) & 0xFFFF; uint32_t DeviceID = GetDevice(bus, device, function) >> 16; if( DeviceID != 0xFFFF){ - printf("Device found!\n"); - printf("Bus: %d, Device: %d, function: %d \n", bus, device, function); - printf("DeviceID: 0x%x, VendorID: %s\n", DeviceID, getVendor(VendorID) ); - - // iterate over the functions if it is a multi function device! - if( false ){ - for ( function ++ ; function < 8; function++) - { - - } - } - PCIBusAddress busAddress = PCIBusAddress{bus, device, function }; - uint8_t header_type = GetHeaderType(busAddress); - printf( "Header type: 0x%x\n", header_type); + PrintPCIDeviceInfo(busAddress); + + // iterate over the functions if it is a multi function device! + if( IsMultiFunctionDevice(busAddress) ){ + printf("Multi function device! \n"); + printf("Check remaining Functions\n"); + for ( function = 1 ; function < 8; function++) + { + uint32_t DeviceID = GetDevice(bus, device, function) >> 16; + + if( DeviceID != 0xFFFF){ + PCIBusAddress busAddress2 = PCIBusAddress{bus, device, function}; + PrintPCIDeviceInfo(busAddress2); + devicesFound++; + } + } + + } + + - uint16_t deviceClasses = GetClassCodes(busAddress); - printf(" class: %s, subClass: %d\n\n", - (deviceClasses >>8) > 0x13 ? "Unknown": GetClassCodeName((deviceClasses >>8)), deviceClasses & 0xFF); devicesFound++; } diff --git a/src/kernel/pci/pciDevice.h b/src/kernel/pci/pciDevice.h index adc52f0..9ef88f2 100644 --- a/src/kernel/pci/pciDevice.h +++ b/src/kernel/pci/pciDevice.h @@ -1,6 +1,5 @@ #pragma once #include - /* * PCI devices API */ @@ -8,14 +7,14 @@ struct PCIBusAddress{ int bus ; int device ; - int function[8]; + int function; - uint32_t getAddress( int deviceFunction = 0 ){ + uint32_t getAddress( ){ return ((uint32_t) 1 << 31) | ((uint32_t) bus << 16) | ((uint32_t) device << 11)| - ((uint32_t) function[deviceFunction] << 8) | + ((uint32_t) function << 8) | 0x0000; }; @@ -27,10 +26,29 @@ class PCIDevice { ~PCIDevice(); PCIBusAddress const PCIAddress(); + + inline const char* getDeviceString(){ + return "Not implemented"; //GetClassCodeName(deviceclass); + } + + inline const char* getVendorString(){ + return "Not implemented"; // getVendor(VendorID); + } + + inline void setVendorID (uint16_t id) { + this->VendorID = id; + } + private: int bus; int device; int function; + + uint16_t VendorID; + uint16_t DeviceID; + uint8_t deviceclass; + uint8_t devicesubclass; + int headerType; }; -- 2.39.5 From a36e3d1c16916e836229a06cf10e6487f5fbcf07 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 28 Nov 2021 21:12:12 +0100 Subject: [PATCH 037/115] PCI support checked of on features.md, PCI enumeration screenshot added to readme.md --- README.md | 3 +++ features.md | 2 +- screenshots/PCIBusEnumeration.png | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 screenshots/PCIBusEnumeration.png diff --git a/README.md b/README.md index ee97592..5b50e3c 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,9 @@ W.I.P - Working on interrupt handling ![Multiboot integration](screenshots/multiboot.png) \ Multiboot information can be read by the kernel. + +![PCI enumeration](screenshots/PCIBusEnumeration.png) \ +Enumerating the PCI bus ________________________ ### The goal diff --git a/features.md b/features.md index 53b1cf0..155b5b5 100644 --- a/features.md +++ b/features.md @@ -17,7 +17,7 @@ Enable SIMD Extensions (SSE) ## Other features I am thinking of: - PCI support \ + PCI support \ ATA PIO Mode support \ USTAR Filesystem ( For its simplicity this is very likely the first filesystem the OS is going to support) \ ACPI support ( Or some other basic way to support shutdown, reboot and possibly hibernation ) \ diff --git a/screenshots/PCIBusEnumeration.png b/screenshots/PCIBusEnumeration.png new file mode 100644 index 0000000..cafbf48 --- /dev/null +++ b/screenshots/PCIBusEnumeration.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3873ae8e4e291661ae99310cf26ed6b51462a3434142423b55652e63efd96c79 +size 17146 -- 2.39.5 From 72438ae70dabc0739dd5107892ecf1c57489114b Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 28 Nov 2021 23:06:21 +0100 Subject: [PATCH 038/115] Makefile: Added ISO test option for qemu. --- Makefile | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Makefile b/Makefile index 365f8be..ada8e52 100644 --- a/Makefile +++ b/Makefile @@ -52,6 +52,9 @@ iso: clean_iso clean build test: $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo +test_iso: + $(EMULATOR) -cdrom $(BUILD_DIR)/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo + build_kernel: $(OBJ_LINK_LIST) $(CC) -T $(SRC_DIR)/kernel//linker.ld -o $(BUILD_DIR)/myos.bin \ -ffreestanding -O2 -nostdlib $(OBJ_LINK_LIST) -lgcc -- 2.39.5 From 5a68f77b33259c8cc25e9b576e0a2c603446656b Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 29 Nov 2021 20:00:28 +0100 Subject: [PATCH 039/115] Started the base implementation for PCI IDE drivers --- src/kernel/ide/ide.h | 95 ++++++++++ src/kernel/ide/ideCommands.h | 86 +++++++++ src/kernel/ide/sampleIDE.definitions.h | 25 +++ src/kernel/ide/sampleIDE.h | 241 +++++++++++++++++++++++++ src/kernel/kernel.cpp | 6 +- src/kernel/kernel.h | 4 +- src/kernel/pci.cpp | 19 +- src/kernel/pci.h | 5 +- 8 files changed, 469 insertions(+), 12 deletions(-) create mode 100644 src/kernel/ide/ide.h create mode 100644 src/kernel/ide/ideCommands.h create mode 100644 src/kernel/ide/sampleIDE.definitions.h create mode 100644 src/kernel/ide/sampleIDE.h diff --git a/src/kernel/ide/ide.h b/src/kernel/ide/ide.h new file mode 100644 index 0000000..776915f --- /dev/null +++ b/src/kernel/ide/ide.h @@ -0,0 +1,95 @@ +#pragma once +#include +#include "../pci/pciDevice.h" +#include "../tty/kterm.h" +#include "ideCommands.h" +#include "sampleIDE.h" + +#define IS_BIT_SET(x, bit) ((x >> bit & 0x1) == 1) + + +inline void CheckProgIF(uint8_t ProgIF){ + if( IS_BIT_SET(ProgIF, 0) ) // Is the 0th bit set + { + printf ("Primary Channel is in PCI native mode\n"); + } else{ + printf("Primary Channel is in Compatibility mode\n"); + } + + if( IS_BIT_SET(ProgIF, 1)){ + printf("Bit 0 can be modified\n"); + }else{ + printf("Bit 0 cannot be modified\n"); + } + + if( IS_BIT_SET(ProgIF, 2)){ + printf("Secondary channel is in PCI native mode\n"); + }else{ + printf("Secondary channel is in Compatibility mode\n"); + } + + if( IS_BIT_SET(ProgIF, 3)){ + printf("Bit 2 can be modified\n"); + }else{ + printf("Bit 2 cannot be modified\n"); + } + + + if( IS_BIT_SET(ProgIF , 7)){ + printf("This is a bus master IDE Controller\n"); + } else{ + printf("This controller doesn't support DMA!\n"); + } + +} + +inline void TestIDEController(){ + // Do stuff + printf("Testing IDE controllers\n"); + + // NOTE: Testing done with a hard coded known PCI addres + // Of an intel PIIX3 IDE Controller + int bus = 0; + int device =1 , function = 1; + PCIBusAddress IDEControllerPCIAddress = PCIBusAddress{bus,device, function}; + + uint8_t ProgIF = GetProgIF(IDEControllerPCIAddress); + printf( "ProgIF: 0x%x\n" ,ProgIF); + + //CheckProgIF(ProgIF); + + // For this test will just assume all bits are set + // the CheckProgIF can check but on the test machine all bits are set anyways + + uint32_t BAR0,BAR1,BAR2,BAR3, BAR4; + + BAR0 = ReadBAR(IDEControllerPCIAddress, 0); + + BAR1 = ReadBAR(IDEControllerPCIAddress, 1); + + BAR2 = ReadBAR(IDEControllerPCIAddress, 2); + + BAR3 = ReadBAR(IDEControllerPCIAddress, 3); + + BAR4 = ReadBAR(IDEControllerPCIAddress, 4); + + // All bars are return 0xffffff for some as of yet mysterious reason! + printf( "BAR 0: 0x%x\n", BAR0); + + printf( "BAR 1: 0x%x\n", BAR1); + + printf( "BAR 2: 0x%x\n", BAR2); + + printf( "BAR 3: 0x%x\n", BAR3); + + printf( "BAR 4: 0x%x\n", BAR4); + + init_IDE(BAR0, BAR1, BAR2, BAR3, BAR4); + + // Read Something from disc + unsigned int maxByteCount = 20 ; + void* MDA_buffer = (void*)0xC0000000; + + + +} diff --git a/src/kernel/ide/ideCommands.h b/src/kernel/ide/ideCommands.h new file mode 100644 index 0000000..584756e --- /dev/null +++ b/src/kernel/ide/ideCommands.h @@ -0,0 +1,86 @@ +#pragma once + +// Commands +#define ATA_CMD_READ_PIO 0x20 +#define ATA_CMD_READ_PIO_EXT 0x24 +#define ATA_CMD_READ_DMA 0xC8 +#define ATA_CMD_READ_DMA_EXT 0x25 +#define ATA_CMD_WRITE_PIO 0x30 +#define ATA_CMD_WRITE_PIO_EXT 0x34 +#define ATA_CMD_WRITE_DMA 0xCA +#define ATA_CMD_WRITE_DMA_EXT 0x35 +#define ATA_CMD_CACHE_FLUSH 0xE7 +#define ATA_CMD_CACHE_FLUSH_EXT 0xEA +#define ATA_CMD_PACKET 0xA0 +#define ATA_CMD_IDENTIFY_PACKET 0xA1 +#define ATA_CMD_IDENTIFY 0xEC + +#define ATAPI_CMD_READ 0xA8 +#define ATAPI_CMD_EJECT 0x1B + +#define ATA_IDENT_DEVICETYPE 0 +#define ATA_IDENT_CYLINDERS 2 +#define ATA_IDENT_HEADS 6 +#define ATA_IDENT_SECTORS 12 +#define ATA_IDENT_SERIAL 20 +#define ATA_IDENT_MODEL 54 +#define ATA_IDENT_CAPABILITIES 98 +#define ATA_IDENT_FIELDVALID 106 +#define ATA_IDENT_MAX_LBA 120 +#define ATA_IDENT_COMMANDSETS 164 +#define ATA_IDENT_MAX_LBA_EXT 200 + +#define IDE_ATA 0x00 +#define IDE_ATAPI 0x01 + +#define ATA_MASTER 0x00 +#define ATA_SLAVE 0x01 + + +#define ATA_REG_DATA 0x00 +#define ATA_REG_ERROR 0x01 +#define ATA_REG_FEATURES 0x01 +#define ATA_REG_SECCOUNT0 0x02 +#define ATA_REG_LBA0 0x03 +#define ATA_REG_LBA1 0x04 +#define ATA_REG_LBA2 0x05 +#define ATA_REG_HDDEVSEL 0x06 +#define ATA_REG_COMMAND 0x07 +#define ATA_REG_STATUS 0x07 +#define ATA_REG_SECCOUNT1 0x08 +#define ATA_REG_LBA3 0x09 +#define ATA_REG_LBA4 0x0A +#define ATA_REG_LBA5 0x0B +#define ATA_REG_CONTROL 0x0C +#define ATA_REG_ALTSTATUS 0x0C +#define ATA_REG_DEVADDRESS 0x0D + +// Channels: +#define ATA_PRIMARY 0x00 +#define ATA_SECONDARY 0x01 + +// Directions: +#define ATA_READ 0x00 +#define ATA_WRITE 0x01 + + +// Status +#define ATA_SR_BSY 0x80 // Busy +#define ATA_SR_DRDY 0x40 // Drive ready +#define ATA_SR_DF 0x20 // Drive write fault +#define ATA_SR_DSC 0x10 // Drive seek complete +#define ATA_SR_DRQ 0x08 // Data request ready +#define ATA_SR_CORR 0x04 // Corrected data +#define ATA_SR_IDX 0x02 // Index +#define ATA_SR_ERR 0x01 // Error + + +// Errors +#define ATA_ER_BBK 0x80 // Bad block +#define ATA_ER_UNC 0x40 // Uncorrectable data +#define ATA_ER_MC 0x20 // Media changed +#define ATA_ER_IDNF 0x10 // ID mark not found +#define ATA_ER_MCR 0x08 // Media change request +#define ATA_ER_ABRT 0x04 // Command aborted +#define ATA_ER_TK0NF 0x02 // Track 0 not found +#define ATA_ER_AMNF 0x01 // No address mark \ No newline at end of file diff --git a/src/kernel/ide/sampleIDE.definitions.h b/src/kernel/ide/sampleIDE.definitions.h new file mode 100644 index 0000000..d24f62f --- /dev/null +++ b/src/kernel/ide/sampleIDE.definitions.h @@ -0,0 +1,25 @@ +#pragma once + +struct IDEChannelRegisters{ + unsigned short base; // I/O Base. + unsigned short ctrl; // Control Base + unsigned short bmide; // Bus Master IDE + unsigned char nIEN; // IEN (no interrupt) +}channels[2]; + +extern unsigned char ide_buf[2048]; +extern unsigned char ide_irq_invoked; +extern unsigned char atapi_packet[12]; + +struct IDE_DEVICE { + unsigned char Reserved; // 0 (Empty) or 1 (This device exists). + unsigned char Channel; // 0 (Primary Channel) or 1 (Secondary Channel). + unsigned char Drive; // 0 (Master Drive) or 1 (Slave Drive). + unsigned short Type; // 0 ATA, 1:ATAPI + unsigned short Signature; // Drive Signature + unsigned short Capabilities; // Features. + unsigned int CommandSets; // Command Sets Supported. + unsigned int Size; // Size in Sectors + unsigned char Model[41]; // Model in string. +} ide_devices[4]; + diff --git a/src/kernel/ide/sampleIDE.h b/src/kernel/ide/sampleIDE.h new file mode 100644 index 0000000..19a7baf --- /dev/null +++ b/src/kernel/ide/sampleIDE.h @@ -0,0 +1,241 @@ +#pragma once +#include +#include "../tty/kterm.h" +#include "sampleIDE.definitions.h" +#include "ideCommands.h" + +void Detect_IO_Ports(uint32_t BAR0, uint32_t BAR1,uint32_t BAR2, uint32_t BAR3, uint32_t BAR4); +void DetectDevices(); + +unsigned char ide_buf[2048] = {0}; +unsigned char ide_irq_invoked = 0; +unsigned char atapi_packet[12] = {0xA8,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + +void wait(int t){ + volatile int i,j; + for(i=0;i 0x07 && reg < 0x0C) + ide_write(channel, ATA_REG_CONTROL, 0x80 | channels[channel].nIEN); + if (reg < 0x08) + outb(channels[channel].base + reg - 0x00, data); + else if (reg < 0x0C) + outb(channels[channel].base + reg - 0x06, data); + else if (reg < 0x0E) + outb(channels[channel].ctrl + reg - 0x0A, data); + else if (reg < 0x16) + outb(channels[channel].bmide + reg - 0x0E, data); + if (reg > 0x07 && reg < 0x0C) + ide_write(channel, ATA_REG_CONTROL, channels[channel].nIEN); +} + +unsigned char ide_read(unsigned char channel, unsigned char reg){ + unsigned char result; + if( reg > 0x07 && reg < 0x0C) + ide_write(channel,ATA_REG_CONTROL, 0x80 | channels[channel].nIEN); + if( reg < 0x08) + result = inb(channels[channel].base + reg - 0x00); + else if (reg < 0x0C) + result = inb(channels[channel].base + reg - 0x06); + else if (reg < 0x0E) + result = inb(channels[channel].ctrl + reg - 0x0A); + else if (reg < 0x16) + result = inb(channels[channel].bmide + reg - 0x0E); + if (reg > 0x07 && reg < 0x0C) + ide_write(channel, ATA_REG_CONTROL, channels[channel].nIEN); + return result; +} + +void ide_read_buffer(unsigned char channel, unsigned char reg, unsigned int buffer, unsigned int quads){ + if (reg > 0x07 && reg < 0x0C) + ide_write(channel, ATA_REG_CONTROL, 0x80 | channels[channel].nIEN); + if (reg < 0x08) + insl(channels[channel].base + reg - 0x00, (void *)buffer, quads); + else if (reg < 0x0C) + insl(channels[channel].base + reg - 0x06, (void *)buffer, quads); + else if (reg < 0x0E) + insl(channels[channel].ctrl + reg - 0x0A, (void *)buffer, quads); + else if (reg < 0x16) + insl(channels[channel].bmide + reg - 0x0E, (void *)buffer, quads); + if (reg > 0x07 && reg < 0x0C) + ide_write(channel, ATA_REG_CONTROL, channels[channel].nIEN); +} + +unsigned char ide_polling(unsigned char channel, unsigned int advanced_check) { + + // (I) Delay 400 nanosecond for BSY to be set: + // ------------------------------------------------- + for(int i = 0; i < 4; i++) + ide_read(channel, ATA_REG_ALTSTATUS); // Reading the Alternate Status port wastes 100ns; loop four times. + + // (II) Wait for BSY to be cleared: + // ------------------------------------------------- + while (ide_read(channel, ATA_REG_STATUS) & ATA_SR_BSY) + ; // Wait for BSY to be zero. + + if (advanced_check) { + unsigned char state = ide_read(channel, ATA_REG_STATUS); // Read Status Register. + + // (III) Check For Errors: + // ------------------------------------------------- + if (state & ATA_SR_ERR) + return 2; // Error. + + // (IV) Check If Device fault: + // ------------------------------------------------- + if (state & ATA_SR_DF) + return 1; // Device Fault. + + // (V) Check DRQ: + // ------------------------------------------------- + // BSY = 0; DF = 0; ERR = 0 so we should check for DRQ now. + if ((state & ATA_SR_DRQ) == 0) + return 3; // DRQ should be set + + } + + return 0; // No Error. + +} + +unsigned char ide_print_error(unsigned int drive, unsigned char err) { + if (err == 0) + return err; + + printf("IDE:"); + if (err == 1) {printf("- Device Fault\n "); err = 19;} + else if (err == 2) { + unsigned char st = ide_read(ide_devices[drive].Channel, ATA_REG_ERROR); + if (st & ATA_ER_AMNF) {printf("- No Address Mark Found\n "); err = 7;} + if (st & ATA_ER_TK0NF) {printf("- No Media or Media Error\n "); err = 3;} + if (st & ATA_ER_ABRT) {printf("- Command Aborted\n "); err = 20;} + if (st & ATA_ER_MCR) {printf("- No Media or Media Error\n "); err = 3;} + if (st & ATA_ER_IDNF) {printf("- ID mark not Found\n "); err = 21;} + if (st & ATA_ER_MC) {printf("- No Media or Media Error\n "); err = 3;} + if (st & ATA_ER_UNC) {printf("- Uncorrectable Data Error\n "); err = 22;} + if (st & ATA_ER_BBK) {printf("- Bad Sectors\n "); err = 13;} + } else if (err == 3) {printf("- Reads Nothing\n "); err = 23;} + else if (err == 4) {printf("- Write Protected\n "); err = 8;} + printf("- [%s %s] %s\n", + (const char *[]){"Primary", "Secondary"}[ide_devices[drive].Channel], // Use the channel as an index into the array + (const char *[]){"Master", "Slave"}[ide_devices[drive].Drive], // Same as above, using the drive + ide_devices[drive].Model); + + return err; +} + + +inline void init_IDE( uint32_t BAR0, uint32_t BAR1,uint32_t BAR2, uint32_t BAR3, uint32_t BAR4) +{ + Detect_IO_Ports( BAR0, BAR1, BAR2, BAR3, BAR4); + + printf("ATA Primary port, base: 0x%x, ctrl: 0x%x\n", channels[ATA_PRIMARY].base , channels[ATA_PRIMARY].ctrl); + printf("ATA Secondary port, base: 0x%x, ctrl: 0x%x\n", channels[ATA_SECONDARY].base , channels[ATA_SECONDARY].ctrl); + + // 2- Disable IRQs: + ide_write(ATA_PRIMARY , ATA_REG_CONTROL, 2); + ide_write(ATA_SECONDARY, ATA_REG_CONTROL, 2); + + DetectDevices(); + + // 4- Print Summary: + for (int i = 0; i < 4; i++) + if (ide_devices[i].Reserved == 1) { + printf(" Found %s Drive %d bytes - %x\n", + (const char *[]){"ATA", "ATAPI"}[ide_devices[i].Type], /* Type */ + ide_devices[i].Size / 2, /* Size */ + ide_devices[i].Model); + } +} + + +// 3- Detect ATA-ATAPI Devices: +void DetectDevices(){ + int i, j, k, count = 0; + + for (i = 0; i < 2; i++) + for (j = 0; j < 2; j++) { + + unsigned char err = 0, type = IDE_ATA, status; + ide_devices[count].Reserved = 0; // Assuming that no drive here. + + // (I) Select Drive: + ide_write(i, ATA_REG_HDDEVSEL, 0xA0 | (j << 4)); // Select Drive. + wait(1000); // Wait 1ms for drive select to work. + + // (II) Send ATA Identify Command: + ide_write(i, ATA_REG_COMMAND, ATA_CMD_IDENTIFY); + wait(1000); + + // (III) Polling: + if (ide_read(i, ATA_REG_STATUS) == 0) continue; // If Status = 0, No Device. + + while(1) { + status = ide_read(i, ATA_REG_STATUS); + if ((status & ATA_SR_ERR)) {err = 1; break;} // If Err, Device is not ATA. + if (!(status & ATA_SR_BSY) && (status & ATA_SR_DRQ)) break; // Everything is right. + } + + // (IV) Probe for ATAPI Devices: + if (err != 0) { + unsigned char cl = ide_read(i, ATA_REG_LBA1); + unsigned char ch = ide_read(i, ATA_REG_LBA2); + + if (cl == 0x14 && ch ==0xEB) + type = IDE_ATAPI; + else if (cl == 0x69 && ch == 0x96) + type = IDE_ATAPI; + else + continue; // Unknown Type (may not be a device). + + ide_write(i, ATA_REG_COMMAND, ATA_CMD_IDENTIFY_PACKET); + wait(1000); + } + + // (V) Read Identification Space of the Device: + ide_read_buffer(i, ATA_REG_DATA, (unsigned int) ide_buf, 128); + + // (VI) Read Device Parameters: + ide_devices[count].Reserved = 1; + ide_devices[count].Type = type; + ide_devices[count].Channel = i; + ide_devices[count].Drive = j; + ide_devices[count].Signature = *((unsigned short *)(ide_buf + ATA_IDENT_DEVICETYPE)); + ide_devices[count].Capabilities = *((unsigned short *)(ide_buf + ATA_IDENT_CAPABILITIES)); + ide_devices[count].CommandSets = *((unsigned int *)(ide_buf + ATA_IDENT_COMMANDSETS)); + + // (VII) Get Size: + if (ide_devices[count].CommandSets & (1 << 26)) + // Device uses 48-Bit Addressing: + ide_devices[count].Size = *((unsigned int *)(ide_buf + ATA_IDENT_MAX_LBA_EXT)); + else + // Device uses CHS or 28-bit Addressing: + ide_devices[count].Size = *((unsigned int *)(ide_buf + ATA_IDENT_MAX_LBA)); + + // (VIII) String indicates model of device (like Western Digital HDD and SONY DVD-RW...): + for(k = 0; k < 40; k += 2) { + ide_devices[count].Model[k] = ide_buf[ATA_IDENT_MODEL + k + 1]; + ide_devices[count].Model[k + 1] = ide_buf[ATA_IDENT_MODEL + k];} + ide_devices[count].Model[40] = 0; // Terminate String. + + count++; + } +} + + +void Detect_IO_Ports(uint32_t BAR0, uint32_t BAR1,uint32_t BAR2, uint32_t BAR3, uint32_t BAR4){ + // 1 Detect I/O Ports which interface an IDE Controller + + // Based on the implementation within serenity + channels[ATA_PRIMARY].base = (BAR0 == 0x1 || BAR0 == 0x0) ? 0x1F0 : BAR0 & (~1); + channels[ATA_PRIMARY ].ctrl = (BAR1 == 0x1 || BAR1 == 0x0) ? 0x3F6 : BAR1 & (~1); + channels[ATA_SECONDARY].base = (BAR2 == 0x1 || BAR2 == 0x0) ? 0x170 : BAR2 & (~1); + channels[ATA_SECONDARY].ctrl = (BAR3 == 0x1 || BAR3 == 0x0) ? 0x376 : BAR3 & (~1); + channels[ATA_PRIMARY ].bmide = (BAR4 & (~1)) + 0; // Bus Master IDE + channels[ATA_SECONDARY].bmide = (BAR4 & (~1)) + 8; // Bus Master IDE + +} \ No newline at end of file diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 8157292..d558d6d 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -65,7 +65,11 @@ extern "C" void kernel_main (void); // Enumerate the PCI bus - PCI_Enumerate(); + PCI_Enumerate(); + + + + TestIDEController(); while (true){ diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index cb9755a..240a57f 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -2,6 +2,8 @@ extern "C"{ #include "../libc/include/string.h" } + + #include "vga/VBE.h" #include "tty/kterm.h" @@ -17,7 +19,7 @@ extern "C"{ #include "cpu.h" #include "serial.h" #include "pci.h" - +#include "ide/ide.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) diff --git a/src/kernel/pci.cpp b/src/kernel/pci.cpp index ae5c62c..c7ba0ac 100644 --- a/src/kernel/pci.cpp +++ b/src/kernel/pci.cpp @@ -121,8 +121,6 @@ const char* getVendor( uint32_t VendorID){ } - - uint32_t ConfigReadWord ( PCIBusAddress& PCIDeviceAddress , uint8_t offset){ outl(CONFIG_ADDRESS , PCIDeviceAddress.getAddress() | offset ); return inl(CONFIG_DATA); @@ -144,8 +142,6 @@ uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offs return inl(CONFIG_DATA); } - - uint8_t GetHeaderType( PCIBusAddress& PCIDeviceAddress ){ uint32_t header_information = ConfigReadWord(PCIDeviceAddress , 0xC); return (uint8_t) ( @@ -167,9 +163,6 @@ bool IsMultiFunctionDevice(PCIBusAddress& PCIDeviceAddress){ >> 7 ); } - - - void PrintPCIDeviceInfo (PCIBusAddress& PCIDeviceAddress) { uint32_t DeviceID = (GetDevice(PCIDeviceAddress.bus, PCIDeviceAddress.device, PCIDeviceAddress.function) >> 16); @@ -191,8 +184,6 @@ void PrintPCIDeviceInfo (PCIBusAddress& PCIDeviceAddress) } - - void PCI_Enumerate(){ int devicesFound = 0; // loop through all possible busses, devices and their functions; @@ -244,3 +235,13 @@ void PCI_Enumerate(){ printf("Found %d PCI devices!\n", devicesFound); } + +uint8_t GetProgIF (PCIBusAddress& PCIDeviceAddress){ + uint32_t data = ConfigReadWord(PCIDeviceAddress, 0x8); + return ((data >> 8) & 0xFF); +} + +uint32_t ReadBAR ( PCIBusAddress& PCIDeviceAddress, int bar_number){ + int offsetToBar = 0x10 + (bar_number* 0x4); + return ConfigReadWord(PCIDeviceAddress, offsetToBar); +} \ No newline at end of file diff --git a/src/kernel/pci.h b/src/kernel/pci.h index 137f950..fdfe5f2 100644 --- a/src/kernel/pci.h +++ b/src/kernel/pci.h @@ -32,4 +32,7 @@ uint16_t GetClassCodes( PCIBusAddress& PICDeviceAddress ); const char* getVendor( uint64_t VendorID); const char* GetClassCodeName (uint64_t ClassCode ); -void PCI_Enumerate(); \ No newline at end of file +uint8_t GetProgIF (PCIBusAddress& PCIDeviceAddress); +void PCI_Enumerate(); + +uint32_t ReadBAR ( PCIBusAddress& PCIDeviceAddress, int bar_number); \ No newline at end of file -- 2.39.5 From 2db83b33e1166ea25e509f614767becfe3029099 Mon Sep 17 00:00:00 2001 From: Nigel Date: Wed, 1 Dec 2021 00:00:45 +0100 Subject: [PATCH 040/115] ATAPI can identify a device correctly --- Makefile | 6 +- README.md | 4 + screenshots/CD-ROM_Identify.png | 3 + src/kernel/drivers/ata/ataDevice.cpp | 131 ++++++++++++++++++++ src/kernel/drivers/ata/ataDevice.h | 29 +++++ src/kernel/drivers/atapi/atapiDevice.cpp | 145 +++++++++++++++++++++++ src/kernel/drivers/atapi/atapiDevice.h | 29 +++++ src/kernel/ide/ide.h | 2 + src/kernel/ide/sampleIDE.definitions.h | 16 ++- src/kernel/kernel.cpp | 27 +++++ src/kernel/kernel.h | 2 + 11 files changed, 387 insertions(+), 7 deletions(-) create mode 100644 screenshots/CD-ROM_Identify.png create mode 100644 src/kernel/drivers/ata/ataDevice.cpp create mode 100644 src/kernel/drivers/ata/ataDevice.h create mode 100644 src/kernel/drivers/atapi/atapiDevice.cpp create mode 100644 src/kernel/drivers/atapi/atapiDevice.h diff --git a/Makefile b/Makefile index ada8e52..7f3f9a4 100644 --- a/Makefile +++ b/Makefile @@ -17,7 +17,8 @@ $(BUILD_DIR)/idt.o \ $(BUILD_DIR)/pci.o \ $(BUILD_DIR)/pic.o \ $(BUILD_DIR)/string.o \ -$(BUILD_DIR)/pcidevice.o +$(BUILD_DIR)/pcidevice.o \ +$(BUILD_DIR)/atapiDevice.o @@ -108,3 +109,6 @@ $(BUILD_DIR)/pci.o: $(BUILD_DIR)/pcidevice.o: $(CPP) -c $(SRC_DIR)/kernel/pci/pciDevice.cpp -o $(BUILD_DIR)/pcidevice.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/atapiDevice.o: + $(CPP) -c $(SRC_DIR)/kernel/drivers/atapi/atapiDevice.cpp -o $(BUILD_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/README.md b/README.md index 5b50e3c..1cd6063 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,10 @@ Multiboot information can be read by the kernel. ![PCI enumeration](screenshots/PCIBusEnumeration.png) \ Enumerating the PCI bus + +![ATAPI CD-ROM Identification](screenshots/CD-ROM_Identify.png) \ +Correctly identified our ATAPI device 🎉 + ________________________ ### The goal diff --git a/screenshots/CD-ROM_Identify.png b/screenshots/CD-ROM_Identify.png new file mode 100644 index 0000000..586d2ee --- /dev/null +++ b/screenshots/CD-ROM_Identify.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a49af346df5f591fd139ebda79fbb80e9d79b1db2697bc8e037ccc6955e69959 +size 58517 diff --git a/src/kernel/drivers/ata/ataDevice.cpp b/src/kernel/drivers/ata/ataDevice.cpp new file mode 100644 index 0000000..bd5f7d1 --- /dev/null +++ b/src/kernel/drivers/ata/ataDevice.cpp @@ -0,0 +1,131 @@ +#include "atapiDevice.h" +#define IS_BIT_SET(x, bit) ((x >> bit & 0x1) == 1) + +void ATA_DEVICE::Soft_Reset(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive){ + printf("Soft reseting drive...\n"); + outb(channels[DEVICE_CHANNEL].base + 7 , 0x4); + // wait a bit.. + for(int i = 0 ; i < 1000000; i++){ + asm volatile("NOP"); + } + outb(channels[DEVICE_CHANNEL].base + 7 , 0x0); + +} + + +void ATA_DEVICE::Identify(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ + // lets ignore which port we actually want to check for now ! + + /* + THE STEPS INVOLVED + + 1. Select the target drive by sending master (0x0A) or slave (0x0B) to the + drive select IO port + + 2. Set the Sectorcount, LBAlo, LBAmid and LBAhi IO ports to 0 + + 3. Send the identify command (0xEC) to the command IO port + + 4. Read the status port + 4.2 If the value is 0x0 the drive does not exist + 4.3 If it has any other value continue + 5. poll the status port until bit 7 is clear. + 6. Check if the LBAmid and LBAhi ports are non-zero + 6.2. If non-zero stop polling this is not an ATA device + 6.3 If zero continue + + 7. poll status port until bit 3 is set or bit 0 is set + + 8. if err is clear, read the data from the data port + + + */ + + + // Assuming Master here + // Select the target drive + outb(0x176, 0x0A); // on the primary bus select the master drive + + // Set the Sectorcount, LBAlo, LBAmid and LBAhi IO ports to 0 + outb(0x172, 0); + + outb(0x173, 0); + + outb(0x174, 0); + + outb(0x175, 0); + + // send the identify command; + outb(0x177, 0xA1); + + // read the status port + uint8_t status = inb(0x177); + if( status == 0x00){ + printf("No drive\n"); + return; + } + + while(true){ + status = inb(0x177); + + if( status & (~8)) + break; + } + + printf("Is this an ATA device?\n"); + uint8_t LBAmid = inb(0x174); + uint8_t LBAhi = inb(0x175); + + printf("LBAmid: 0x%x, LBAhi: 0x%x\n", LBAmid, LBAhi); + + + if( LBAhi != 0x0 || LBAmid != 0x0){ + printf("Not ATA device.. Stopping..\n"); + // return; + } + + while(true){ + status = inb(0x177); + printf( "Status bit: 0x%x\n", status); + if ( IS_BIT_SET(status, 3)){ + printf("Status: ready!\n"); + break; + + } + + if( IS_BIT_SET(status, 0)){ + printf("Status: error!\n"); + break; + } + } + + if( IS_BIT_SET(status, 0) == false){ + // READ DATA + + uint16_t deviceIdentify [256]; + + for (int i= 0; i < 256; i++){ + uint8_t data = inb(0x170); + uint8_t data2 = inb(0x170); + + deviceIdentify[i] = (uint16_t) ( (uint16_t) data << 8 | (uint16_t) data2 ); + + } + + + printf("Data received!\n"); + } + + printf("Error bit was set!\n"); + + +} + + +void ATA_DEVICE::Read(uint8_t DEVICE_CHANNEL, DEVICE_DRIVE drive) { + printf("Not implemented"); +} + +void ATA_DEVICE::Write(uint8_t DEVICE_CHANNEL, DEVICE_DRIVE drive) { + printf("Not implemented"); +} \ No newline at end of file diff --git a/src/kernel/drivers/ata/ataDevice.h b/src/kernel/drivers/ata/ataDevice.h new file mode 100644 index 0000000..cccefa4 --- /dev/null +++ b/src/kernel/drivers/ata/ataDevice.h @@ -0,0 +1,29 @@ +#pragma once +#include +#include "../io.h" +#include "../ide/ideCommands.h" +#include "../ide/sampleIDE.definitions.h" + +#include "../tty/kterm.h" + +/* +* This first driver wil make use of IO ports. +* Doing so means reading or writing from disk is going +* to be very cpu intensive. +* +*/ + +enum DEVICE_DRIVE{ + MASTER = 0xA0, + SLAVE = 0xB0 +}; + + +namespace ATA_DEVICE +{ + void Identify ( uint8_t, DEVICE_DRIVE ); + void Read ( uint8_t, DEVICE_DRIVE ); + void Write ( uint8_t, DEVICE_DRIVE ); + void Soft_Reset ( uint8_t, DEVICE_DRIVE ); + +}; diff --git a/src/kernel/drivers/atapi/atapiDevice.cpp b/src/kernel/drivers/atapi/atapiDevice.cpp new file mode 100644 index 0000000..e619680 --- /dev/null +++ b/src/kernel/drivers/atapi/atapiDevice.cpp @@ -0,0 +1,145 @@ +#include "atapiDevice.h" +#define IS_BIT_SET(x, bit) ((x >> bit & 0x1) == 1) + +bool isPacketDevice(){ + + uint8_t LBAmid = inb(0x174); + uint8_t LBAhi = inb(0x175); + + printf(" LBAmid: 0x%x, LBAhi: 0x%x"); + return LBAmid == 0x14 && LBAhi == 0xEB; + +} + + +void ATAPI_DEVICE::Identify(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ + // lets ignore which port we actually want to check for now ! + + /* THE STEPS INVOLVED + + 1. Select the target drive by sending master (0x0A) or slave (0x0B) to the + drive select IO port + + 2. Set the Sectorcount, LBAlo, LBAmid and LBAhi IO ports to 0 + + 3. Send the identify command (0xEC) to the command IO port + + 4. Read the status port + 4.2 If the value is 0x0 the drive does not exist + 4.3 If it has any other value continue + 5. poll the status port until bit 7 is clear. + 6. Check if the LBAmid and LBAhi ports are non-zero + 6.2. If non-zero stop polling this is not an ATA device + 6.3 If zero continue + + 7. poll status port until bit 3 is set or bit 0 is set + + 8. if err is clear, read the data from the data port + + + */ + + // Select the target drive + outb(0x176, 0xA0); // on the secondary bus select the master drive + outb(0x170 + 0x206 , 0x0); // write 0 to the controlport for some reason + + outb(0x176, 0xA0); + // read the status port + uint8_t status = inb(0x177); + printf("status after drive select: 0x%x\n",status); + if( status == 0x00){ + printf("No drive\n"); + return; + } + + outb(0x176, 0xA0); + + + // Set the Sectorcount, LBAlo, LBAmid and LBAhi IO ports to 0 + outb(0x172, 0); + + outb(0x173, 0); + + outb(0x174, 0); + + outb(0x175, 0); + + // send the identify command; + printf("command sent!\n"); + outb(0x177, 0xA1); + + // read the status port + uint8_t status2 = inb(0x177); + if( status2 == 0x00){ + printf("No drive\n"); + return; + } + + + printf("Waiting until ready...\n"); + + while(((status2 & 0x80 == 0x80) + && (status2 & 0x01) != 0x01) + ) status2 = inb(0x177); + + + if(status2 & 0x01){ + printf("Error!"); + return; + } + + + // READ DATA + + uint16_t deviceIdentify [256] ={0}; + + for (int i= 0; i < 256; i++){ + uint16_t data; + asm volatile ( "in %1, %0" + : "=a"(data) + : "Nd"(0x170) ); + + + deviceIdentify[i] = data ; + + + } + + printf("Model-label (ASCII hex):\n"); + for(int i = 27; i < 47; i++){ + printf(" %x ",deviceIdentify[i]); + } + + printf("\nSerial number (ASCII hex):\n"); + for (int i = 10; i < 19; i++){ + printf(" %x ", deviceIdentify[i]); + } + + printf("\nFirmware revision (ASCII hex):\n"); + for (int i = 23; i < 26; i++){ + printf(" %x ", deviceIdentify[i]); + } + + printf("\nConfiguration: %x\n", deviceIdentify[0]); + + + + printf("\nData received!\n"); + + + + + + +} + + +void ATAPI_DEVICE::Read(uint8_t DEVICE_CHANNEL, DEVICE_DRIVE drive) { + printf("Not implemented"); +} + +void ATAPI_DEVICE::Write(uint8_t DEVICE_CHANNEL, DEVICE_DRIVE drive) { + printf("Not implemented"); +} + + diff --git a/src/kernel/drivers/atapi/atapiDevice.h b/src/kernel/drivers/atapi/atapiDevice.h new file mode 100644 index 0000000..51b7ffe --- /dev/null +++ b/src/kernel/drivers/atapi/atapiDevice.h @@ -0,0 +1,29 @@ +#pragma once +#include +#include "../../io.h" +#include "../../ide/ideCommands.h" +#include "../../ide/sampleIDE.definitions.h" + +#include "../../tty/kterm.h" + +/* +* This first driver wil make use of IO ports. +* Doing so means reading or writing from disk is going +* to be very cpu intensive. +* +*/ + +enum DEVICE_DRIVE{ + MASTER = 0xA0, + SLAVE = 0xB0 +}; + + +namespace ATAPI_DEVICE +{ + bool isPacketDevice(); + void Identify ( uint8_t, DEVICE_DRIVE ); + void Read ( uint8_t, DEVICE_DRIVE ); + void Write ( uint8_t, DEVICE_DRIVE ); + +}; diff --git a/src/kernel/ide/ide.h b/src/kernel/ide/ide.h index 776915f..ce2ebc1 100644 --- a/src/kernel/ide/ide.h +++ b/src/kernel/ide/ide.h @@ -7,6 +7,8 @@ #define IS_BIT_SET(x, bit) ((x >> bit & 0x1) == 1) +IDEChannelRegisters channels[2]; +IDE_DEVICE ide_devices[4]; inline void CheckProgIF(uint8_t ProgIF){ if( IS_BIT_SET(ProgIF, 0) ) // Is the 0th bit set diff --git a/src/kernel/ide/sampleIDE.definitions.h b/src/kernel/ide/sampleIDE.definitions.h index d24f62f..957dc60 100644 --- a/src/kernel/ide/sampleIDE.definitions.h +++ b/src/kernel/ide/sampleIDE.definitions.h @@ -5,11 +5,8 @@ struct IDEChannelRegisters{ unsigned short ctrl; // Control Base unsigned short bmide; // Bus Master IDE unsigned char nIEN; // IEN (no interrupt) -}channels[2]; +}; -extern unsigned char ide_buf[2048]; -extern unsigned char ide_irq_invoked; -extern unsigned char atapi_packet[12]; struct IDE_DEVICE { unsigned char Reserved; // 0 (Empty) or 1 (This device exists). @@ -19,7 +16,14 @@ struct IDE_DEVICE { unsigned short Signature; // Drive Signature unsigned short Capabilities; // Features. unsigned int CommandSets; // Command Sets Supported. - unsigned int Size; // Size in Sectors + unsigned int Size; // Size in Sectors (NOTE: Seems unused nowadays as i've only seen the value be zero unsigned char Model[41]; // Model in string. -} ide_devices[4]; +} ; + + +extern IDEChannelRegisters channels[2]; +extern IDE_DEVICE ide_devices[4]; +extern unsigned char ide_buf[2048]; +extern unsigned char ide_irq_invoked; +extern unsigned char atapi_packet[12]; diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index d558d6d..8f32274 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -71,6 +71,33 @@ extern "C" void kernel_main (void); TestIDEController(); + int devNumber = 0 ; + for ( auto device : ide_devices){ + if (!device.Reserved) + continue; + + + printf("Device %d\n" , devNumber); + printf (" Device on Channel: (0x%x) %s\n" ,device.Channel, device.Channel == 0 ? "Primary" : "Secondary"); + printf (" Device drive:(0x%x) %s\n" , device.Drive, device.Drive? "Slave" : "Master"); + printf (" Device Type:(0x%x) %s\n" , device.Type, device.Type ? "ATAPI" : "ATA"); + devNumber ++; + + + + + + + } + + // ATAPI_DEVICE::isPacketDevice(); + + + + + ATAPI_DEVICE::Identify(ATA_SECONDARY, DEVICE_DRIVE::MASTER); + + while (true){ //Read time indefinetely diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 240a57f..9e84d19 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -20,6 +20,8 @@ extern "C"{ #include "serial.h" #include "pci.h" #include "ide/ide.h" +#include "drivers/atapi/atapiDevice.h" + #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) -- 2.39.5 From 88cc1d75bb0a38144f9ed543c049a8efaa509dd2 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 20 Dec 2021 21:53:57 +0100 Subject: [PATCH 041/115] Re-enabled interrupts from keyboard, Enabled and configured the PIT to throw interrupts at a regular interval --- Makefile | 9 +++---- src/kernel/boot.S | 40 +++++++++++-------------------- src/kernel/gdt/gdtc.cpp | 8 ++----- src/kernel/idt/idt.cpp | 37 +++++++++++++--------------- src/kernel/io.cpp | 2 +- src/kernel/kernel.cpp | 19 ++++++++++++--- src/kernel/kernel.h | 1 + src/kernel/pit.cpp | 53 +++++++++++++++++++++++++++++++++++++++++ src/kernel/pit.h | 18 ++++++++++++++ src/kernel/serial.h | 1 + 10 files changed, 128 insertions(+), 60 deletions(-) create mode 100644 src/kernel/pit.cpp create mode 100644 src/kernel/pit.h diff --git a/Makefile b/Makefile index afa65c7..5ea7845 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -23,8 +23,6 @@ all: clean build build: build_kernel iso - - clean_iso: if [[ -a isodir/boot ]] ; then rm root/boot -rd ; fi if [ -f build/barinkOS.iso ] ; then rm build/barinkOS.iso ; fi @@ -36,7 +34,7 @@ iso: clean_iso clean build grub-mkrescue -o build/barinkOS.iso root test: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -monitor stdio -display gtk -m 2G -cpu core2duo + $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo build_kernel: $(OBJ_LINK_LIST) $(CC) -T $(SRC_DIR)/kernel//linker.ld -o $(BUILD_DIR)/myos.bin \ @@ -85,3 +83,6 @@ $(BUILD_DIR)/string.o: $(BUILD_DIR)/PhysicalMemoryManager.o: $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/pit.o: + $(CPP) -c $(SRC_DIR)/kernel/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/boot.S b/src/kernel/boot.S index 0c79b10..4b38316 100644 --- a/src/kernel/boot.S +++ b/src/kernel/boot.S @@ -21,6 +21,7 @@ stack_bottom: stack_top: .section .text +.include "./src/kernel/gdt/gdt.s" .include "./src/kernel/irs_table.s" .include "./src/kernel/irq_table.s" .include "./src/kernel/idt/idt.s" @@ -45,34 +46,21 @@ _start: pushl %eax call early_main + + + mov %cr0, %eax + or $1, %eax + mov %eax, %cr0 + + + call kernel_main + + cli - - - -.include "./src/kernel/gdt/gdt.s" - - loadIDT: - #load idt - call init_idt - sti - - # Try enable A20 - # mov $0x2401, %ax - # int $0x15 +1: hlt + jmp 1b - # enable protected mode - mov %cr0, %eax - or $1, %eax - mov %eax, %cr0 - - - call kernel_main +.size _start, . - _start - cli - 1: hlt - jmp 1b - - -.size _start, . - _start \ No newline at end of file diff --git a/src/kernel/gdt/gdtc.cpp b/src/kernel/gdt/gdtc.cpp index f2624bf..9ff30d0 100644 --- a/src/kernel/gdt/gdtc.cpp +++ b/src/kernel/gdt/gdtc.cpp @@ -29,6 +29,8 @@ void add_descriptor(int which , unsigned long base, unsigned long limit, unsigne void initGDT(){ + printf("Init GDT!\n"); + // NULL segment add_descriptor(NULL_SEGMENT, 0,0,0,0); @@ -52,10 +54,4 @@ void initGDT(){ LoadGlobalDescriptorTable(); - while (true) - asm volatile("hlt"); - - - - } diff --git a/src/kernel/idt/idt.cpp b/src/kernel/idt/idt.cpp index 3334a3b..8e6fbf8 100644 --- a/src/kernel/idt/idt.cpp +++ b/src/kernel/idt/idt.cpp @@ -1,4 +1,5 @@ #include "idt.h" +#include "../pit.h" //#include "scancodes/set1.h" IDT_entry idt_table[256]; @@ -24,6 +25,8 @@ void irs_handler (registers regs) { } + + @@ -32,36 +35,33 @@ void irs_handler (registers regs) { void irq_handler (registers regs) { - - - if ( regs.int_no != 0) { - kterm_writestring("received interrupt!\n"); - printf("(IRQ) Interrupt number: %d \n", regs.int_no); - - } - - if ( regs.int_no == 1 ){ + + switch (regs.int_no) + { + case 0: + pit_tick++; + break; + case 1: // Keyboard interrupt !! int scan; /*register*/int i; // Read scancode - scan = inb(0x60); // Send ack message! i = inb(0x61); outb(0x61, i|0x80); outb(0x61, i); - kterm_writestring("A key was pressed/released\n"); printf( "Scancode: %x\n", scan); + break; - - } + default: + printf("Received INT: 0x%x\n", regs.int_no); + break; + } - - outb(0x20, 0x20); // send end of interrupt to master if ( regs.int_no > 8 && regs.int_no <= 15) { @@ -76,16 +76,13 @@ void irq_handler (registers regs) { } - - - - void init_idt(){ // Initialise the IDT pointer idt_ptr.length = sizeof(IDT_entry) * 255; idt_ptr.base = (uint32_t)&idt_table; - + printf("Init IDT\n"); + // TODO: Set everything to zero first set_id_entry(0, (uint32_t) irs0 , 0x08, 0x8F); diff --git a/src/kernel/io.cpp b/src/kernel/io.cpp index 8a0861c..e87fd90 100644 --- a/src/kernel/io.cpp +++ b/src/kernel/io.cpp @@ -22,7 +22,7 @@ unsigned int inl_p(unsigned short ){ } -void outb_p(unsigned char , unsigned short ){ +void b_p(unsigned char , unsigned short ){ } void outw(unsigned short , unsigned short ){ diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index d30350d..4a29ddc 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -1,6 +1,8 @@ #include "kernel.h" -#define GB4 524288 #define GB2 262144 + + extern "C" void kernel_main (void); + extern "C" void early_main(unsigned long magic, unsigned long addr){ /** initialize terminal interface */ kterm_init(); @@ -27,19 +29,30 @@ } initGDT(); + init_idt(); + // Enable interrupts + asm volatile("STI"); + + kernel_main(); } extern "C" void kernel_main (void) { - printf("call to init serial\n"); + init_serial(); + + + pit_initialise(); + + + while (true){ //Read time indefinetely read_rtc(); - printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); + printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d (Ticks: %06d) [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second, pit_tick); delay(1000); } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index f82f5da..7618358 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -12,6 +12,7 @@ extern "C"{ #include "gdt/gdtc.h" #include "idt/idt.h" +#include "pit.h" #include "io.h" #include "time.h" #include "cpu.h" diff --git a/src/kernel/pit.cpp b/src/kernel/pit.cpp new file mode 100644 index 0000000..585519b --- /dev/null +++ b/src/kernel/pit.cpp @@ -0,0 +1,53 @@ +#include "pit.h" +#include "tty/kterm.h" +uint32_t pit_tick = 0; + + +void pit_initialise() +{ + asm volatile("CLI"); + + printf("init PIT!\n"); + + // clear mask for IRQ 0 + uint8_t value = inb(0x21) & ~(1<< 0); + outb(0x21, value); + + io_wait(); + + const int freq = 500; + + uint32_t divisor = 1193180 / freq; + + outb(PIT_COMMAND, 0x36); + + uint8_t l = (uint8_t) (divisor & 0xFF); + uint8_t h = (uint8_t) ( (divisor>>8) & 0xff); + + outb(PIT_DATA_0, l); + outb(PIT_DATA_0,h); + + + asm volatile("STI"); +} + + +void get_pit_count() +{ + asm volatile ("CLI"); + + outb(PIT_COMMAND, 0); + uint16_t count = inb(PIT_DATA_0); + count |= inb(PIT_DATA_0) << 8; + + printf("PIT count: 0x%x\n", count); + + asm volatile("STI"); + +} + +void set_pit_count() +{ + +} + diff --git a/src/kernel/pit.h b/src/kernel/pit.h new file mode 100644 index 0000000..361ed4b --- /dev/null +++ b/src/kernel/pit.h @@ -0,0 +1,18 @@ +#pragma once +#include +#include "io.h" +#define PIT_DATA_0 0x40 +#define PIT_DATA_1 0x41 +#define PIT_DATA_2 0x42 +#define PIT_COMMAND 0x43 + + +extern uint32_t pit_tick; + + +void pit_initialise(); + + +void get_pit_count(); + +void set_pit_count(); diff --git a/src/kernel/serial.h b/src/kernel/serial.h index ecc82db..3d0b9ad 100644 --- a/src/kernel/serial.h +++ b/src/kernel/serial.h @@ -4,6 +4,7 @@ #include "io.h" #define PORT 0x3f8 static int init_serial() { + printf("Init serial\n"); outb(PORT + 1, 0x00); // Disable all interrupts outb(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor) outb(PORT + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud -- 2.39.5 From bd5d3f5d49e2c047bc29c1433a79be7e5ad5bcac Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 23 Dec 2021 17:41:07 +0100 Subject: [PATCH 042/115] Basic PIO ATA driver which can read and identify ata drives --- src/kernel/drivers/ata/ataDevice.cpp | 206 +++++++++++++++++---------- src/kernel/drivers/ata/ataDevice.h | 24 ++-- 2 files changed, 147 insertions(+), 83 deletions(-) diff --git a/src/kernel/drivers/ata/ataDevice.cpp b/src/kernel/drivers/ata/ataDevice.cpp index bd5f7d1..246638f 100644 --- a/src/kernel/drivers/ata/ataDevice.cpp +++ b/src/kernel/drivers/ata/ataDevice.cpp @@ -1,4 +1,4 @@ -#include "atapiDevice.h" +#include "ataDevice.h" #define IS_BIT_SET(x, bit) ((x >> bit & 0x1) == 1) void ATA_DEVICE::Soft_Reset(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive){ @@ -13,7 +13,7 @@ void ATA_DEVICE::Soft_Reset(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive){ } -void ATA_DEVICE::Identify(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ +void ATA_DEVICE::Identify(uint16_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ // lets ignore which port we actually want to check for now ! /* @@ -41,91 +41,153 @@ void ATA_DEVICE::Identify(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ */ - + + //printf("channel selected: 0x%x", DEVICE_CHANNEL); // Assuming Master here // Select the target drive - outb(0x176, 0x0A); // on the primary bus select the master drive - - // Set the Sectorcount, LBAlo, LBAmid and LBAhi IO ports to 0 - outb(0x172, 0); - - outb(0x173, 0); - - outb(0x174, 0); - - outb(0x175, 0); + outb(DEVICE_CHANNEL | 6, drive); // on the primary bus select the master drive + outb(DEVICE_CHANNEL | 6 , 0x0); // write 0 to the controlport for some reason + outb(DEVICE_CHANNEL | 6, drive); + uint8_t status = inb(DEVICE_CHANNEL | 7 ); + if(status == 0x00){ + printf("No drive\n"); + return; + } // send the identify command; - outb(0x177, 0xA1); + outb(DEVICE_CHANNEL | 7, 0xEC); - // read the status port - uint8_t status = inb(0x177); + + // set the sectorCount, LBAlo, LBAmid, LBA,hi IO ports to 0 + outb(DEVICE_CHANNEL | 2, 0); + + outb(DEVICE_CHANNEL | 3, 0); + + outb(DEVICE_CHANNEL | 4, 0); + + outb(DEVICE_CHANNEL | 5, 0); + + // send the identify command ; + //printf("command sent!\n"); + outb(DEVICE_CHANNEL | 7 , 0xEC); + + // read the status port + uint8_t status2 = inb(DEVICE_CHANNEL | 7); + if( status2 == 0x00){ + printf("No drive\n"); + return; + } + + //printf("Waiting until ready...\n"); + while(((status2 & 0x80 == 0x80) + && (status2 & 0x01) != 0x01) + ) status2 = inb(DEVICE_CHANNEL | 7); + + if( status2 & 0x01){ + printf("Error!\n"); + return ; + } + + uint16_t deviceIdentify [256] = {0}; + + for ( int i = 0; i < 256; i++){ + uint16_t data; + asm volatile ("inw %1, %0" : "=a"(data): "Nd"(DEVICE_CHANNEL)); + + deviceIdentify[i] = data; + } + + + printf("Model-label (ASCII hex): "); + for(int i = 27; i < 47; i++){ + kterm_put((char)(deviceIdentify[i] >> 8)); + kterm_put((char)(deviceIdentify[i] & 0x00FF)); + } + kterm_put('\n'); + +} + +void ATA_DEVICE::Read(uint16_t DEVICE_CHANNEL, DEVICE_DRIVE drive, uint32_t LBA, uint16_t* buffer) { + /* + Assume you have a sectorcount byte and a 28 bit LBA value. A sectorcount of 0 means 256 sectors = 128K. + + Notes: - When you send a command byte and the RDY bit of the Status Registers is clear, you may have to wait (technically up to 30 seconds) for the drive to spin up, before DRQ sets. You may also need to ignore ERR and DF the first four times that you read the Status, if you are polling. + - for polling PIO drivers: After transferring the last uint16_t of a PIO data block to the data IO port, give the drive a 400ns delay to reset its DRQ bit (and possibly set BSY again, while emptying/filling its buffer to/from the drive). + - on the "magic bits" sent to port 0x1f6: Bit 6 (value = 0x40) is the LBA bit. This must be set for either LBA28 or LBA48 transfers. It must be clear for CHS transfers. Bits 7 and 5 are obsolete for current ATA drives, but must be set for backwards compatibility with very old (ATA1) drives. + + An example of a 28 bit LBA PIO mode read on the Primary bus: + + */ + + const int sectorCount = 1; + + // Floating bus check + uint8_t floatingBus = inb(DEVICE_CHANNEL | 7); + if (floatingBus == 0xFF){ + printf("Floating bus!!"); + return ; + } + + printf("Read LBA: 0x%x\n", LBA); + // Send 0xE0 for the "master" or 0xF0 for the "slave", ORed with the highest 4 bits of the LBA to port 0x1F6: outb(0x1F6, 0xE0 | (slavebit << 4) | ((LBA >> 24) & 0x0F)) + outb(DEVICE_CHANNEL | 6 , ( 0xE0 | (LBA >>28) ) ); + // Send a NULL byte to port 0x1F1, if you like (it is ignored and wastes lots of CPU time): outb(0x1F1, 0x00) + outb(DEVICE_CHANNEL | 1, 0x0000 ); + //Send the sectorcount to port 0x1F2: outb(0x1F2, (unsigned char) count) + outb(DEVICE_CHANNEL | 2, sectorCount); + //Send the low 8 bits of the LBA to port 0x1F3: outb(0x1F3, (unsigned char) LBA)) + outb(DEVICE_CHANNEL | 3, LBA); + //Send the next 8 bits of the LBA to port 0x1F4: outb(0x1F4, (unsigned char)(LBA >> 8)) + outb(DEVICE_CHANNEL | 4, (LBA >> 8)); + //Send the next 8 bits of the LBA to port 0x1F5: outb(0x1F5, (unsigned char)(LBA >> 16)) + outb(DEVICE_CHANNEL | 5, (LBA >> 16)); + //Send the "READ SECTORS" command (0x20) to port 0x1F7: outb(0x1F7, 0x20) + outb(DEVICE_CHANNEL | 7, 0x20); + + volatile int i,j; + for(i=0;i<2000;i++) + for(j=0;j<25000;j++) + asm("NOP"); + + //Wait for an IRQ or poll. + uint8_t status = inb(DEVICE_CHANNEL | 7); if( status == 0x00){ printf("No drive\n"); return; } - while(true){ - status = inb(0x177); - - if( status & (~8)) - break; + printf("Status: %x\n", status); + // Check if busy! + while((status & 0x80) == 0x80){ + printf("Reading....\r"); + status = inb(DEVICE_CHANNEL | 7); + } + + + if ((status & 0x01) == 0x01){ + printf("Error occured during read!\n"); + return; } - printf("Is this an ATA device?\n"); - uint8_t LBAmid = inb(0x174); - uint8_t LBAhi = inb(0x175); - - printf("LBAmid: 0x%x, LBAhi: 0x%x\n", LBAmid, LBAhi); - - - if( LBAhi != 0x0 || LBAmid != 0x0){ - printf("Not ATA device.. Stopping..\n"); - // return; - } - - while(true){ - status = inb(0x177); - printf( "Status bit: 0x%x\n", status); - if ( IS_BIT_SET(status, 3)){ - printf("Status: ready!\n"); - break; - - } - - if( IS_BIT_SET(status, 0)){ - printf("Status: error!\n"); - break; - } + //Transfer 256 16-bit values, a uint16_t at a time, into your buffer from I/O port 0x1F0. + if( status & 0x01){ + printf("Error!\n"); + printf("Status: 0x%x\n", status); + uint16_t error_register = inb(DEVICE_CHANNEL | 1); + printf("Error register 0x%x\n",error_register ); + return ; } - - if( IS_BIT_SET(status, 0) == false){ - // READ DATA - - uint16_t deviceIdentify [256]; - - for (int i= 0; i < 256; i++){ - uint8_t data = inb(0x170); - uint8_t data2 = inb(0x170); - - deviceIdentify[i] = (uint16_t) ( (uint16_t) data << 8 | (uint16_t) data2 ); - - } - - - printf("Data received!\n"); + for ( int i = 0; i < 256; i++){ + uint16_t data; + asm volatile ("inw %1, %0" : "=a"(data): "Nd"(DEVICE_CHANNEL)); + printf (" %x ", data); + buffer[i] = data; } - - printf("Error bit was set!\n"); - + + //Then loop back to waiting for the next IRQ (or poll again -- see next note) for each successive sector. } - -void ATA_DEVICE::Read(uint8_t DEVICE_CHANNEL, DEVICE_DRIVE drive) { - printf("Not implemented"); -} - -void ATA_DEVICE::Write(uint8_t DEVICE_CHANNEL, DEVICE_DRIVE drive) { - printf("Not implemented"); +void ATA_DEVICE::Write(uint16_t DEVICE_CHANNEL, DEVICE_DRIVE drive) { + printf("Not implemented\n"); } \ No newline at end of file diff --git a/src/kernel/drivers/ata/ataDevice.h b/src/kernel/drivers/ata/ataDevice.h index cccefa4..0c8abd7 100644 --- a/src/kernel/drivers/ata/ataDevice.h +++ b/src/kernel/drivers/ata/ataDevice.h @@ -1,10 +1,10 @@ #pragma once #include -#include "../io.h" -#include "../ide/ideCommands.h" -#include "../ide/sampleIDE.definitions.h" +#include "../../io.h" +#include "../../ide/ideCommands.h" +#include "../../ide/sampleIDE.definitions.h" -#include "../tty/kterm.h" +#include "../../tty/kterm.h" /* * This first driver wil make use of IO ports. @@ -19,11 +19,13 @@ enum DEVICE_DRIVE{ }; -namespace ATA_DEVICE -{ - void Identify ( uint8_t, DEVICE_DRIVE ); - void Read ( uint8_t, DEVICE_DRIVE ); - void Write ( uint8_t, DEVICE_DRIVE ); - void Soft_Reset ( uint8_t, DEVICE_DRIVE ); - + + +namespace ATA_DEVICE{ + void Identify(uint16_t, DEVICE_DRIVE); + void Read (uint16_t, DEVICE_DRIVE, uint32_t, uint16_t*); + void Write(uint16_t, DEVICE_DRIVE); + void Soft_Reset(uint8_t ,DEVICE_DRIVE ); }; + + -- 2.39.5 From 9173b90eb16ea1c68f945e5768a665e34e7b5e50 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 23 Dec 2021 17:43:25 +0100 Subject: [PATCH 043/115] Structures added for MasterBootRecord support --- src/kernel/PartitionTable/MBR/MasterBootRecord.h | 11 +++++++++++ src/kernel/PartitionTable/MBR/PartitionTableEntry.h | 11 +++++++++++ 2 files changed, 22 insertions(+) create mode 100644 src/kernel/PartitionTable/MBR/MasterBootRecord.h create mode 100644 src/kernel/PartitionTable/MBR/PartitionTableEntry.h diff --git a/src/kernel/PartitionTable/MBR/MasterBootRecord.h b/src/kernel/PartitionTable/MBR/MasterBootRecord.h new file mode 100644 index 0000000..a8d7aea --- /dev/null +++ b/src/kernel/PartitionTable/MBR/MasterBootRecord.h @@ -0,0 +1,11 @@ +#pragma once +#include +#include "PartitionTableEntry.h" + +struct MBR { + uint8_t code [440]; + uint32_t uniqueID; + uint16_t Reserved; + PartitionTableEntry TableEntries[4]; + uint16_t ValidBootsector; +}__attribute__((packed)); \ No newline at end of file diff --git a/src/kernel/PartitionTable/MBR/PartitionTableEntry.h b/src/kernel/PartitionTable/MBR/PartitionTableEntry.h new file mode 100644 index 0000000..e1bd4d6 --- /dev/null +++ b/src/kernel/PartitionTable/MBR/PartitionTableEntry.h @@ -0,0 +1,11 @@ +#pragma once +#include + +struct PartitionTableEntry{ + uint8_t driveAttribute; + uint8_t CHS_start_address [3]; + uint8_t PartitionType; + uint8_t CHS_lastSector_Address[3]; + uint32_t LBA_partition_start; + uint32_t Number_sectors_inPartition; +}__attribute__((packed)); \ No newline at end of file -- 2.39.5 From 6d946ddce3b6eec8e6de7411fdcadfd9320b5376 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 23 Dec 2021 17:44:27 +0100 Subject: [PATCH 044/115] Struct defining the EXT2 filesystems superblock --- src/kernel/filesytems/EXT2/SuperBlock.h | 29 +++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 src/kernel/filesytems/EXT2/SuperBlock.h diff --git a/src/kernel/filesytems/EXT2/SuperBlock.h b/src/kernel/filesytems/EXT2/SuperBlock.h new file mode 100644 index 0000000..35a5a94 --- /dev/null +++ b/src/kernel/filesytems/EXT2/SuperBlock.h @@ -0,0 +1,29 @@ +#pragma once +#include +struct SuperBlock { + uint32_t NumberOfInodes; + uint32_t NumberOfBlocks; + uint32_t NumberOfReservedBlocks; + uint32_t NumberOfUnallocatedBlocks; + uint32_t NumberOfUnallocatedInodes; + uint32_t BlockNumberOfSuperBlock; + uint32_t BlockSize;// Something about a shift left + uint32_t FragmentSize; + uint32_t NumberOfBlocksInGroup; + uint32_t NumberOfFragmentsInBlockGroup; + uint32_t NumberOfInodesInBlockGroup; + uint32_t LastMountTime; // POSIX + uint32_t LastWrittenTime; // POSIX + uint16_t TimesMountedSinceCheck; + uint16_t TimesMountedUntilCheck; + uint16_t EXT_SIG ; // 0xef53 + uint16_t FS_STATE; + uint16_t ON_ERR; + uint16_t VERSION_MINOR; + uint32_t TimeLastCheck; // POSIX + uint32_t CheckInterval; //POSIX + uint32_t OS_ID; // OS the FS was created with + uint32_t VERSION_MAJOR; + uint16_t UIDReservedBlocks; + uint16_t GIDReservedBlocks; +}__attribute__((packed)); \ No newline at end of file -- 2.39.5 From 767dac7e731a6964ba82108ef297ca622eb05705 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 23 Dec 2021 17:46:27 +0100 Subject: [PATCH 045/115] Adjustments to IDE driver --- src/kernel/ide/sampleIDE.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/kernel/ide/sampleIDE.h b/src/kernel/ide/sampleIDE.h index 19a7baf..5e805e3 100644 --- a/src/kernel/ide/sampleIDE.h +++ b/src/kernel/ide/sampleIDE.h @@ -142,6 +142,7 @@ inline void init_IDE( uint32_t BAR0, uint32_t BAR1,uint32_t BAR2, uint32_t BAR3, DetectDevices(); + return; // 4- Print Summary: for (int i = 0; i < 4; i++) if (ide_devices[i].Reserved == 1) { -- 2.39.5 From 26213993493ac67163e3920b06b45b25a1272199 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 24 Dec 2021 20:08:18 +0100 Subject: [PATCH 046/115] Small code fix up - Moved memcmp function to temporary libc/mem.h - I/O functions are inlined - ATA_DEVICE read function won't print the 512 bytes by default --- Makefile | 14 +++++++++++--- src/kernel/drivers/ata/ataDevice.cpp | 3 ++- src/kernel/kernel.cpp | 24 +----------------------- src/kernel/serial.h | 14 +++++++------- src/kernel/tty/kterm.cpp | 8 +++++++- src/libc/include/mem.h | 22 ++++++++++++++++++++++ src/libc/include/string.c | 4 +++- 7 files changed, 53 insertions(+), 36 deletions(-) diff --git a/Makefile b/Makefile index 7f3f9a4..a83b0c7 100644 --- a/Makefile +++ b/Makefile @@ -18,8 +18,9 @@ $(BUILD_DIR)/pci.o \ $(BUILD_DIR)/pic.o \ $(BUILD_DIR)/string.o \ $(BUILD_DIR)/pcidevice.o \ -$(BUILD_DIR)/atapiDevice.o - +$(BUILD_DIR)/atapiDevice.o \ +$(BUILD_DIR)/ataDevice.o \ +$(BUILD_DIR)/rsdp.o \ SRC_DIR = src @@ -54,7 +55,7 @@ test: $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo test_iso: - $(EMULATOR) -cdrom $(BUILD_DIR)/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo + $(EMULATOR) -boot d -cdrom $(BUILD_DIR)/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo build_kernel: $(OBJ_LINK_LIST) $(CC) -T $(SRC_DIR)/kernel//linker.ld -o $(BUILD_DIR)/myos.bin \ @@ -112,3 +113,10 @@ $(BUILD_DIR)/pcidevice.o: $(BUILD_DIR)/atapiDevice.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/atapi/atapiDevice.cpp -o $(BUILD_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti + + +$(BUILD_DIR)/ataDevice.o: + $(CPP) -c $(SRC_DIR)/kernel/drivers/ata/ataDevice.cpp -o $(BUILD_DIR)/ataDevice.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/rsdp.o: + $(CPP) -c $(SRC_DIR)/kernel/drivers/rsdp/rsdp.cpp -o $(BUILD_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/drivers/ata/ataDevice.cpp b/src/kernel/drivers/ata/ataDevice.cpp index 246638f..05947f1 100644 --- a/src/kernel/drivers/ata/ataDevice.cpp +++ b/src/kernel/drivers/ata/ataDevice.cpp @@ -180,7 +180,8 @@ void ATA_DEVICE::Read(uint16_t DEVICE_CHANNEL, DEVICE_DRIVE drive, uint32_t LBA for ( int i = 0; i < 256; i++){ uint16_t data; asm volatile ("inw %1, %0" : "=a"(data): "Nd"(DEVICE_CHANNEL)); - printf (" %x ", data); + // printf (" %x ", data); + buffer[i] = data; } diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 8f32274..5e30044 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -2,7 +2,6 @@ #define GB4 524288 #define GB2 262144 -int memcmp( const void* ptr1, const void* ptr2, size_t num); extern "C" void kernel_main (void); @@ -34,27 +33,10 @@ extern "C" void kernel_main (void); initGDT(); - kernel_main(); } - int memcmp( const void* ptr1, const void* ptr2, size_t num) - { - const unsigned char * cs = (const unsigned char*) ptr1; - const unsigned char * ct = (const unsigned char*) ptr2; - - - for (int i = 0 ; i < num ; i++, cs++, ct++ ){ - if( *cs < *ct){ - return -1; - } else if( *cs > *ct){ - return 1; - } - } - - return 0; - - } + extern "C" void kernel_main (void) { @@ -105,9 +87,5 @@ extern "C" void kernel_main (void); printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); delay(1000); } - - - } - diff --git a/src/kernel/serial.h b/src/kernel/serial.h index ecc82db..71d0da1 100644 --- a/src/kernel/serial.h +++ b/src/kernel/serial.h @@ -3,7 +3,7 @@ #include "tty/kterm.h" #include "io.h" #define PORT 0x3f8 -static int init_serial() { +inline static int init_serial() { outb(PORT + 1, 0x00); // Disable all interrupts outb(PORT + 3, 0x80); // Enable DLAB (set baud rate divisor) outb(PORT + 0, 0x03); // Set divisor to 3 (lo byte) 38400 baud @@ -25,33 +25,33 @@ static int init_serial() { return 0; } -int is_transmit_empty() { +inline int is_transmit_empty() { return inb(PORT + 5) & 0x20; } -void write_serial(char a) { +inline void write_serial(char a) { while (is_transmit_empty() == 0); outb(PORT,a); } -int serial_received() { +inline int serial_received() { return inb(PORT + 5) & 1; } -char read_serial() { +inline char read_serial() { while (serial_received() == 0); return inb(PORT); } -void print_serial(const char* string ){ +inline void print_serial(const char* string ){ for(size_t i = 0; i < strlen(string); i ++){ write_serial(string[i]); } } -void test_serial(){ +inline void test_serial(){ /** Serial test **/ kterm_writestring("Writing to COM1 serial port:"); init_serial(); diff --git a/src/kernel/tty/kterm.cpp b/src/kernel/tty/kterm.cpp index 94bc3f1..78e481a 100644 --- a/src/kernel/tty/kterm.cpp +++ b/src/kernel/tty/kterm.cpp @@ -1,5 +1,4 @@ #include "kterm.h" - static const size_t VGA_WIDTH = 80; static const size_t VGA_HEIGHT = 25; @@ -173,6 +172,13 @@ static void itoa (char *buf, int base, int d) { } + +/** + * @brief For now this will not only write to VGA memory but also write to serial + * + * @param format + * @param ... + */ void printf ( const char *format, ...) { char **arg = (char **)&format; diff --git a/src/libc/include/mem.h b/src/libc/include/mem.h index 62c4318..7a0e216 100644 --- a/src/libc/include/mem.h +++ b/src/libc/include/mem.h @@ -1,3 +1,5 @@ +#pragma once +// NOTE: These should not be inline inline void* memset (void* ptr, int value, size_t num){ for( int i = 0; i < num; i++ ) { @@ -6,3 +8,23 @@ inline void* memset (void* ptr, int value, size_t num){ } return ptr; } + + + +inline int memcmp( const void* ptr1, const void* ptr2, size_t num) + { + const unsigned char * cs = (const unsigned char*) ptr1; + const unsigned char * ct = (const unsigned char*) ptr2; + + + for (int i = 0 ; i < num ; i++, cs++, ct++ ){ + if( *cs < *ct){ + return -1; + } else if( *cs > *ct){ + return 1; + } + } + + return 0; + + } \ No newline at end of file diff --git a/src/libc/include/string.c b/src/libc/include/string.c index 60b96b8..7822a39 100644 --- a/src/libc/include/string.c +++ b/src/libc/include/string.c @@ -6,4 +6,6 @@ size_t strlen(const char* str) { len++; } return len; -} \ No newline at end of file +} + + -- 2.39.5 From 72008b0a7a3dcff08fcf69d1b769b03c133aadc5 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 24 Dec 2021 20:13:28 +0100 Subject: [PATCH 047/115] Find RSD Table in early BIOS memory Adding functions and structures to read the RSD. --- src/kernel/drivers/rsdp/rsdp.cpp | 46 ++++++++++++++++++++++++++++++++ src/kernel/drivers/rsdp/rsdp.h | 36 +++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 src/kernel/drivers/rsdp/rsdp.cpp create mode 100644 src/kernel/drivers/rsdp/rsdp.h diff --git a/src/kernel/drivers/rsdp/rsdp.cpp b/src/kernel/drivers/rsdp/rsdp.cpp new file mode 100644 index 0000000..5f4991f --- /dev/null +++ b/src/kernel/drivers/rsdp/rsdp.cpp @@ -0,0 +1,46 @@ +#include "rsdp.h" + +void printRSD(RSDPTR* rsd){ + printf("Signature: "); + for(int i = 0; i < 8; i++){ + kterm_put(rsd->signature[i]); + } + kterm_put('\n'); + + printf("OEMID: "); + for(int i =0; i < 6 ; i++){ + kterm_put (rsd->OEMID[i]); + } + kterm_put('\n'); + + printf("Revision: %d\n", rsd->Revision); + printf("RSDT Address: 0x%x\n", rsd->RsdtAddress ); +} + +RSDPTR* FindRSD(){ + char* memory_byte = (char*) 0x000f2e14; + const void* string = "RSD PTR "; + + for( ; (uint32_t) memory_byte < 0x0100000; memory_byte+=10){ + if( memcmp(memory_byte , string , 8 ) == 0 ) { + printf("RSD PTR found at 0x%x !\n", memory_byte); + break; + } + } + + printRSD((RSDPTR*) memory_byte); + return (RSDPTR*) memory_byte; +} + + +RSDT* getRSDT(RSDPTR* rsd){ + + RSDT* rsdt = (RSDT*) rsd->RsdtAddress; + + printf("OEMID: "); + for(int i = 0; i < 6; i++){ + kterm_put(rsdt->header.OEMID[i]); + } + kterm_put('\n'); + return rsdt; +} \ No newline at end of file diff --git a/src/kernel/drivers/rsdp/rsdp.h b/src/kernel/drivers/rsdp/rsdp.h new file mode 100644 index 0000000..1bac440 --- /dev/null +++ b/src/kernel/drivers/rsdp/rsdp.h @@ -0,0 +1,36 @@ +#pragma once +#include +#include "./../../tty/kterm.h" +#include "../../../libc/include/mem.h" +struct RSDPTR { + char signature[8]; + uint8_t Checksum ; + char OEMID [6]; + uint8_t Revision; + uint32_t RsdtAddress; +}__attribute__((packed)); + +struct ACPISDTHeader{ + char Signature[4]; + uint32_t Length; + uint8_t CheckSum; + char OEMID[6]; + char OEMTableID[8]; + uint32_t OEMRevision; + uint32_t CreatorID; + uint32_t CreatorRevision; +}__attribute__((packed)); + + +struct RSDT{ + struct ACPISDTHeader header; + uint32_t PointerToSDT[]; // Length of array : (header.Length - sizeof(header))/ 4 +}__attribute__((packed)); + + +//NOTE: only scans EBDA enough to find RSD PTR in QEMU +RSDPTR* FindRSD(); + +void printRSD(RSDPTR* rsd); + +RSDT* getRSDT(RSDPTR* rsd); \ No newline at end of file -- 2.39.5 From fb2a19e11db9d183f233af3da0cfef4950a0df5c Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 24 Dec 2021 21:31:10 +0100 Subject: [PATCH 048/115] FAT16 structures read from disk using ATA. The proper reading of folders and files is not yet implemented. Although it is close. --- .../filesytems/FAT32/BiosParameterBlock.h | 21 +++++ .../filesytems/FAT32/ExtendBootRecord.h | 32 ++++++++ src/kernel/kernel.cpp | 76 +++++++++++++++---- src/kernel/kernel.h | 8 +- 4 files changed, 119 insertions(+), 18 deletions(-) create mode 100644 src/kernel/filesytems/FAT32/BiosParameterBlock.h create mode 100644 src/kernel/filesytems/FAT32/ExtendBootRecord.h diff --git a/src/kernel/filesytems/FAT32/BiosParameterBlock.h b/src/kernel/filesytems/FAT32/BiosParameterBlock.h new file mode 100644 index 0000000..3bf2de3 --- /dev/null +++ b/src/kernel/filesytems/FAT32/BiosParameterBlock.h @@ -0,0 +1,21 @@ +#pragma once +#include +#include "./ExtendBootRecord.h" + +struct BiosParameterBlock { + uint8_t BootLoaderCodeSection [3]; + uint8_t OEM_id [8]; + uint16_t BytesPerSector ; // I suspect would be 512 + uint8_t SectorsPerCluster ; + uint16_t ReservedSectors; + uint8_t NumberOfFileAllocationTables; // Probably equals 2 + uint16_t NumberOfDirectoryEntries; // Root directory must contain entire sectors + uint16_t TotalSectorsInLogicalVolume ; // 0 means >65535 sectors in volume , actual count can be found in LargeSectorCount + uint8_t MediaDescriptor ; // Indication the media descriptor type + uint16_t NumberOfSectorsPerFAT;// only in FAT12 / FAT 16 + uint16_t NumberOfSectorsPerTrack; + uint16_t NumberOfHeadsOnMedia; + uint32_t NumberOfHiddenSectors; + uint32_t LargeSectorCount; + ExtendedBootRecord_FAT16 ebpb; +}__attribute__((packed)); \ No newline at end of file diff --git a/src/kernel/filesytems/FAT32/ExtendBootRecord.h b/src/kernel/filesytems/FAT32/ExtendBootRecord.h new file mode 100644 index 0000000..38a40b7 --- /dev/null +++ b/src/kernel/filesytems/FAT32/ExtendBootRecord.h @@ -0,0 +1,32 @@ +#pragma once +#include + +struct ExtendedBootRecord_FAT16{ + uint8_t DriveNumber; + uint8_t Reserved; + uint8_t Signature; + const uint32_t VOLUME_ID_SERIAL_NUMBER; + uint8_t volume_label [11]; + uint8_t Identifier_string [8]; + uint8_t bootCode [448]; + uint16_t partitionSignature; +}__attribute__((packed)); + +struct ExtendedBootRecord_FAT32{ + uint32_t SectorsPerFAT; + uint16_t Flags; + const uint16_t FAT_VERSION_NUMBER; + uint32_t rootDirectory_clusterNumber;// Often set to 2; + uint16_t FSInfo_SectorNumber; + uint16_t backup_bpb_sectorNumber; + uint8_t Reserved [12]; + uint8_t DriveNumber; + uint8_t Reserved2; + uint8_t Signature; // must be 0x28 or 0x29 + uint32_t VOLUME_ID_SERIAL; + uint8_t volume_label[11]; + uint8_t SystemIdentifierString [8]; // ALWAYS "FAT32 " but spec says do not trust + uint8_t BootCode [420]; // NICE + uint16_t PartitionSignature; // 0xAA55 + +}__attribute__((packed)); \ No newline at end of file diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 5e30044..407f637 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -44,40 +44,84 @@ extern "C" void kernel_main (void); init_serial(); print_serial("Serial port initialized!"); - + RSDPTR* rsd = FindRSD(); + RSDT* rsd_table = getRSDT(rsd); + // Enumerate the PCI bus PCI_Enumerate(); - - - - TestIDEController(); + TestIDEController(); int devNumber = 0 ; for ( auto device : ide_devices){ if (!device.Reserved) continue; - - printf("Device %d\n" , devNumber); printf (" Device on Channel: (0x%x) %s\n" ,device.Channel, device.Channel == 0 ? "Primary" : "Secondary"); printf (" Device drive:(0x%x) %s\n" , device.Drive, device.Drive? "Slave" : "Master"); printf (" Device Type:(0x%x) %s\n" , device.Type, device.Type ? "ATAPI" : "ATA"); devNumber ++; - - - - - } - // ATAPI_DEVICE::isPacketDevice(); - - + enum BUS_PORT { + Primary= 0x1f0, + Secondary = 0x170 + }; - ATAPI_DEVICE::Identify(ATA_SECONDARY, DEVICE_DRIVE::MASTER); + + ATA_DEVICE::Identify((uint16_t) BUS_PORT::Primary, DEVICE_DRIVE::MASTER); + + const int C = 0; + const int H = 0; + const int HPC = 16; + const int SPT = 63; + + int S = 1; + uint32_t LBA = (C*HPC+H) * SPT + (S-1); + printf("LBA: %d\n" , LBA); + uint16_t buffer [256]; + + + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, buffer); + + MBR* mbr = (MBR*) buffer; + + printf("BootSector: 0x%x\n", mbr->ValidBootsector ); + for( int i = 0 ; i < 4 ; i ++){ + PartitionTableEntry PT = mbr->TableEntries[i]; + + printf("Partition %d [ %d sectors, PartitionType: %x, 0x%x, \nLBA Start: 0x%x ]\n" , + i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); + } + + // Find the super block + uint16_t superBlock[256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, superBlock); + + BiosParameterBlock* bpb = (BiosParameterBlock*) superBlock; + + + printf("\nBPB: Bytes per Sector %d\n", bpb->BytesPerSector ); + printf("OEM ID: %s\n", bpb->OEM_id); + printf("Bytes per sector: %d\n", bpb->BytesPerSector); + printf("Sectors per cluster: %d\n", bpb->SectorsPerCluster); + printf("Reserved sectors: %d\n", bpb->ReservedSectors); + printf("Number of FAT: %d\n", bpb->NumberOfFileAllocationTables); + printf("Number of Dir entries: %d\n", bpb->NumberOfDirectoryEntries); + printf("Total Sectors in volume: %d\n", bpb->TotalSectorsInLogicalVolume); + printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); + + uint32_t PartitionAddress = mbr->TableEntries[0].LBA_partition_start *512 ; + uint32_t RootDirAddress = PartitionAddress + ((bpb->ReservedSectors + bpb->NumberOfSectorsPerFAT * bpb->NumberOfFileAllocationTables ) * bpb->BytesPerSector); + uint32_t RootDirLBA =RootDirAddress/512; + + + + uint16_t RootDir [16]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER,RootDirLBA, (uint16_t*) RootDir ); + diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 9e84d19..5542a5c 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -20,8 +20,12 @@ extern "C"{ #include "serial.h" #include "pci.h" #include "ide/ide.h" -#include "drivers/atapi/atapiDevice.h" - +//#include "drivers/atapi/atapiDevice.h" +#include "drivers/ata/ataDevice.h" +#include "./PartitionTable/MBR/MasterBootRecord.h" +#include "./filesytems/FAT32/BiosParameterBlock.h" +#include "./filesytems/FAT32/ExtendBootRecord.h" +#include "./drivers/rsdp/rsdp.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) -- 2.39.5 From b8d75dddaec072cff4f592ec0b461798ffbbc431 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 27 Dec 2021 15:26:32 +0100 Subject: [PATCH 049/115] Moving lots into seperate folders to cleanup the project structure - Drivers have now gotten Category folders - RSDP is now called ACPI - Ports folders is now called Serial to show that its a serial driver - Paging assembly definition is moved to the memory folder - VGA folder has moved into the drivers - Patched the makefile and include statements to reflect the changes in the project structure --- Makefile | 12 ++++++------ src/kernel/boot.S | 2 +- src/kernel/drivers/{rsdp => ACPI}/rsdp.cpp | 0 src/kernel/drivers/{rsdp => ACPI}/rsdp.h | 0 src/kernel/{ => drivers/IO/PCI}/pci.cpp | 0 src/kernel/{ => drivers/IO/PCI}/pci.h | 6 +++--- src/kernel/drivers/{ => IO}/ata/ataDevice.cpp | 0 src/kernel/drivers/{ => IO}/ata/ataDevice.h | 8 ++++---- src/kernel/drivers/{ => IO}/atapi/atapiDevice.cpp | 0 src/kernel/drivers/{ => IO}/atapi/atapiDevice.h | 8 ++++---- src/kernel/{ => drivers/IO}/io.cpp | 0 src/kernel/{ => drivers/IO}/io.h | 0 src/kernel/{vga => drivers/VGA}/VBE.h | 0 src/kernel/{vga => drivers/VGA}/colors.h | 0 src/kernel/idt/idt.h | 2 +- src/kernel/kernel.h | 11 +++++------ src/kernel/{ => memory}/paging.s | 0 src/kernel/pic/pic.h | 2 +- src/kernel/serial.h | 2 +- src/kernel/{ports => serial}/serial.cpp | 0 src/kernel/{ports => serial}/serial.h | 0 src/kernel/tty/kterm.h | 4 ++-- 22 files changed, 28 insertions(+), 29 deletions(-) rename src/kernel/drivers/{rsdp => ACPI}/rsdp.cpp (100%) rename src/kernel/drivers/{rsdp => ACPI}/rsdp.h (100%) rename src/kernel/{ => drivers/IO/PCI}/pci.cpp (100%) rename src/kernel/{ => drivers/IO/PCI}/pci.h (92%) rename src/kernel/drivers/{ => IO}/ata/ataDevice.cpp (100%) rename src/kernel/drivers/{ => IO}/ata/ataDevice.h (76%) rename src/kernel/drivers/{ => IO}/atapi/atapiDevice.cpp (100%) rename src/kernel/drivers/{ => IO}/atapi/atapiDevice.h (76%) rename src/kernel/{ => drivers/IO}/io.cpp (100%) rename src/kernel/{ => drivers/IO}/io.h (100%) rename src/kernel/{vga => drivers/VGA}/VBE.h (100%) rename src/kernel/{vga => drivers/VGA}/colors.h (100%) rename src/kernel/{ => memory}/paging.s (100%) rename src/kernel/{ports => serial}/serial.cpp (100%) rename src/kernel/{ports => serial}/serial.h (100%) diff --git a/Makefile b/Makefile index a83b0c7..5f7cbd5 100644 --- a/Makefile +++ b/Makefile @@ -75,7 +75,7 @@ $(BUILD_DIR)/kterm.o: $(CPP) -c $(SRC_DIR)/kernel/tty/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/boot.o: - $(AS) $(SRC_DIR)/kernel//boot.S -o $(BUILD_DIR)/boot.o + $(AS) $(SRC_DIR)/kernel/boot.S -o $(BUILD_DIR)/boot.o $(BUILD_DIR)/crti.o: $(AS) $(SRC_DIR)/kernel/crti.s -o $(BUILD_DIR)/crti.o @@ -84,7 +84,7 @@ $(BUILD_DIR)/crtn.o: $(AS) $(SRC_DIR)/kernel/crtn.s -o $(BUILD_DIR)/crtn.o $(BUILD_DIR)/io.o: - $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/IO/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/PageDirectory.o: $(CPP) -c $(SRC_DIR)/kernel/memory/PageDirectory.cpp -o $(BUILD_DIR)/PageDirectory.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -106,17 +106,17 @@ $(BUILD_DIR)/PhysicalMemoryManager.o: $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pci.o: - $(CPP) -c $(SRC_DIR)/kernel/pci.cpp -o $(BUILD_DIR)/pci.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/IO/PCI/pci.cpp -o $(BUILD_DIR)/pci.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pcidevice.o: $(CPP) -c $(SRC_DIR)/kernel/pci/pciDevice.cpp -o $(BUILD_DIR)/pcidevice.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/atapiDevice.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/atapi/atapiDevice.cpp -o $(BUILD_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/IO/atapi/atapiDevice.cpp -o $(BUILD_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/ataDevice.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/ata/ataDevice.cpp -o $(BUILD_DIR)/ataDevice.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/IO/ata/ataDevice.cpp -o $(BUILD_DIR)/ataDevice.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/rsdp.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/rsdp/rsdp.cpp -o $(BUILD_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/ACPI/rsdp.cpp -o $(BUILD_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/boot.S b/src/kernel/boot.S index 0c79b10..ee4698e 100644 --- a/src/kernel/boot.S +++ b/src/kernel/boot.S @@ -24,7 +24,7 @@ stack_top: .include "./src/kernel/irs_table.s" .include "./src/kernel/irq_table.s" .include "./src/kernel/idt/idt.s" -.include "./src/kernel/paging.s" +.include "./src/kernel/memory/paging.s" .global _start diff --git a/src/kernel/drivers/rsdp/rsdp.cpp b/src/kernel/drivers/ACPI/rsdp.cpp similarity index 100% rename from src/kernel/drivers/rsdp/rsdp.cpp rename to src/kernel/drivers/ACPI/rsdp.cpp diff --git a/src/kernel/drivers/rsdp/rsdp.h b/src/kernel/drivers/ACPI/rsdp.h similarity index 100% rename from src/kernel/drivers/rsdp/rsdp.h rename to src/kernel/drivers/ACPI/rsdp.h diff --git a/src/kernel/pci.cpp b/src/kernel/drivers/IO/PCI/pci.cpp similarity index 100% rename from src/kernel/pci.cpp rename to src/kernel/drivers/IO/PCI/pci.cpp diff --git a/src/kernel/pci.h b/src/kernel/drivers/IO/PCI/pci.h similarity index 92% rename from src/kernel/pci.h rename to src/kernel/drivers/IO/PCI/pci.h index fdfe5f2..9f2bba2 100644 --- a/src/kernel/pci.h +++ b/src/kernel/drivers/IO/PCI/pci.h @@ -1,8 +1,8 @@ #pragma once #include -#include "io.h" -#include "tty/kterm.h" -#include "pci/pciDevice.h" +#include "../io.h" +#include "../../../tty/kterm.h" +#include "../../../pci/pciDevice.h" // Configuration Space Access Mechanism #1 #define CONFIG_ADDRESS 0xCF8 // Configuration adress that is to be accessed diff --git a/src/kernel/drivers/ata/ataDevice.cpp b/src/kernel/drivers/IO/ata/ataDevice.cpp similarity index 100% rename from src/kernel/drivers/ata/ataDevice.cpp rename to src/kernel/drivers/IO/ata/ataDevice.cpp diff --git a/src/kernel/drivers/ata/ataDevice.h b/src/kernel/drivers/IO/ata/ataDevice.h similarity index 76% rename from src/kernel/drivers/ata/ataDevice.h rename to src/kernel/drivers/IO/ata/ataDevice.h index 0c8abd7..89bfe7d 100644 --- a/src/kernel/drivers/ata/ataDevice.h +++ b/src/kernel/drivers/IO/ata/ataDevice.h @@ -1,10 +1,10 @@ #pragma once #include -#include "../../io.h" -#include "../../ide/ideCommands.h" -#include "../../ide/sampleIDE.definitions.h" +#include "../io.h" +#include "../../../ide/ideCommands.h" +#include "../../../ide/sampleIDE.definitions.h" -#include "../../tty/kterm.h" +#include "../../../tty/kterm.h" /* * This first driver wil make use of IO ports. diff --git a/src/kernel/drivers/atapi/atapiDevice.cpp b/src/kernel/drivers/IO/atapi/atapiDevice.cpp similarity index 100% rename from src/kernel/drivers/atapi/atapiDevice.cpp rename to src/kernel/drivers/IO/atapi/atapiDevice.cpp diff --git a/src/kernel/drivers/atapi/atapiDevice.h b/src/kernel/drivers/IO/atapi/atapiDevice.h similarity index 76% rename from src/kernel/drivers/atapi/atapiDevice.h rename to src/kernel/drivers/IO/atapi/atapiDevice.h index 51b7ffe..37d516e 100644 --- a/src/kernel/drivers/atapi/atapiDevice.h +++ b/src/kernel/drivers/IO/atapi/atapiDevice.h @@ -1,10 +1,10 @@ #pragma once #include -#include "../../io.h" -#include "../../ide/ideCommands.h" -#include "../../ide/sampleIDE.definitions.h" +#include "../io.h" +#include "../../../ide/ideCommands.h" +#include "../../../ide/sampleIDE.definitions.h" -#include "../../tty/kterm.h" +#include "../../../tty/kterm.h" /* * This first driver wil make use of IO ports. diff --git a/src/kernel/io.cpp b/src/kernel/drivers/IO/io.cpp similarity index 100% rename from src/kernel/io.cpp rename to src/kernel/drivers/IO/io.cpp diff --git a/src/kernel/io.h b/src/kernel/drivers/IO/io.h similarity index 100% rename from src/kernel/io.h rename to src/kernel/drivers/IO/io.h diff --git a/src/kernel/vga/VBE.h b/src/kernel/drivers/VGA/VBE.h similarity index 100% rename from src/kernel/vga/VBE.h rename to src/kernel/drivers/VGA/VBE.h diff --git a/src/kernel/vga/colors.h b/src/kernel/drivers/VGA/colors.h similarity index 100% rename from src/kernel/vga/colors.h rename to src/kernel/drivers/VGA/colors.h diff --git a/src/kernel/idt/idt.h b/src/kernel/idt/idt.h index 04173d3..48c026c 100644 --- a/src/kernel/idt/idt.h +++ b/src/kernel/idt/idt.h @@ -2,7 +2,7 @@ #include "stdint.h" #include "stddef.h" -#include "../vga/colors.h" +#include "../drivers/VGA/colors.h" #include "../pic/pic.h" #include "../tty/kterm.h" diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 5542a5c..fe75fb4 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -4,7 +4,7 @@ extern "C"{ } -#include "vga/VBE.h" +#include "drivers/VGA/VBE.h" #include "tty/kterm.h" #include "./bootloader/multiboot.h" @@ -14,18 +14,17 @@ extern "C"{ #include "gdt/gdtc.h" #include "idt/idt.h" -#include "io.h" +#include "drivers/IO/io.h" #include "time.h" #include "cpu.h" #include "serial.h" -#include "pci.h" +#include "drivers/IO/PCI/pci.h" #include "ide/ide.h" -//#include "drivers/atapi/atapiDevice.h" -#include "drivers/ata/ataDevice.h" +#include "./drivers/IO/ata/ataDevice.h" #include "./PartitionTable/MBR/MasterBootRecord.h" #include "./filesytems/FAT32/BiosParameterBlock.h" #include "./filesytems/FAT32/ExtendBootRecord.h" -#include "./drivers/rsdp/rsdp.h" +#include "drivers/ACPI/rsdp.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) diff --git a/src/kernel/paging.s b/src/kernel/memory/paging.s similarity index 100% rename from src/kernel/paging.s rename to src/kernel/memory/paging.s diff --git a/src/kernel/pic/pic.h b/src/kernel/pic/pic.h index 9560cea..fa06d3d 100644 --- a/src/kernel/pic/pic.h +++ b/src/kernel/pic/pic.h @@ -1,5 +1,5 @@ #pragma once -#include "../io.h" +#include "../drivers/IO/io.h" #define PIC1 0x20 /* IO base address for master PIC */ #define PIC2 0xA0 /* IO base address for slave PIC */ diff --git a/src/kernel/serial.h b/src/kernel/serial.h index 71d0da1..edc2185 100644 --- a/src/kernel/serial.h +++ b/src/kernel/serial.h @@ -1,7 +1,7 @@ #pragma once #include "tty/kterm.h" -#include "io.h" +#include "drivers/IO/io.h" #define PORT 0x3f8 inline static int init_serial() { outb(PORT + 1, 0x00); // Disable all interrupts diff --git a/src/kernel/ports/serial.cpp b/src/kernel/serial/serial.cpp similarity index 100% rename from src/kernel/ports/serial.cpp rename to src/kernel/serial/serial.cpp diff --git a/src/kernel/ports/serial.h b/src/kernel/serial/serial.h similarity index 100% rename from src/kernel/ports/serial.h rename to src/kernel/serial/serial.h diff --git a/src/kernel/tty/kterm.h b/src/kernel/tty/kterm.h index 4f048d0..0753294 100644 --- a/src/kernel/tty/kterm.h +++ b/src/kernel/tty/kterm.h @@ -4,8 +4,8 @@ #include #include -#include "../vga/colors.h" -#include "../io.h" +#include "../drivers/VGA/colors.h" +#include "../drivers/IO/io.h" extern "C"{ #include "./../../libc/include/string.h" -- 2.39.5 From 19b9cfe9086deb7e17509a2bb24a3593e5ba0936 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 27 Dec 2021 19:35:24 +0100 Subject: [PATCH 050/115] Reading files from disk - Modified makefile to start the virtualbox vm on `make run` - Listing files in rootdirectory with their properties and content --- Makefile | 4 +- .../{FAT32 => FAT}/BiosParameterBlock.h | 0 src/kernel/filesytems/FAT/DirectoryEntry.h | 19 ++ .../{FAT32 => FAT}/ExtendBootRecord.h | 0 src/kernel/kernel.cpp | 168 +++++++++++++----- src/kernel/kernel.h | 5 +- 6 files changed, 148 insertions(+), 48 deletions(-) rename src/kernel/filesytems/{FAT32 => FAT}/BiosParameterBlock.h (100%) create mode 100644 src/kernel/filesytems/FAT/DirectoryEntry.h rename src/kernel/filesytems/{FAT32 => FAT}/ExtendBootRecord.h (100%) diff --git a/Makefile b/Makefile index 5f7cbd5..173bd5c 100644 --- a/Makefile +++ b/Makefile @@ -50,7 +50,9 @@ iso: clean_iso clean build cp build/myos.bin root/boot/myos.bin cp src/grub.cfg root/boot/grub/grub.cfg grub-mkrescue -o build/barinkOS.iso root - +run: all + virtualboxvm --startvm "BarinkOS_test" + test: $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo diff --git a/src/kernel/filesytems/FAT32/BiosParameterBlock.h b/src/kernel/filesytems/FAT/BiosParameterBlock.h similarity index 100% rename from src/kernel/filesytems/FAT32/BiosParameterBlock.h rename to src/kernel/filesytems/FAT/BiosParameterBlock.h diff --git a/src/kernel/filesytems/FAT/DirectoryEntry.h b/src/kernel/filesytems/FAT/DirectoryEntry.h new file mode 100644 index 0000000..c3e48ec --- /dev/null +++ b/src/kernel/filesytems/FAT/DirectoryEntry.h @@ -0,0 +1,19 @@ +#pragma once +#include + +struct DirectoryEntry { + uint8_t filename [8]; + uint8_t Extension [3]; + uint8_t attribute; + uint8_t Reserved; + uint8_t creation; + uint16_t CreationTime; + uint16_t CreationDate; + uint16_t LastAccessDate; + uint16_t ReservedFAT32; + uint16_t LastWriteTime; + uint16_t LastWriteDate; + uint16_t StartingCluster; + uint32_t FilesizeInBytes; + +}__attribute__((packed)); \ No newline at end of file diff --git a/src/kernel/filesytems/FAT32/ExtendBootRecord.h b/src/kernel/filesytems/FAT/ExtendBootRecord.h similarity index 100% rename from src/kernel/filesytems/FAT32/ExtendBootRecord.h rename to src/kernel/filesytems/FAT/ExtendBootRecord.h diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 407f637..9e1a416 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -3,40 +3,17 @@ #define GB2 262144 -extern "C" void kernel_main (void); - extern "C" void early_main(unsigned long magic, unsigned long addr){ - /** initialize terminal interface */ - kterm_init(); - - if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ - printf("Invalid magic number: 0x%x\n", magic); - return; - } - - CheckMBT( (multiboot_info_t *) addr); - - multiboot_info_t* mbt = (multiboot_info_t*) addr; - - /* Are mmap_* valid? */ - if (CHECK_FLAG(mbt->flags, 6)){ - PhysicalMemoryManager_initialise( mbt->mmap_addr, GB2/* Seriously dangerous hardcoded memory value*/); - PhysicalMemoryManager_initialise_available_regions(mbt->mmap_addr, mbt->mmap_addr + mbt->mmap_length); - PhysicalMemoryManager_deinitialise_kernel(); - extern uint8_t* kernel_begin; - extern uint8_t* kernel_end; - - printf("Kernel MemoryMap:\n"); - printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); + extern "C" void wait_until_shutdown(){ + while (true){ + //Read time indefinetely + read_rtc(); + printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); + delay(1000); } - initGDT(); - - - kernel_main(); } - extern "C" void kernel_main (void) { @@ -96,11 +73,11 @@ extern "C" void kernel_main (void); i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); } - // Find the super block - uint16_t superBlock[256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, superBlock); + // Find the BiosParameter block + uint16_t biosparameterblock[256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, biosparameterblock); - BiosParameterBlock* bpb = (BiosParameterBlock*) superBlock; + BiosParameterBlock* bpb = (BiosParameterBlock*) biosparameterblock; printf("\nBPB: Bytes per Sector %d\n", bpb->BytesPerSector ); @@ -113,23 +90,124 @@ extern "C" void kernel_main (void); printf("Total Sectors in volume: %d\n", bpb->TotalSectorsInLogicalVolume); printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); - uint32_t PartitionAddress = mbr->TableEntries[0].LBA_partition_start *512 ; - uint32_t RootDirAddress = PartitionAddress + ((bpb->ReservedSectors + bpb->NumberOfSectorsPerFAT * bpb->NumberOfFileAllocationTables ) * bpb->BytesPerSector); - uint32_t RootDirLBA =RootDirAddress/512; - - uint16_t RootDir [16]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER,RootDirLBA, (uint16_t*) RootDir ); - + + /** + * @brief File Allocation Table + */ + uint32_t FATAddress = mbr->TableEntries[0].LBA_partition_start + bpb->ReservedSectors ; + uint16_t FAT[256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); - while (true){ - //Read time indefinetely - read_rtc(); - printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second); - delay(1000); + // Show data in terminal + for(int i = 0; i < 256; i++ ) { + printf("%x ", FAT[i]); } + kterm_put('\n'); + + + uint32_t RootDirectoryRegion = FATAddress + ( bpb->NumberOfFileAllocationTables * bpb->NumberOfSectorsPerFAT ); + uint32_t DataRegion = RootDirectoryRegion + ((bpb->NumberOfDirectoryEntries * 32) / bpb->BytesPerSector ); + + uint16_t data2 [256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, RootDirectoryRegion, data2 ); + DirectoryEntry* RootDirectory = (DirectoryEntry*) data2; + // List files in root + for(int i= 0; i < bpb->NumberOfDirectoryEntries ; i++ ) + { + DirectoryEntry* entry = (DirectoryEntry*)((uint32_t) RootDirectory + (i * sizeof(DirectoryEntry))); + + if( entry->filename[0] == (uint8_t) 0x00 ) + break; // There are no more entries in this directory or the entry is free + + if( entry->attribute & 0x01 == 0x01 || entry->attribute & 0x20 == 0x20) + continue; // Skip listing if hidden or Achieve flag is set + + // Print the filename; + for( int n = 0; n < 8; n++ ){ + if(entry->filename[n] == 0x20) + break; + kterm_put(entry->filename[n]); + }kterm_put('\n'); + + for( int n = 0; n < 3; n++){ + kterm_put(entry->Extension[n]); + }kterm_put('\n'); + + printf("Attribute: %x \n" , entry->attribute); + printf("FileSize: %d Bytes\n", entry->FilesizeInBytes); + + if( entry->FilesizeInBytes != 0x0 || entry->attribute & 0x8 == 0x0){ + printf("Show contents"); + + printf( "Start cluster of the file: 0x%x\n" , entry->StartingCluster); + + printf("IS it only 1 cluster? %s\n" , FAT[i] == 0xFFFF? "Yes": "No" ); + + uint32_t sector = DataRegion + ((entry->StartingCluster - 0x02 ) * bpb->SectorsPerCluster); + + + uint16_t dataBlob [256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob ); + for( int n = 0; n < 256; n++) + { + kterm_put(dataBlob[n] & 0x00ff); + + kterm_put(dataBlob[n] >> 8); + }kterm_put('\n'); + + + } + + printf("======================\n"); + + + } + + + + + + + wait_until_shutdown(); } + + + + + extern "C" void early_main(unsigned long magic, unsigned long addr){ + /** initialize terminal interface */ + kterm_init(); + + if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ + printf("Invalid magic number: 0x%x\n", magic); + return; + } + + CheckMBT( (multiboot_info_t *) addr); + + multiboot_info_t* mbt = (multiboot_info_t*) addr; + + /* Are mmap_* valid? */ + if (CHECK_FLAG(mbt->flags, 6)){ + PhysicalMemoryManager_initialise( mbt->mmap_addr, GB2/* Seriously dangerous hardcoded memory value*/); + PhysicalMemoryManager_initialise_available_regions(mbt->mmap_addr, mbt->mmap_addr + mbt->mmap_length); + PhysicalMemoryManager_deinitialise_kernel(); + extern uint8_t* kernel_begin; + extern uint8_t* kernel_end; + + printf("Kernel MemoryMap:\n"); + printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); + } + + initGDT(); + + + kernel_main(); + } + + diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index fe75fb4..3dad1ef 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -22,8 +22,9 @@ extern "C"{ #include "ide/ide.h" #include "./drivers/IO/ata/ataDevice.h" #include "./PartitionTable/MBR/MasterBootRecord.h" -#include "./filesytems/FAT32/BiosParameterBlock.h" -#include "./filesytems/FAT32/ExtendBootRecord.h" +#include "./filesytems/FAT/BiosParameterBlock.h" +#include "./filesytems/FAT/ExtendBootRecord.h" +#include "./filesytems/FAT/DirectoryEntry.h" #include "drivers/ACPI/rsdp.h" -- 2.39.5 From 0d8ef065e0cfd78fd8e968dcab62a75919ec706e Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 28 Dec 2021 19:47:32 +0100 Subject: [PATCH 051/115] Interactive supervisor mode To ease the pain of debuggin I can now interact with the system through a very simplistic terminal. Hopefully things can be tested more easily by activating the piece through a simple command. The max characters for a command is 10. To achieve this I have had to make the following changes. - Changed IRQ to update a global status variable - Added a standalone keyboard driver with getKey functions - Changed the main kernel loop to display a prompt - Added a strncmp function to the clib/string file --- Makefile | 6 ++- src/kernel/idt/idt.cpp | 91 ++++++++++++++++++++------------ src/kernel/kernel.cpp | 62 ++++++++++++++++------ src/kernel/kernel.h | 2 + src/kernel/keyboard/keyboard.cpp | 51 ++++++++++++++++++ src/kernel/keyboard/keyboard.h | 34 ++++++++++++ src/libc/include/string.c | 19 +++++++ src/libc/include/string.h | 3 ++ 8 files changed, 215 insertions(+), 53 deletions(-) create mode 100644 src/kernel/keyboard/keyboard.cpp create mode 100644 src/kernel/keyboard/keyboard.h diff --git a/Makefile b/Makefile index 5ea7845..0828ddc 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -86,3 +86,7 @@ $(BUILD_DIR)/PhysicalMemoryManager.o: $(BUILD_DIR)/pit.o: $(CPP) -c $(SRC_DIR)/kernel/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti + + +$(BUILD_DIR)/keyboard.o: + $(CPP) -c $(SRC_DIR)/kernel/keyboard/keyboard.cpp -o $(BUILD_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/idt/idt.cpp b/src/kernel/idt/idt.cpp index 8e6fbf8..8fa0fba 100644 --- a/src/kernel/idt/idt.cpp +++ b/src/kernel/idt/idt.cpp @@ -1,6 +1,6 @@ #include "idt.h" #include "../pit.h" -//#include "scancodes/set1.h" +#include "../keyboard/keyboard.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; @@ -14,7 +14,6 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ }; - void irs_handler (registers regs) { kterm_writestring("received interrupt!\n"); @@ -36,44 +35,61 @@ void irs_handler (registers regs) { void irq_handler (registers regs) { - switch (regs.int_no) - { - case 0: - pit_tick++; - break; - case 1: - // Keyboard interrupt !! + - int scan; - /*register*/int i; + switch (regs.int_no) { + case 0: + pit_tick++; + break; + case 1: + // Keyboard interrupt !! - // Read scancode - scan = inb(0x60); - - // Send ack message! - i = inb(0x61); - outb(0x61, i|0x80); - outb(0x61, i); - printf( "Scancode: %x\n", scan); - break; + int scan; + int i;/*register*/ - default: - printf("Received INT: 0x%x\n", regs.int_no); - break; - } + // Read scancode + scan = inb(0x60); + + // Send ack message! + i = inb(0x61); + outb(0x61, i|0x80); + outb(0x61, i); - outb(0x20, 0x20); // send end of interrupt to master - - if ( regs.int_no > 8 && regs.int_no <= 15) { - outb(0xA0, 0x20); // send end of interrupt to slave - } - - - if( regs.int_no == 13){ - printf(" Error code: %d \n", regs.err_code); + // NOTE: check for special scan codes + // e.g. modifiers etc.. + if( scan < 0x37){ + //printf("Read from IO: 0x%x\n", scan); + keyPress.ScanCode = scan ; + //printf( "[From Interrupt] Scancode: %x\n", keyPress.ScanCode); } + + break; + case 12: + // PS2 Mouse interrupt + printf("Mouse event triggered!"); + //int event = inb(0x60); + break; + + default: + printf("Interrupt happened!"); + printf("Received INT: 0x%x\n", regs.int_no); + break; + } + + outb(0x20, 0x20); // send end of interrupt to master + + if ( regs.int_no > 8 && regs.int_no <= 15) { + outb(0xA0, 0x20); // send end of interrupt to slave + } + + + if( regs.int_no == 13){ + printf(" Error code: %d \n", regs.err_code); + + } + } void init_idt(){ @@ -122,10 +138,15 @@ void init_idt(){ //print_serial("Remapping PIC\n"); PIC_remap(0x20, 0x28); + // clear mask for IRQ 12 + uint8_t value = inb(0x21) & ~(1<< 12); + outb(0x21, value); + + // pic IRQ Table set_id_entry(32, (uint32_t)irq0, 0x08, 0x8E); - set_id_entry(33, (uint32_t)irq1, 0x08, 0x8E); + set_id_entry(33, (uint32_t)irq1, 0x08, 0x8E); // PS2 Keyboard set_id_entry(34, (uint32_t)irq2, 0x08, 0x8E); set_id_entry(35, (uint32_t)irq3, 0x08, 0x8E); set_id_entry(36, (uint32_t)irq4, 0x08, 0x8E); @@ -136,7 +157,7 @@ void init_idt(){ set_id_entry(41, (uint32_t)irq9, 0x08, 0x8E); set_id_entry(42, (uint32_t)irq10, 0x08, 0x8E); set_id_entry(43, (uint32_t)irq11, 0x08, 0x8E); - set_id_entry(44, (uint32_t)irq12, 0x08, 0x8E); + set_id_entry(44, (uint32_t)irq12, 0x08, 0x8E); // PS2 Mouse set_id_entry(45, (uint32_t)irq13, 0x08, 0x8E); set_id_entry(46, (uint32_t)irq14, 0x08, 0x8E); set_id_entry(47, (uint32_t)irq15, 0x08, 0x8E); diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 4a29ddc..274fa30 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -7,13 +7,12 @@ /** initialize terminal interface */ kterm_init(); + // Check Multiboot magic number if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ printf("Invalid magic number: 0x%x\n", magic); return; } - CheckMBT( (multiboot_info_t *) addr); - multiboot_info_t* mbt = (multiboot_info_t*) addr; /* Are mmap_* valid? */ @@ -26,38 +25,67 @@ printf("Kernel MemoryMap:\n"); printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); + printf("Frames used: 0x%x blocks of 4 KiB\n", used_blocks); } - + initGDT(); init_idt(); // Enable interrupts asm volatile("STI"); + CheckMBT( (multiboot_info_t *) addr); + + kernel_main(); } extern "C" void kernel_main (void) { - - init_serial(); - - - pit_initialise(); - - while (true){ - //Read time indefinetely - read_rtc(); - printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d (Ticks: %06d) [ Formatted as YY-MM-DD h:mm:ss]\r" ,year, month, day, hour, minute, second, pit_tick); - delay(1000); - } - + + printf("SUPERVISOR:>$ " ); + int characterCount = 0; + char command[10] = ""; + + // NOTE: lets just show a kernel prompt + uint8_t ScanCode = getKey(); + while( ScanCode != 0x1C ) + { + char character = getASCIIKey(); + kterm_put(character ); + // wHAT THE HELL + + if( characterCount < 10 ){ + command[characterCount] = character; + characterCount++; + } + + ScanCode = getKey(); + } + printf("\n"); + KeyHandled(); + + + if ( strncmp("TIME", command , characterCount ) == 0 ) { + read_rtc(); + printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d (Ticks: %06d)\n" ,year, month, day, hour, minute, second, pit_tick); + } else if(strncmp("TEST", command, characterCount) == 0){ + // asm volatile ("MOV $4, %AX ; MOV $0, %BX ; DIV %BX"); // IRS 0 + } + else{ + printf("Unknown command\n"); + } + + + delay(1000); + } + - + } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 7618358..88b2ef9 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -12,6 +12,8 @@ extern "C"{ #include "gdt/gdtc.h" #include "idt/idt.h" +#include "keyboard/keyboard.h" + #include "pit.h" #include "io.h" #include "time.h" diff --git a/src/kernel/keyboard/keyboard.cpp b/src/kernel/keyboard/keyboard.cpp new file mode 100644 index 0000000..d526ecc --- /dev/null +++ b/src/kernel/keyboard/keyboard.cpp @@ -0,0 +1,51 @@ +#include "keyboard.h" + +KeyPressInfo keyPress {}; + +void KeyHandled(){ + keyPress.ScanCode= 0x00; + keyPress.PressedModifiers = 0x00; +} + + +char getASCIIKey(){ + char keyPressed; + // Wait until a key is pressed + while(keyPress.ScanCode == 0x00) { + asm volatile ("NOP"); + } + + + // Translate keycode to ascii + // Probably a lookup table might be handy + // Until 0x37 + const char* ASCIILookUp = + "\01234567890-=\0\0QWERTYUIOP[]\0\0ASDFGHJKL;\'`\0\\ZXCVBNM,./\0"; + + uint8_t ASCII_Index = keyPress.ScanCode - 3 ; + //printf("ASCII_INDEX: %x\n", ASCII_Index); + keyPressed = ASCIILookUp[ASCII_Index]; + + KeyHandled(); + + return keyPressed; +} + + + +uint8_t getKey(){ + // Wait until a key is pressed + while(keyPress.ScanCode == 0x00){ + asm volatile ("NOP"); + } + + if( keyPress.ScanCode > 0x37){ + keyPress.ScanCode = 0x00; + return 0; + } + + uint8_t ScanCode = keyPress.ScanCode; + // KeyHandled(); + + return ScanCode ; +} \ No newline at end of file diff --git a/src/kernel/keyboard/keyboard.h b/src/kernel/keyboard/keyboard.h new file mode 100644 index 0000000..09ce1bb --- /dev/null +++ b/src/kernel/keyboard/keyboard.h @@ -0,0 +1,34 @@ +#pragma once +#include +#include "../tty/kterm.h" +typedef enum ScanCodeSet{ + None = 0, + ScanCodeSet1 = 1, + ScanCodeSet2 = 2, + ScanCodeSet3 = 3, +}; + +typedef enum Modifiers{ + LSHIFT = 1, + RSHIFT = 2, + + LCTRL = 3, + RCTRL = 4, + + LALT = 5, + RALT = 6 +}; + +struct KeyPressInfo{ + uint8_t PressedModifiers; + uint8_t ScanCode; +}; + + + +extern KeyPressInfo keyPress; + +void KeyHandled(); + +char getASCIIKey(); +uint8_t getKey(); diff --git a/src/libc/include/string.c b/src/libc/include/string.c index 60b96b8..a45162c 100644 --- a/src/libc/include/string.c +++ b/src/libc/include/string.c @@ -6,4 +6,23 @@ size_t strlen(const char* str) { len++; } return len; +} + + + +int strncmp ( const char* str1, const char* str2, size_t num ){ + for( int i = 0; i < num ; i++){ + + if( str1[i] < str2[i]){ + return -1; + } + + if( str1[i] > str2[i] ){ + return 1; + } + + + } + + return 0; } \ No newline at end of file diff --git a/src/libc/include/string.h b/src/libc/include/string.h index 90329e9..fb8d746 100644 --- a/src/libc/include/string.h +++ b/src/libc/include/string.h @@ -1,3 +1,6 @@ #pragma once #include size_t strlen(const char* str); + + +int strncmp ( const char* str1, const char* str2, size_t num ); \ No newline at end of file -- 2.39.5 From 7496299761b4ba5f530dd0e5e1e237b1b30b1a12 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 28 Dec 2021 19:54:10 +0100 Subject: [PATCH 052/115] Basic Intel Exceptions Any interrupt thrown for any Intel defined Exception is not only being caught but displays an appropriate message to the screen. Changes made in src/kernel/idt/idt.cpp --- src/kernel/idt/idt.cpp | 181 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 169 insertions(+), 12 deletions(-) diff --git a/src/kernel/idt/idt.cpp b/src/kernel/idt/idt.cpp index 8fa0fba..74fa3ae 100644 --- a/src/kernel/idt/idt.cpp +++ b/src/kernel/idt/idt.cpp @@ -15,24 +15,181 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ }; void irs_handler (registers regs) { - kterm_writestring("received interrupt!\n"); - printf("(IRS) Interrupt number: %d \n", regs.int_no); - - if( regs.int_no == 13){ - printf(" Error code: %d \n", regs.err_code); - - } + //printf("(IRS) Interrupt number: %d \r", regs.int_no); + switch (regs.int_no) + { + case 0: + // Divide Error #DE + printf("#DE\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + case 1: + // Debug Exception #DB + printf("#DB\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; - - - + case 2: + // NMI Interrupt + printf("#NMI\n"); + break; + + case 3: + // Breakpoint Exception #BP + printf("#BP\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 4: + // Overflow Exception #OF + printf("#OF\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 5: + // BOUND Range Exceeded Exception #BR + printf("#BR\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 6: + // Invalid OpCode Exception #UD + printf("#UD\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 7: + // Device Not Available Exception #NM + printf("#NM\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 8: + // Double Fault Exception #DF + printf("#DF\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + case 9: + // Coprocessor Segment Overrun + printf("Coprocessor Segment overrun!\n"); + break; + + case 10: + // Invalid TSS Exception #TS + printf("#TS\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 11: + // Segment Not Present #NP + printf("#NP\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 12: + // Stack Fault Exception #SS + printf("#SS\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 13: + // General Protection Exception #GP + printf("#GP\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 14: + // Page Fault Exception #PF + printf("#PF\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 16: + // x87 FPU Floating-point Error #MF + printf("#MF\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 17: + // Alignment Check Exception #AC + printf("#AC\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 18: + // Machine-Check Exception #MC + printf("#MC\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 19: + // SIMD Floating-point Exception #XM + printf("#XM\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 20: + // Virtualization Exception #VE + printf("#VE\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + case 21: + // Control Protection Exception #CP + printf("#CP\n"); + printf("EIP: 0x%x\n", regs.eip); + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); + break; + + default: + // PANIC!!! + break; + } + + + } - - void irq_handler (registers regs) { -- 2.39.5 From 97606dbf7187933a9602de4ea7c20fcb547e9721 Mon Sep 17 00:00:00 2001 From: Nigel Date: Wed, 29 Dec 2021 16:15:18 +0100 Subject: [PATCH 053/115] Clean up of debugging logs and new commands. As this project grows it becomes important to keep things properly organised. In this commit I've put some effort into making the kernel.cpp file more consise and thus improve its readability. Certain parts of the code have gotten their own definition file where before it was only a header file. - Moving the Supervisor Terminal into its own definition file. - Subtracting debugging messages with preprocessor ifdef's - Time and Date is now not just a header but has its own proper definition file - Banner is displayed when booting up - Terminal has a couple new commands Commmand Description =================|||||=================================================== DATE (was TIME) Displays the curren time, date and ticks VERSION Displays system version information MEMORY Displays memory information --- Makefile | 11 +- src/kernel/bootcheck.h | 35 ++-- src/kernel/disk.h | 17 -- src/kernel/gdt/gdtc.cpp | 3 +- src/kernel/idt/idt.cpp | 4 +- src/kernel/kernel.cpp | 39 +++-- src/kernel/kernel.h | 21 +-- src/kernel/pit.cpp | 5 +- src/kernel/serial.h | 6 +- src/kernel/sv-terminal/superVisorTerminal.cpp | 74 ++++++++ src/kernel/sv-terminal/superVisorTerminal.h | 8 + src/kernel/time.cpp | 111 ++++++++++++ src/kernel/time.h | 160 ++---------------- 13 files changed, 289 insertions(+), 205 deletions(-) delete mode 100644 src/kernel/disk.h create mode 100644 src/kernel/sv-terminal/superVisorTerminal.cpp create mode 100644 src/kernel/sv-terminal/superVisorTerminal.h create mode 100644 src/kernel/time.cpp diff --git a/Makefile b/Makefile index 0828ddc..afdeb22 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES = $(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/string.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/PageFrameAllocator.o SRC_DIR = src BUILD_DIR = build @@ -33,7 +33,7 @@ iso: clean_iso clean build cp src/grub.cfg root/boot/grub/grub.cfg grub-mkrescue -o build/barinkOS.iso root -test: +run: all $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo build_kernel: $(OBJ_LINK_LIST) @@ -90,3 +90,10 @@ $(BUILD_DIR)/pit.o: $(BUILD_DIR)/keyboard.o: $(CPP) -c $(SRC_DIR)/kernel/keyboard/keyboard.cpp -o $(BUILD_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti + + +$(BUILD_DIR)/time.o: + $(CPP) -c $(SRC_DIR)/kernel/time.cpp -o $(BUILD_DIR)/time.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/sv-terminal.o: + $(CPP) -c $(SRC_DIR)/kernel/sv-terminal/superVisorTerminal.cpp -o $(BUILD_DIR)/sv-terminal.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/src/kernel/bootcheck.h b/src/kernel/bootcheck.h index 028eeba..62765a5 100644 --- a/src/kernel/bootcheck.h +++ b/src/kernel/bootcheck.h @@ -10,66 +10,81 @@ void CheckMBT ( multiboot_info_t* mbt ){ /* Set MBI to the addresss of the multiboot information structure*/ multiboot_info_t * mbi = (multiboot_info_t *) mbt; +#ifdef __VERBOSE__ /* Print out the flags */ printf("flags = 0x%x\n", (unsigned) mbi->flags); - +#endif /* Are mem_* valid? */ if ( CHECK_FLAG(mbi->flags,0)){ - printf("mem_lower = %uKB, mem_upper = %uKB\n"); + // Do nothing } /* is boot device valid ? */ - if (CHECK_FLAG (mbi->flags, 1)){ + if (CHECK_FLAG (mbi->flags, 1)) + { +#ifdef __VERBOSE__ printf("boot_device = 0x0%x\n", (unsigned) mbi->boot_device); +#endif } /* is the command line passed? */ - if (CHECK_FLAG ( mbi->flags,2)){ + if (CHECK_FLAG ( mbi->flags,2)) + { +#ifdef __VERBOSE__ printf("cmdline = %s\n", (char *) mbi->cmdline); +#endif } /* Are mods_* valid? */ if(CHECK_FLAG ( mbi->flags, 3)){ multiboot_module_t *mod; uint32_t i; - +#ifdef __VERBOSE__ printf("mods count = %d, mods_addr = 0x%x\n", (int) mbi->mods_count, (int) mbi->mods_addr); for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ printf(" mod start = 0x%x, mod_end = 0x%x, cmdline = %s\n", (unsigned) mod->mod_start, (unsigned) mod->mod_end, (char*) mod->cmdline); } +#endif } /* Bits 4 and 5 are mutually exclusive! */ - if (CHECK_FLAG (mbi->flags, 4) && CHECK_FLAG(mbi->flags, 5)){ + if (CHECK_FLAG (mbi->flags, 4) && CHECK_FLAG(mbi->flags, 5)) + { +#ifdef __VERBOSE__ printf("Both bits 4 and 5 are set.\n"); +#endif return; } /* Is the symbol table of a.out valid? */ if (CHECK_FLAG(mbi->flags, 4)){ multiboot_aout_symbol_table_t *multiboot_aout_sym = &(mbi->u.aout_sym); - +#ifdef __VERBOSE__ printf( "multiboot_aout_symbol_table: tabsize = 0x%0x, strsize = 0x%x, addr = 0x%x\n", (unsigned) multiboot_aout_sym->tabsize, (unsigned) multiboot_aout_sym->strsize, (unsigned) multiboot_aout_sym->addr); - +#endif } /* Is the section header table of ELF valid? */ if (CHECK_FLAG(mbi->flags, 5)){ multiboot_elf_section_header_table_t *multiboot_elf_sec = &(mbi->u.elf_sec); - +#ifdef __VERBOSE__ printf("multiboot_elf_sec: num = %u, size = 0x%x, addr = 0x%x, shnd = 0x%x\n", + (unsigned) multiboot_elf_sec->num, (unsigned) multiboot_elf_sec->size, (unsigned) multiboot_elf_sec->addr, (unsigned) multiboot_elf_sec->shndx); +#endif } /* Draw diagonal blue line */ if (CHECK_FLAG (mbt->flags, 12)){ - printf("Can draw!"); +#ifdef __VERBOSE__ + printf("Can draw!\n"); +#endif } diff --git a/src/kernel/disk.h b/src/kernel/disk.h deleted file mode 100644 index 7ba3925..0000000 --- a/src/kernel/disk.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -// Let's write an ATA PIO | ATA driver for now. Mostly to show that I can in theory interact with a -// storage device - -// PRIMARY_ATA_BUS -// 0x1F0 through 0x1F7 - -// SECONDARY_ATA_BUS -// 0x170 through 0x177 - -#define DEVICE_CONTROL_REGISTER 0x3F6 -#define DEVICE_CONTROL_ALTERNATE 0x376 - - -// IRQ14 Primary bus interrupt -// IRQ15 Secondary bus interrupt diff --git a/src/kernel/gdt/gdtc.cpp b/src/kernel/gdt/gdtc.cpp index 9ff30d0..c2d7ac6 100644 --- a/src/kernel/gdt/gdtc.cpp +++ b/src/kernel/gdt/gdtc.cpp @@ -29,8 +29,9 @@ void add_descriptor(int which , unsigned long base, unsigned long limit, unsigne void initGDT(){ +#ifdef __VERBOSE__ printf("Init GDT!\n"); - +#endif // NULL segment add_descriptor(NULL_SEGMENT, 0,0,0,0); diff --git a/src/kernel/idt/idt.cpp b/src/kernel/idt/idt.cpp index 74fa3ae..393902b 100644 --- a/src/kernel/idt/idt.cpp +++ b/src/kernel/idt/idt.cpp @@ -254,8 +254,10 @@ void init_idt(){ idt_ptr.length = sizeof(IDT_entry) * 255; idt_ptr.base = (uint32_t)&idt_table; +#ifdef __VERBOSE__ printf("Init IDT\n"); - +#endif + // TODO: Set everything to zero first set_id_entry(0, (uint32_t) irs0 , 0x08, 0x8F); diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 274fa30..04c2ff1 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -4,28 +4,45 @@ extern "C" void kernel_main (void); extern "C" void early_main(unsigned long magic, unsigned long addr){ - /** initialize terminal interface */ + /** + * Initialize terminal interface + * NOTE: This should be done later on , the magic value should be checked first. + */ kterm_init(); - // Check Multiboot magic number + /** + * Check Multiboot magic number + * NOTE: Printf call should not be a thing this early on ... + */ if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ printf("Invalid magic number: 0x%x\n", magic); return; } - multiboot_info_t* mbt = (multiboot_info_t*) addr; + /** + * Show a little banner for cuteness + */ + printf("|=== BarinkOS ===|\n"); - /* Are mmap_* valid? */ - if (CHECK_FLAG(mbt->flags, 6)){ + + /** + * Use the address given as an argument as the pointer + * to a Multiboot information structure. + */ + multiboot_info_t* mbt = (multiboot_info_t*) addr; + + /* + If we got a memory map from our bootloader we + should be parsing it to find out the memory regions available. + */ + if (CHECK_FLAG(mbt->flags, 6)) + { + printf("Preliminary results mmap scan:\n"); + mapMultibootMemoryMap(mbt); + PhysicalMemoryManager_initialise( mbt->mmap_addr, GB2/* Seriously dangerous hardcoded memory value*/); PhysicalMemoryManager_initialise_available_regions(mbt->mmap_addr, mbt->mmap_addr + mbt->mmap_length); PhysicalMemoryManager_deinitialise_kernel(); - extern uint8_t* kernel_begin; - extern uint8_t* kernel_end; - - printf("Kernel MemoryMap:\n"); - printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); - printf("Frames used: 0x%x blocks of 4 KiB\n", used_blocks); } initGDT(); diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 88b2ef9..63570b5 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -7,30 +7,21 @@ extern "C"{ #include "./bootloader/multiboot.h" #include "bootcheck.h" -#include "memory/PhysicalMemoryManager.h" +#include "memory/physical/PhysicalMemoryManager.h" +#include "memory/frames/PageFrameAllocator.h" #include "gdt/gdtc.h" #include "idt/idt.h" -#include "keyboard/keyboard.h" - #include "pit.h" #include "io.h" -#include "time.h" #include "cpu.h" #include "serial.h" +#include "time.h" +#include "sv-terminal/superVisorTerminal.h" + #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) -#define PANIC(message) { return; } +#define PANIC(message) {return;} -/* This needs to be moved! */ -/** - * simple delay function - **/ -void delay(int t){ - volatile int i,j; - for(i=0;i$ " ); + int characterCount = 0; + char command[10] = ""; + + // NOTE: lets just show a kernel prompt + uint8_t ScanCode = getKey(); + while( ScanCode != 0x1C ) + { + char character = getASCIIKey(); + kterm_put(character ); + // wHAT THE HELL + + if( characterCount < 10 ){ + command[characterCount] = character; + characterCount++; + } + + ScanCode = getKey(); + } + printf("\n"); + KeyHandled(); + + + if ( strncmp("DATE", command , characterCount ) == 0 ) + { + read_rtc(); + printf("======= Time & Date ==========\n"); + printf(" - Date: %02d-%02d-%02d\n",day, month, year); + printf(" - Time: %02d:%02d:%02d\n" , hour, minute, second); + printf(" - Ticks: %09d\n", pit_tick); + } + else if( strncmp ("MEMORY" , command , characterCount) == 0 ) + { + // Show memory layout + printf("========= Memory ==========\n"); + printf("Kernel MemoryMap:\n"); + printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); + printf("Frames used: 0x%x blocks of 4 KiB\n", used_blocks); + //printf("\n\n"); + //PrintPhysicalMemoryAllocation( ); + + + } + else if(strncmp("TEST", command, characterCount) == 0) + { + // TEST #DE exception + asm volatile ("MOV $4, %AX ; MOV $0, %BX ; DIV %BX"); // IRS 0 + } + else if (strncmp("VERSION", command , characterCount) == 0) + { + // Show version information + printf("========= Version ========\n"); + printf("Kernel v%d\n", 0); + + } + else if(strncmp("CLEAR", command, characterCount) == 0) + { + kterm_init(); + printf("|=== BarinkOS ===|\n"); + } + else + { + printf("Unknown command\n"); + } + + + delay(1000); + } +} \ No newline at end of file diff --git a/src/kernel/sv-terminal/superVisorTerminal.h b/src/kernel/sv-terminal/superVisorTerminal.h new file mode 100644 index 0000000..8f83a15 --- /dev/null +++ b/src/kernel/sv-terminal/superVisorTerminal.h @@ -0,0 +1,8 @@ +#pragma once +#include "../tty/kterm.h" +#include "../time.h" +#include "../pit.h" +#include "../keyboard/keyboard.h" +#include "../memory/physical/PhysicalMemoryManager.h" + +void startSuperVisorTerminal(); \ No newline at end of file diff --git a/src/kernel/time.cpp b/src/kernel/time.cpp new file mode 100644 index 0000000..325aece --- /dev/null +++ b/src/kernel/time.cpp @@ -0,0 +1,111 @@ +#include "time.h" + +// Set by ACPI table parsing code if possible +int century_register = 0x00; +unsigned char second; +unsigned char minute; +unsigned char hour; +unsigned char day; +unsigned char month; +unsigned int year; + + +int get_update_in_progress_flag() { + outb(cmos_address, 0x0A); + return (inb(cmos_data) & 0x80); +} + +unsigned char get_RTC_register(int reg) { + outb(cmos_address, reg); + return inb(cmos_data); +} + +void read_rtc() { + unsigned char century; + unsigned char last_second; + unsigned char last_minute; + unsigned char last_hour; + unsigned char last_day; + unsigned char last_month; + unsigned char last_year; + unsigned char last_century; + unsigned char registerB; + + // Note: This uses the "read registers until you get the same values twice in a row" technique + // to avoid getting dodgy/inconsistent values due to RTC updates + + while (get_update_in_progress_flag()); // Make sure an update isn't in progress + second = get_RTC_register(0x00); + minute = get_RTC_register(0x02); + hour = get_RTC_register(0x04); + day = get_RTC_register(0x07); + month = get_RTC_register(0x08); + year = get_RTC_register(0x09); + if(century_register != 0) { + century = get_RTC_register(century_register); + } else { + century = 21; + } + + do { + last_second = second; + last_minute = minute; + last_hour = hour; + last_day = day; + last_month = month; + last_year = year; + last_century = century; + + while (get_update_in_progress_flag()); // Make sure an update isn't in progress + second = get_RTC_register(0x00); + minute = get_RTC_register(0x02); + hour = get_RTC_register(0x04); + day = get_RTC_register(0x07); + month = get_RTC_register(0x08); + year = get_RTC_register(0x09); + if(century_register != 0) { + century = get_RTC_register(century_register); + } + } while( (last_second != second) || (last_minute != minute) || (last_hour != hour) || + (last_day != day) || (last_month != month) || (last_year != year) || + (last_century != century) ); + + registerB = get_RTC_register(0x0B); + + // Convert BCD to binary values if necessary + + if (!(registerB & 0x04)) { + second = (second & 0x0F) + ((second / 16) * 10); + minute = (minute & 0x0F) + ((minute / 16) * 10); + hour = ( (hour & 0x0F) + (((hour & 0x70) / 16) * 10) ) | (hour & 0x80); + day = (day & 0x0F) + ((day / 16) * 10); + month = (month & 0x0F) + ((month / 16) * 10); + year = (year & 0x0F) + ((year / 16) * 10); + if(century_register != 0) { + century = (century & 0x0F) + ((century / 16) * 10); + } + } + + // Convert 12 hour clock to 24 hour clock if necessary + + if (!(registerB & 0x02) && (hour & 0x80)) { + hour = ((hour & 0x7F) + 12) % 24; + } + + // Calculate the full (4-digit) year + + if(century_register != 0) { + year += century * 100; + } else { + year += (CURRENT_YEAR / 100) * 100; + if(year < CURRENT_YEAR) year += 100; + } +} + + +void delay(int t){ + volatile int i,j; + for(i=0;i Date: Wed, 29 Dec 2021 16:28:55 +0100 Subject: [PATCH 054/115] Started definition file for a CMOS driver --- src/kernel/drivers/cmos/cmos.cpp | 38 ++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 src/kernel/drivers/cmos/cmos.cpp diff --git a/src/kernel/drivers/cmos/cmos.cpp b/src/kernel/drivers/cmos/cmos.cpp new file mode 100644 index 0000000..17b3ae6 --- /dev/null +++ b/src/kernel/drivers/cmos/cmos.cpp @@ -0,0 +1,38 @@ +void ReadFromCMOS(unsigned char array[]) +{ + unsigned char tvalue, index; + + for (index = 0; index < 128; index++) + { + asm( + "cli\n\t" // Disable interrupts + "mov al, index\n\t" // Move index address + // since the 0x80 bit of al is not set, NMI is active + "out 0x70,al\n\t" // Copy address to CMOS register + // some kind of real delay here is probably best + "in al,0x71\n\t" // Fetch 1 byte to al + "sti\n\t" // Enable interrupts + "mov tvalue,al\n\t"); + + array[index] = tvalue; + } +} + +void WriteTOCMOS(unsigned char array[]) +{ + unsigned char index; + + for(index = 0; index < 128; index++) + { + unsigned char tvalue = array[index]; + + asm("cli\n\t" // Clear interrupts + "mov al,index\n\t" // move index address + "out 0x70,al\n\t" // copy address to CMOS register + // some kind of real delay here is probably best + "mov al,tvalue\n\t" // move value to al + "out 0x71,al\n\t" // write 1 byte to CMOS + "sti\n\\t" ); // Enable interrupts + + } +} \ No newline at end of file -- 2.39.5 From b4cff3e667be4818a835f1cae28f0b9c65d251ac Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 26 Feb 2022 20:44:16 +0100 Subject: [PATCH 055/115] Basic block allocation for physical memory allocation. - 1 block = 4096 bytes : because this will make page fault handling possibly somewhat easier - 1 byte in the bitmap = 8 blocks of physical memory unsure if the allocation is perfect ... guess i'll find out some day if this is actually correct. The bitmap needs 16kb to keep track of 2gb of physical memory. Seems a decent percentage to me. --- Makefile | 11 +- README.md | 3 +- features.md | 37 ++-- src/grub.cfg | 7 +- src/kernel/{boot.S => boot.s} | 0 src/kernel/bootinfo.h | 9 + src/kernel/definitions.h | 11 + src/kernel/kernel.cpp | 205 ++++++++++-------- src/kernel/kernel.h | 12 +- src/kernel/kstructures/bitmap.h | 28 +-- src/kernel/memory/PageDirectory.cpp | 58 +++-- src/kernel/memory/PageDirectory.h | 21 +- src/kernel/memory/PageFrameAllocator.cpp | 38 ---- src/kernel/memory/PageFrameAllocator.h | 20 -- src/kernel/memory/PhysicalMemoryManager.cpp | 118 ---------- src/kernel/memory/PhysicalMemoryManager.h | 34 --- src/kernel/memory/SlabAllocator.h | 33 --- src/kernel/memory/memory.cpp | 142 ++++++++++++ src/kernel/memory/memory.h | 48 ++++ src/kernel/memory/memoryinfo.h | 20 ++ src/kernel/sv-terminal/superVisorTerminal.cpp | 13 +- src/kernel/sv-terminal/superVisorTerminal.h | 5 +- src/libc/include/mem.h | 4 +- todo.md | 21 ++ 24 files changed, 472 insertions(+), 426 deletions(-) rename src/kernel/{boot.S => boot.s} (100%) create mode 100644 src/kernel/bootinfo.h create mode 100644 src/kernel/definitions.h delete mode 100644 src/kernel/memory/PageFrameAllocator.cpp delete mode 100644 src/kernel/memory/PageFrameAllocator.h delete mode 100644 src/kernel/memory/PhysicalMemoryManager.cpp delete mode 100644 src/kernel/memory/PhysicalMemoryManager.h delete mode 100644 src/kernel/memory/SlabAllocator.h create mode 100644 src/kernel/memory/memory.cpp create mode 100644 src/kernel/memory/memory.h create mode 100644 src/kernel/memory/memoryinfo.h diff --git a/Makefile b/Makefile index afdeb22..c1b4aa0 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/PhysicalMemoryManager.o $(BUILD_DIR)/io.o $(BUILD_DIR)/PageDirectory.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/PageFrameAllocator.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -54,7 +54,7 @@ $(BUILD_DIR)/kterm.o: $(CPP) -c $(SRC_DIR)/kernel/tty/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/boot.o: - $(AS) $(SRC_DIR)/kernel//boot.S -o $(BUILD_DIR)/boot.o + $(AS) $(SRC_DIR)/kernel/boot.s -o $(BUILD_DIR)/boot.o $(BUILD_DIR)/crti.o: $(AS) $(SRC_DIR)/kernel/crti.s -o $(BUILD_DIR)/crti.o @@ -65,8 +65,6 @@ $(BUILD_DIR)/crtn.o: $(BUILD_DIR)/io.o: $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti -$(BUILD_DIR)/PageDirectory.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/PageDirectory.cpp -o $(BUILD_DIR)/PageDirectory.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/idt.o: $(CPP) -c $(SRC_DIR)/kernel/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -81,8 +79,6 @@ $(BUILD_DIR)/pic.o: $(BUILD_DIR)/string.o: $(CC) -c $(SRC_DIR)/libc/include/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 -$(BUILD_DIR)/PhysicalMemoryManager.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pit.o: $(CPP) -c $(SRC_DIR)/kernel/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -97,3 +93,6 @@ $(BUILD_DIR)/time.o: $(BUILD_DIR)/sv-terminal.o: $(CPP) -c $(SRC_DIR)/kernel/sv-terminal/superVisorTerminal.cpp -o $(BUILD_DIR)/sv-terminal.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/memory.o: + $(CPP) -c $(SRC_DIR)/kernel/memory/memory.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/README.md b/README.md index ee97592..2e5fbb6 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,8 @@ Multiboot information can be read by the kernel. ________________________ ### The goal -Writing a hobby operating system to better understand the basic building blocks of any operating system. +Writing a hobby operating system to better understand the basic building blocks of any operating system.Initially I'd like for my +operating system to be able to run bash. ________________________ ### Operating System Technical specs/details diff --git a/features.md b/features.md index 53b1cf0..b704af2 100644 --- a/features.md +++ b/features.md @@ -1,29 +1,30 @@ # TODO list -## Start planning +## Basics Setup Cross-Compiler \ Multiboot to kernel \ Printing string to the screen \ - Printing values/numbers to the screen (a.k.k itoa) \ + Printing values/numbers to the screen \ + Basic Terminal \ Extend Multiboot implementation \ Output to serial port \ Move to protected mode \ Enabel CMOS clock \ - Time measurement (PIC &| PIT) \ + Time measurement (PIC &| PIT) \ Detect CPU speed \ Interrupt / exception system (API) \ - - Plan your memory map (virtual, and physical) : decide where you want the data to be. \ + PCI support \ + ATA PIO Mode support \ + FAT Filesystem \ + Virtual filesystem \ + Keyboard support ( P/S2 Keyboard) \ + Physical memory management \ + Paging \ + Virtual memory management \ The heap: allocating memory at runtime (malloc and free) is almost impossible to go without. \ Enable SIMD Extensions (SSE) -## Other features I am thinking of: - PCI support \ - ATA PIO Mode support \ - USTAR Filesystem ( For its simplicity this is very likely the first filesystem the OS is going to support) \ - ACPI support ( Or some other basic way to support shutdown, reboot and possibly hibernation ) \ - ATAPI support \ - Keyboard support ( P/S2 Keyboard) \ - Memory Management (MMU) + Hardware Management system + Preemptive multi tasking \ Processes \ Threads @@ -32,9 +33,11 @@ POSIX compliance (partially) \ RPC - for interprocess communication \ Sync primitives - Semaphores, Mutexes, spinlocks et al. \ - Basic Terminal \ - Extend hardware recognition ( CPU codename, memory, ATA harddisk, RAW diskSpace, CPU speed through SMBIOS et al. ) \ + + ACPI support \ + ATAPI support \ + +## Optional Basic Window server/client \ -## Support for more filesystems if I like the challenge in writing these ... - FAT Filesystem \ EXT2 Filesystem + USTAR Filesystem \ diff --git a/src/grub.cfg b/src/grub.cfg index 40431b9..27391d2 100644 --- a/src/grub.cfg +++ b/src/grub.cfg @@ -1,3 +1,8 @@ -menuentry "BarinkOS"{ +GRUB_DEFAULT=0 +GRUB_TIMEOUT=-1 +GRUB_HIDDEN_TIMEOUT=0 +GRUB_HIDDEN_TIMEOUT_QUITE=true + +menuentry "BarinkOS" { multiboot /boot/myos.bin } diff --git a/src/kernel/boot.S b/src/kernel/boot.s similarity index 100% rename from src/kernel/boot.S rename to src/kernel/boot.s diff --git a/src/kernel/bootinfo.h b/src/kernel/bootinfo.h new file mode 100644 index 0000000..575a048 --- /dev/null +++ b/src/kernel/bootinfo.h @@ -0,0 +1,9 @@ +#pragma once +#include "memory/memoryinfo.h" + + +struct BootInfo{ + const char* BootStructureID = "BarinkOS"; + MemoryInfo* memory; + +}; \ No newline at end of file diff --git a/src/kernel/definitions.h b/src/kernel/definitions.h new file mode 100644 index 0000000..1f99d57 --- /dev/null +++ b/src/kernel/definitions.h @@ -0,0 +1,11 @@ +#pragma once +/** + * Kernel definitions + */ + + + +#define __DEBUG__ false +#define KERNEL_VERSION 0 + +#define ARCHITECTURE "I386" diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 04c2ff1..9e78828 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -1,108 +1,123 @@ #include "kernel.h" -#define GB2 262144 - extern "C" void kernel_main (void); - - extern "C" void early_main(unsigned long magic, unsigned long addr){ - /** - * Initialize terminal interface - * NOTE: This should be done later on , the magic value should be checked first. - */ - kterm_init(); - - /** - * Check Multiboot magic number - * NOTE: Printf call should not be a thing this early on ... - */ - if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ - printf("Invalid magic number: 0x%x\n", magic); - return; - } +extern "C" void kernel_main (BootInfo* bootinfo) { + init_serial(); + pit_initialise(); - /** - * Show a little banner for cuteness - */ - printf("|=== BarinkOS ===|\n"); + startSuperVisorTerminal(bootinfo); +} - /** - * Use the address given as an argument as the pointer - * to a Multiboot information structure. - */ - multiboot_info_t* mbt = (multiboot_info_t*) addr; - - /* - If we got a memory map from our bootloader we - should be parsing it to find out the memory regions available. - */ - if (CHECK_FLAG(mbt->flags, 6)) - { - printf("Preliminary results mmap scan:\n"); - mapMultibootMemoryMap(mbt); - - PhysicalMemoryManager_initialise( mbt->mmap_addr, GB2/* Seriously dangerous hardcoded memory value*/); - PhysicalMemoryManager_initialise_available_regions(mbt->mmap_addr, mbt->mmap_addr + mbt->mmap_length); - PhysicalMemoryManager_deinitialise_kernel(); - } - - initGDT(); - init_idt(); - // Enable interrupts - asm volatile("STI"); - - - CheckMBT( (multiboot_info_t *) addr); - - - kernel_main(); - +extern "C" void early_main(unsigned long magic, unsigned long addr){ + /** + * Initialize terminal interface + * NOTE: This should be done later on , the magic value should be checked first. + */ + kterm_init(); + + /** + * Check Multiboot magic number + * NOTE: Printf call should not be a thing this early on ... + */ + if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ + printf("Invalid magic number: 0x%x\n", magic); + return; } - extern "C" void kernel_main (void) { - init_serial(); - pit_initialise(); - - while (true){ - - printf("SUPERVISOR:>$ " ); - int characterCount = 0; - char command[10] = ""; - - // NOTE: lets just show a kernel prompt - uint8_t ScanCode = getKey(); - while( ScanCode != 0x1C ) - { - char character = getASCIIKey(); - kterm_put(character ); - // wHAT THE HELL - - if( characterCount < 10 ){ - command[characterCount] = character; - characterCount++; - } - - ScanCode = getKey(); - } - printf("\n"); - KeyHandled(); - - - if ( strncmp("TIME", command , characterCount ) == 0 ) { - read_rtc(); - printf( "UTC time: %02d-%02d-%02d %02d:%02d:%02d (Ticks: %06d)\n" ,year, month, day, hour, minute, second, pit_tick); - } else if(strncmp("TEST", command, characterCount) == 0){ - // asm volatile ("MOV $4, %AX ; MOV $0, %BX ; DIV %BX"); // IRS 0 - } - else{ - printf("Unknown command\n"); - } + /** + * Show a little banner for cuteness + */ + printf("|=== BarinkOS ===|\n"); - delay(1000); - } - + /** + * Use the address given as an argument as the pointer + * to a Multiboot information structure. + */ + multiboot_info_t* mbt = (multiboot_info_t*) addr; + /** + * Construct our own bootInfo structure + */ + BootInfo bootinfo = {}; + + /* + If we got a memory map from our bootloader we + should be parsing it to find out the memory regions available. + */ + if (CHECK_FLAG(mbt->flags, 6)) + { - } + /* + Setup Physical memory managment + */ + MemoryInfo meminfo = {}; + bootinfo.memory = &meminfo; + + mapMultibootMemoryMap(bootinfo.memory , mbt); + printf("Memory size: 0x%x bytes\n", bootinfo.memory->TotalMemory ); + + PhysicalMemory memAlloc = PhysicalMemory{}; + memAlloc.setup(bootinfo.memory ); + + /* + Mark already in use sections + */ + + // Mark kernel memory as used + printf("Kernel Begin Pointer: 0x%x, Kernel end pointer: 0x%x\n", kernel_begin , kernel_end ); + + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; + + for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + + if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ + + } else{ + printf("allocate region: 0x%x, size : 0x%x bytes\n", (unsigned) mmap->addr,(unsigned) mmap->len ); + memAlloc.allocate_region((unsigned)mmap->addr , (unsigned)mmap->len); + } + + + } + + + printf("allocate region: 0x%x, size : 0x%x bytes\n", kernel_begin, kernel_end - kernel_begin ); + memAlloc.allocate_region(kernel_end, kernel_end - kernel_begin); + + // test alloc_block + + + uint8_t* memory = (uint8_t*) memAlloc.allocate_block(); + printf("Got a new pointer: 0x%x\n", memory); + + uint8_t* memory2 = (uint8_t*) memAlloc.allocate_block(); + printf("Got a new pointer: 0x%x\n", memory2); + + + memAlloc.free_block((void*) memory); + + uint8_t* newBlockPlse = (uint8_t*) memAlloc.allocate_block(); + + + + + // memAlloc.free_block((void*) memory); + + + } + + initGDT(); + init_idt(); + // Enable interrupts + asm volatile("STI"); + + + CheckMBT( (multiboot_info_t *) addr); + + + kernel_main(&bootinfo); + +} diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 63570b5..604c4ff 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -1,14 +1,20 @@ #pragma once -extern "C"{ +extern "C" +{ #include "../libc/include/string.h" } + +#include "definitions.h" + #include "vga/VBE.h" #include "tty/kterm.h" #include "./bootloader/multiboot.h" +#include "bootinfo.h" + +#include "memory/memory.h" +#include "memory/memoryinfo.h" #include "bootcheck.h" -#include "memory/physical/PhysicalMemoryManager.h" -#include "memory/frames/PageFrameAllocator.h" #include "gdt/gdtc.h" #include "idt/idt.h" diff --git a/src/kernel/kstructures/bitmap.h b/src/kernel/kstructures/bitmap.h index e4487fe..165266c 100644 --- a/src/kernel/kstructures/bitmap.h +++ b/src/kernel/kstructures/bitmap.h @@ -13,26 +13,26 @@ inline void bitmap_unset(uint32_t* map , int index) map[index/32] &= ~(1 << (index % 32)); } -inline int bitmap_first_unset( uint32_t* map , int size) +inline uint32_t bitmap_first_unset( uint32_t* map , int map_size) { - uint32_t rem_bits = size % 32; - for(uint32_t i = 0; i < size/32; i++) + for ( int i = 0 ; i < map_size ; i ++ ) { - if(map[i] != 0xFFFFFFFF){ - for(int j = 0; j < 32; j++){ - if(!(map[i] & (1<< j))){ - return (i*32) + j; + // a bit or more is set within this byte! + if( (map[i] & 0xFFFFFFFF) > 0 ){ + + // which bit is set? + for(int j = 0 ; j < 32 ; j++){ + if ( (map[i] & (0x00000001 << j)) > 0) + { + printf("Found bit: byte 0x%x , bit 0x%x\n", i , j); + return (i*32)+j; } } - } - } - if(rem_bits){ - for(uint32_t j = 0; j < rem_bits; j++){ - if(!(map[size/32] & (1 << j ))){ - return size + j; // Original author divided size by 32 and then multiplied it by 32 which is a net zero calculation ?!? - } + } + + } return -1; diff --git a/src/kernel/memory/PageDirectory.cpp b/src/kernel/memory/PageDirectory.cpp index f740680..5e4ab31 100644 --- a/src/kernel/memory/PageDirectory.cpp +++ b/src/kernel/memory/PageDirectory.cpp @@ -1,47 +1,43 @@ #include "PageDirectory.h" -#include + +void PageDirectory::enable() +{ - -void PageDirectory::enable(){ // https://wiki.osdev.org/Setting_Up_Paging //set each entry to not present - int i; - for(i = 0; i < 1024; i++) - { - // This sets the following flags to the pages: - // Supervisor: Only kernel-mode can access them - // Write Enabled: It can be both read from and written to - // Not Present: The page table is not present - this->page_directory[i] = 0x00000002; - } + // int i; + // for(i = 0; i < 1024; i++) + // { + // // This sets the following flags to the pages: + // // Supervisor: Only kernel-mode can access them + // // Write Enabled: It can be both read from and written to + // // Not Present: The page table is not present + // this->page_directory[i] = 0x00000002; + // } - // holds the physical address where we want to start mapping these pages to. - // in this case, we want to map these pages to the very beginning of memory. + // // holds the physical address where we want to start mapping these pages to. + // // in this case, we want to map these pages to the very beginning of memory. - //we will fill all 1024 entries in the table, mapping 4 megabytes - for(unsigned int i = 0; i < 1024; i++) - { - // As the address is page aligned, it will always leave 12 bits zeroed. - // Those bits are used by the attributes ;) - first_page_table[i] = (i * 0x1000) | 3; // attributes: supervisor level, read/write, present. - } + // //we will fill all 1024 entries in the table, mapping 4 megabytes + // for(unsigned int i = 0; i < 1024; i++) + // { + // // As the address is page aligned, it will always leave 12 bits zeroed. + // // Those bits are used by the attributes ;) + // first_page_table[i] = (i * 0x1000) | 3; // attributes: supervisor level, read/write, present. + // } - // attributes: supervisor level, read/write, present - this->page_directory[0] = ((unsigned int)first_page_table) | 3; + // // attributes: supervisor level, read/write, present + // this->page_directory[0] = ((unsigned int)first_page_table) | 3; + printf("Enable Paging!\n"); loadPageDirectory(this->page_directory); enablePaging(); } -/* -void IdentityPaging(uint32_t *first_pte, vaddr from, int size) + +void PageDirectory::MapPhysicalToVirtualAddress ( address_t PAddress , address_t VAddress, uint32_t size ) { - from = from & 0xFFFFF000; // Discard the bits we don't want - for (; size > 0; from += 4096, first_pte++) - { - *first_pte = from | 1; // makr page present. - } + } -*/ diff --git a/src/kernel/memory/PageDirectory.h b/src/kernel/memory/PageDirectory.h index a2863d3..c43c8fa 100644 --- a/src/kernel/memory/PageDirectory.h +++ b/src/kernel/memory/PageDirectory.h @@ -1,17 +1,18 @@ #pragma once #include - -extern "C" void loadPageDirectory (uint32_t* addr ); -extern "C" void enablePaging(); -typedef uintptr_t address_t; - - +#include "./memory.h" +#include "./../tty/kterm.h" #define KB 1024 + +typedef uintptr_t address_t; + static const int MAX_PAGES = 1024 * KB; // 4GB , 4kB/page static volatile address_t pmem_stack[MAX_PAGES]; static volatile address_t pmem_stack_top = MAX_PAGES; // top down allocation +extern "C" void loadPageDirectory (uint32_t* addr ); +extern "C" void enablePaging(); struct page_directory_entry {}; struct page_table_entry{}; @@ -21,8 +22,10 @@ struct page_table_entry{}; class PageDirectory { public: void enable (); - + void MapPhysicalToVirtualAddress ( address_t PAddress , address_t VAddress, uint32_t size ); + private: - uint32_t page_directory[1024] __attribute__((aligned(4096))); - uint32_t first_page_table[1024] __attribute__((aligned(4096))); + uint32_t page_directory[1024] __attribute__((aligned(4096))); // align on 4 kiloByte pages + uint32_t first_page_table[1024] __attribute__((aligned(4096))); // align on 4 kiloByte pages + }; \ No newline at end of file diff --git a/src/kernel/memory/PageFrameAllocator.cpp b/src/kernel/memory/PageFrameAllocator.cpp deleted file mode 100644 index f34c282..0000000 --- a/src/kernel/memory/PageFrameAllocator.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "PageFrameAllocator.h" - - -MemoryInfo memInfo {}; -void mapMultibootMemoryMap( multiboot_info_t *mbt){ - printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", - (unsigned) mbt->mmap_addr, (unsigned) mbt->mmap_length); - multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; - - for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ - - if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ - memInfo.memorySizeInBytes += mmap->len; - } else { - memInfo.reservedMemoryInBytes += mmap->len; - } - - print_Multiboot_memory_Map(mmap); - - } - uint32_t memorySizeInGiB = memInfo.memorySizeInBytes / 1073741824; - - printf("Available Memory: 0x%x bytes, 0x%x GiB\n", memInfo.memorySizeInBytes, memorySizeInGiB ); - printf("Reserved Memory: 0x%x bytes\n", memInfo.reservedMemoryInBytes ); - -} - -void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap){ - printf( - "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", - (unsigned) mmap->size, - (unsigned) (mmap->addr >> 32), - (unsigned) (mmap->addr & 0xffffffff), - (unsigned) (mmap->len >> 32), - (unsigned) (mmap->len & 0xffffffff), - (unsigned) mmap->type - ); -} \ No newline at end of file diff --git a/src/kernel/memory/PageFrameAllocator.h b/src/kernel/memory/PageFrameAllocator.h deleted file mode 100644 index 2b19180..0000000 --- a/src/kernel/memory/PageFrameAllocator.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include "../arch/i386/tty/kterm.h" - -#include -#include "../bootloader/multiboot.h" - -struct MemoryInfo{ - uint32_t memorySizeInBytes = 0; - uint32_t reservedMemoryInBytes = 0; -}; - - -extern void *kernel_begin; -extern void *kernel_end; - - - - -void print_Multiboot_memory_Map(multiboot_memory_map_t*); -void mapMultibootMemoryMap(multiboot_info_t*); \ No newline at end of file diff --git a/src/kernel/memory/PhysicalMemoryManager.cpp b/src/kernel/memory/PhysicalMemoryManager.cpp deleted file mode 100644 index 8e894ba..0000000 --- a/src/kernel/memory/PhysicalMemoryManager.cpp +++ /dev/null @@ -1,118 +0,0 @@ -#include "PhysicalMemoryManager.h" - -size_t mem_size = 0; -int used_blocks = 0; -size_t max_blocks = 0; -uint32_t* pmmap = 0; -size_t pmmap_size = 0; - - -void PhysicalMemoryManager_initialise(uint32_t physicalmemorymap_address, size_t size ) -{ - mem_size = size; - max_blocks = KB_TO_BLOCKS(mem_size); - - used_blocks = max_blocks; - - pmmap = (uint32_t*) physicalmemorymap_address; - - if(max_blocks % BLOCKS_PER_WORD) - pmmap_size++; - - memset(pmmap, 0xFF, pmmap_size); -} - -void PhysicalMemoryManager_region_initialise(uint32_t base, size_t size) -{ - size_t blocks = size /BLOCK_SIZE; - uint32_t align = base / BLOCK_SIZE; - - for(size_t i = 0 ; i < blocks; i ++) - { - bitmap_unset(pmmap, align++); - used_blocks--; - } - - bitmap_set(pmmap, 0); - -} - -void PhysicalMemoryManager_region_deinitialise(uint32_t base, size_t size ) -{ - size_t blocks = size / BLOCK_SIZE; - uint32_t align = base / BLOCK_SIZE; - - for(size_t i = 0 ; i < blocks; i++ ) - { - bitmap_set(pmmap, align++); - used_blocks++; - } - - -} - -void PhysicalMemoryManager_initialise_available_regions(uint32_t mmap_, uint32_t mmap_end_) -{ - multiboot_memory_map_t *mmap = (multiboot_memory_map_t*)mmap_; - multiboot_memory_map_t *mmap_end= (multiboot_memory_map_t*) mmap_end_; - - for(int i = 0; mmap < mmap_end ; mmap++, i++) - { - if(mmap->type == MULTIBOOT_MEMORY_AVAILABLE) - { - PhysicalMemoryManager_region_initialise((uint32_t) mmap->addr, (size_t) mmap->len); - } - } - -} - -void PhysicalMemoryManager_deinitialise_kernel() -{ - extern uint8_t kernel_begin; - extern uint8_t kernel_end; - - size_t kernel_size = (size_t) &kernel_end - (size_t) &kernel_begin; - - uint32_t pmmap_size_aligned = pmmap_size; - if(!IS_ALIGNED(pmmap_size_aligned, BLOCK_SIZE)) - { - pmmap_size_aligned = ALIGN(pmmap_size_aligned, BLOCK_SIZE); - } - - PhysicalMemoryManager_region_deinitialise((uint32_t) &kernel_begin, kernel_size); - PhysicalMemoryManager_region_deinitialise((uint32_t) &kernel_end, pmmap_size_aligned); - -} - -void* PhysicalMemoryManager_allocate_block() -{ - if(used_blocks - max_blocks <= 0) - { - return 0; - } - - int p_index = bitmap_first_unset(pmmap, p_index ); - - if(p_index == -1){ - return 0; - } - - bitmap_set(pmmap, p_index); - used_blocks++; - - return (void*) (BLOCK_SIZE * p_index); -} - -void PhysicalMemoryManager_free_block(void* p){ - if(p==0){ - return ; - } - - uint32_t p_addr = (uint32_t) p; - - int index = p_addr / BLOCK_SIZE; - bitmap_unset(pmmap, index); - - used_blocks--; - -} \ No newline at end of file diff --git a/src/kernel/memory/PhysicalMemoryManager.h b/src/kernel/memory/PhysicalMemoryManager.h deleted file mode 100644 index 3adc1eb..0000000 --- a/src/kernel/memory/PhysicalMemoryManager.h +++ /dev/null @@ -1,34 +0,0 @@ -#pragma once - -#include "../bootloader/multiboot.h" -#include -#include -#include "../../libc/include/mem.h" -#include "../kstructures/bitmap.h" - - -#define BLOCK_SIZE 4092 -#define BLOCKS_PER_WORD 32 - -#define KB_TO_BLOCKS(x) (((x) * 1024 ) / BLOCK_SIZE) -#define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) -#define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) - - -extern void PhysicalMemoryManager_initialise(uint32_t, size_t); - -extern void PhysicalMemoryManager_region_initialise(uint32_t, size_t); -extern void PhysicalMemoryManager_region_deinitialise(uint32_t,size_t); - -extern void PhysicalMemoryManager_initialise_available_regions(uint32_t, uint32_t); -extern void PhysicalMemoryManager_deinitialise_kernel(); - -extern void* PhysicalMemoryManager_allocate_block(); -extern void PhysicalMemoryManager_free_block(void* p); - - -extern size_t mem_size; -extern int used_blocks; -extern size_t max_blocks; -extern uint32_t* pmmap; -extern size_t pmmap_size ; \ No newline at end of file diff --git a/src/kernel/memory/SlabAllocator.h b/src/kernel/memory/SlabAllocator.h deleted file mode 100644 index b9f00df..0000000 --- a/src/kernel/memory/SlabAllocator.h +++ /dev/null @@ -1,33 +0,0 @@ -#pragma once -/** - * We'll need something to this effect to allocate memory in the kernel - * this will hopefully someday implement a full slab allocator - **/ -enum SlabState { - empty, - partial, - full -}; - -class CacheSlab { - const int SlabSize = 4000; - void* start = 0x0; -}; - - -class Allocator { - - public: - Allocator(); - ~Allocator(); - - void* kmalloc( int size ); - void kfree (void* address); - - private: - CacheSlab** _cache; - - - - -}; \ No newline at end of file diff --git a/src/kernel/memory/memory.cpp b/src/kernel/memory/memory.cpp new file mode 100644 index 0000000..b72e786 --- /dev/null +++ b/src/kernel/memory/memory.cpp @@ -0,0 +1,142 @@ +#include "./memory.h" +uint32_t* memoryBitMap; +/* + +*/ +void PhysicalMemory::setup( MemoryInfo* memory) { + + // calculate the maximum number of blocks + max_blocks = KB_TO_BLOCKS(memory->TotalMemory); + + used_blocks = 0; + + memoryBitMap = (uint32_t*) 0x00a00000; + + + printf("Maximum Number of blocks: 0x%x, Number of bytes for memMap: 0x%x\n", max_blocks , (max_blocks/8)); + + //Size of memory map + uint32_t memMap_size = (max_blocks / 8 ) ; + + printf("Memory Map size: 0x%x\n", memMap_size ); + printf("size of int in bytes: 0x%x \n" , sizeof(int)); + + // Set all places in memory as free + memset(memoryBitMap, 0xFF, memMap_size ); +} + +// NOTE: this can only give blocks of 4kb at a time! +void* PhysicalMemory::allocate_block() { + uint8_t blocks_available = max_blocks - used_blocks; + // Are there any blocks available? + if( blocks_available <= 0) + { + printf("No blocks available. Blocks Delta: 0x%x\n", blocks_available); + return 0; + } + + // Find 1 free block somewhere + int free_block_index = bitmap_first_unset(memoryBitMap, (max_blocks /8) /*memMap Size*/ ); + + + + if(free_block_index == -1) + { + printf("Could not find a good block!\n"); + // Could not find a block + return (void*)0xFFFF; + } + + if(free_block_index == 0) + printf("Somethings wrong!!!\n"); + + // Set the block to be used! + bitmap_unset(memoryBitMap, free_block_index); + // Increase the used_block count! + used_blocks++; + printf("used blocks: 0x%x\n", used_blocks); + // return the pointer to the physical address + return (void*) (BLOCK_SIZE * free_block_index); +} + + +void PhysicalMemory::free_block(void* p) { + // If it is a null pointer we don't need to do anything. + if(p==0) { + return; + } + // calculate the index into the bitmap + int index = ((uint32_t) p) / BLOCK_SIZE; + + // set the block to be free + bitmap_set(memoryBitMap, index); + used_blocks--; + printf("used blocks: 0x%x, after free\n", used_blocks); + +} + + + +void PhysicalMemory::allocate_region(uint32_t startAddress, uint32_t size) { + // every bit should be 4KiB + // every byte is 8*4KiB = 32KiB + + int NumberOfBlocksToAllocate = ( size / 1024) / 4 / 8 + 1; + int startBlock = (startAddress / 1024) / 4 / 8 ; + + // printf("NumberOfBlocksToAllocate: 0x%x\n", NumberOfBlocksToAllocate); + //printf( "start block: 0x%x\n" , startBlock); + for( int i = 0; i < NumberOfBlocksToAllocate; i++) + { + + //printf("ALLOCATE BLOCK: 0x%x\n" , startBlock + i ); + bitmap_unset(memoryBitMap, startBlock+ i); + used_blocks++; + } + + +} +void PhysicalMemory::deallocate_region(uint32_t StartAddress , uint32_t size ) { + // NOT IMPLEMENTED YET +} + + +void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt) { + printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", + (unsigned) mbt->mmap_addr, (unsigned) mbt->mmap_length); + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; + + for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + + if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ + + memInfo->TotalMemory += mmap->len; + } else { + memInfo->ReservedMemory += mmap->len; + } + + print_Multiboot_memory_Map(mmap); + + } + +} + + +/** + * @brief Debug Verbose functions + * + * @param mmap + */ + +void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap) { + printf( + "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", + (unsigned) mmap->size, + (unsigned) (mmap->addr >> 32), + (unsigned) (mmap->addr & 0xffffffff), + (unsigned) (mmap->len >> 32), + (unsigned) (mmap->len & 0xffffffff), + (unsigned) mmap->type + ); +} + diff --git a/src/kernel/memory/memory.h b/src/kernel/memory/memory.h new file mode 100644 index 0000000..2d0d309 --- /dev/null +++ b/src/kernel/memory/memory.h @@ -0,0 +1,48 @@ +#pragma once +#include +#include + +#include "memoryinfo.h" +#include "../bootloader/multiboot.h" +#include "../tty/kterm.h" +#include "../../libc/include/mem.h" +#include "../kstructures/bitmap.h" + +#define BLOCK_SIZE 4092 +#define BLOCKS_PER_WORD 32 // A word is 16 bit in x86 machines according to my google search results! + +#define KB_TO_BLOCKS(x) (x / BLOCK_SIZE) +#define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) +#define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) + +extern uint32_t kernel_begin; +extern uint32_t kernel_end; + +void initialise_available_regions(uint32_t memoryMapAddr, uint32_t memoryMapLastAddr, uint32_t* memoryBitMap, int* used_blocks); + +extern uint32_t* memoryBitMap; + +class PhysicalMemory +{ + public: + void setup(MemoryInfo* memory); + void destroy(); + void free_block(void* ptr); + void* allocate_block(); + void allocate_region(uint32_t, uint32_t); + void deallocate_region(uint32_t , uint32_t ); + + private: + size_t pmmap_size; + size_t max_blocks; + int used_blocks; +}; + +void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt); + +/** + * @brief Debug Verbose Functions + * + * @param mmap + */ +void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap); diff --git a/src/kernel/memory/memoryinfo.h b/src/kernel/memory/memoryinfo.h new file mode 100644 index 0000000..9bbb626 --- /dev/null +++ b/src/kernel/memory/memoryinfo.h @@ -0,0 +1,20 @@ +#pragma once +#include +#include + +struct MemoryArea{ + void* StartAddress; + size_t Size; + unsigned int type; + MemoryArea* Next; + +}__attribute__((packed)); + +struct MemoryInfo { + uint32_t TotalMemory; + uint32_t ReservedMemory; + MemoryArea* MemoryRegionList; +}__attribute__((packed)); + + + diff --git a/src/kernel/sv-terminal/superVisorTerminal.cpp b/src/kernel/sv-terminal/superVisorTerminal.cpp index 436fad2..b568208 100644 --- a/src/kernel/sv-terminal/superVisorTerminal.cpp +++ b/src/kernel/sv-terminal/superVisorTerminal.cpp @@ -1,6 +1,6 @@ #include "superVisorTerminal.h" -void startSuperVisorTerminal(){ +void startSuperVisorTerminal(BootInfo* bootinfo){ while (true){ printf("SUPERVISOR:>$ " ); @@ -40,7 +40,16 @@ void startSuperVisorTerminal(){ printf("========= Memory ==========\n"); printf("Kernel MemoryMap:\n"); printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); - printf("Frames used: 0x%x blocks of 4 KiB\n", used_blocks); + printf("Frames used: 0x%x blocks of 4 KiB\n", 0); + const int bytesInGiB = 1073741824; + int64_t bytesLeft = (bootinfo->memory->TotalMemory % bytesInGiB) / bytesInGiB; + int64_t effectiveNumberOfGib = bootinfo->memory->TotalMemory / bytesInGiB; + + int64_t GiBs = effectiveNumberOfGib + bytesLeft; + + printf("Available Memory: %d bytes, %d GiB\n", bootinfo->memory->TotalMemory, GiBs ); + printf("Reserved Memory: %d bytes\n", bootinfo->memory->ReservedMemory); + //printf("\n\n"); //PrintPhysicalMemoryAllocation( ); diff --git a/src/kernel/sv-terminal/superVisorTerminal.h b/src/kernel/sv-terminal/superVisorTerminal.h index 8f83a15..5d4519d 100644 --- a/src/kernel/sv-terminal/superVisorTerminal.h +++ b/src/kernel/sv-terminal/superVisorTerminal.h @@ -3,6 +3,7 @@ #include "../time.h" #include "../pit.h" #include "../keyboard/keyboard.h" -#include "../memory/physical/PhysicalMemoryManager.h" +#include "../memory/memory.h" +#include "../bootinfo.h" -void startSuperVisorTerminal(); \ No newline at end of file +void startSuperVisorTerminal(BootInfo * ); \ No newline at end of file diff --git a/src/libc/include/mem.h b/src/libc/include/mem.h index 62c4318..75e7cf8 100644 --- a/src/libc/include/mem.h +++ b/src/libc/include/mem.h @@ -1,8 +1,8 @@ inline void* memset (void* ptr, int value, size_t num){ for( int i = 0; i < num; i++ ) { - int* data = (int*)ptr+ i; - *data = value; + unsigned char* data = (unsigned char*)ptr+ i; + *data = (unsigned char)value; } return ptr; } diff --git a/todo.md b/todo.md index e69de29..d927cb1 100644 --- a/todo.md +++ b/todo.md @@ -0,0 +1,21 @@ +# TODO list + +![Todo image](https://camo.githubusercontent.com/c43d969d9d071c8342e9a69cdd6acb433c541f431127738974ce22290c46f2b8/68747470733a2f2f692e696d6775722e636f6d2f4f764d5a4273392e6a7067) + + +This list keeps me focused and organised so I don't forget what +needs to be done. It is a expansion on the features markdown file which describes the features. Here I put things I need to remember +to do on a more in depth level. + +## -- +[ ] Setup paging \ +[ ] HELP command +[ ] Setup a proper HEAP \ +[ ] Setup a proper Stack \ +[ ] Setup KMalloc and KFree \ +[ ] Merge Functioning Feature branches into sandboxKernelDev \ +[ ] Remove merged feature branches \ +[ ] Merge sandboxKernelDev with dev \ +[ ] Remove sandboxKernelDev branch \ +[ ] Implement proper virtual filesystem + -- 2.39.5 From a93bf566c8a65ca9a166f33943b90bbcbd848a94 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 12 Mar 2022 17:04:38 +0100 Subject: [PATCH 056/115] Added FAT-16 screenshot --- README.md | 3 +++ screenshots/ReadingFilesFromFAT16.png | 3 +++ 2 files changed, 6 insertions(+) create mode 100644 screenshots/ReadingFilesFromFAT16.png diff --git a/README.md b/README.md index 6e37240..ce638ec 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,9 @@ Enumerating the PCI bus ![ATAPI CD-ROM Identification](screenshots/CD-ROM_Identify.png) \ Correctly identified our ATAPI device 🎉 +![Reading Files from FAT-16](screenshots/ReadingFilesFromFAT16.png) \ +Reading a file from a FAT-16 Formatted drive + ________________________ ### The goal diff --git a/screenshots/ReadingFilesFromFAT16.png b/screenshots/ReadingFilesFromFAT16.png new file mode 100644 index 0000000..f203823 --- /dev/null +++ b/screenshots/ReadingFilesFromFAT16.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab26fe8f7b0d9fca81e8481a67796e93bbc2fb7369accac03a9aaecf415cd4de +size 27813 -- 2.39.5 From 2e2693d1ea64eaca8e3e358bfd627c2483f580b8 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 15 Mar 2022 21:56:32 +0100 Subject: [PATCH 057/115] Build some structures will need for the virtual filesystem --- .../EXT2/SuperBlock.h | 0 .../FAT/BiosParameterBlock.h | 0 .../FAT/DirectoryEntry.h | 0 .../FAT/ExtendBootRecord.h | 0 src/kernel/kernel.h | 6 +-- src/kernel/vfs/File.h | 9 ++++ src/kernel/vfs/VFS.cpp | 50 +++++++++++++++++++ src/kernel/vfs/VFS.h | 29 +++++++++++ 8 files changed, 91 insertions(+), 3 deletions(-) rename src/kernel/{filesytems => filesystems}/EXT2/SuperBlock.h (100%) rename src/kernel/{filesytems => filesystems}/FAT/BiosParameterBlock.h (100%) rename src/kernel/{filesytems => filesystems}/FAT/DirectoryEntry.h (100%) rename src/kernel/{filesytems => filesystems}/FAT/ExtendBootRecord.h (100%) create mode 100644 src/kernel/vfs/File.h create mode 100644 src/kernel/vfs/VFS.cpp create mode 100644 src/kernel/vfs/VFS.h diff --git a/src/kernel/filesytems/EXT2/SuperBlock.h b/src/kernel/filesystems/EXT2/SuperBlock.h similarity index 100% rename from src/kernel/filesytems/EXT2/SuperBlock.h rename to src/kernel/filesystems/EXT2/SuperBlock.h diff --git a/src/kernel/filesytems/FAT/BiosParameterBlock.h b/src/kernel/filesystems/FAT/BiosParameterBlock.h similarity index 100% rename from src/kernel/filesytems/FAT/BiosParameterBlock.h rename to src/kernel/filesystems/FAT/BiosParameterBlock.h diff --git a/src/kernel/filesytems/FAT/DirectoryEntry.h b/src/kernel/filesystems/FAT/DirectoryEntry.h similarity index 100% rename from src/kernel/filesytems/FAT/DirectoryEntry.h rename to src/kernel/filesystems/FAT/DirectoryEntry.h diff --git a/src/kernel/filesytems/FAT/ExtendBootRecord.h b/src/kernel/filesystems/FAT/ExtendBootRecord.h similarity index 100% rename from src/kernel/filesytems/FAT/ExtendBootRecord.h rename to src/kernel/filesystems/FAT/ExtendBootRecord.h diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 26f6fa5..ac164a3 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -28,9 +28,9 @@ extern "C" #include "ide/ide.h" #include "./drivers/IO/ata/ataDevice.h" #include "./PartitionTable/MBR/MasterBootRecord.h" -#include "./filesytems/FAT/BiosParameterBlock.h" -#include "./filesytems/FAT/ExtendBootRecord.h" -#include "./filesytems/FAT/DirectoryEntry.h" +#include "./filesystems/FAT/BiosParameterBlock.h" +#include "./filesystems/FAT/ExtendBootRecord.h" +#include "./filesystems/FAT/DirectoryEntry.h" #include "drivers/ACPI/rsdp.h" diff --git a/src/kernel/vfs/File.h b/src/kernel/vfs/File.h new file mode 100644 index 0000000..5a76c48 --- /dev/null +++ b/src/kernel/vfs/File.h @@ -0,0 +1,9 @@ +#pragma once + +class File { + +public: + virtual const File* Open () const ; // TODO: figure out a proper return value + virtual const char* Read() const; + virtual void Write(); +}; diff --git a/src/kernel/vfs/VFS.cpp b/src/kernel/vfs/VFS.cpp new file mode 100644 index 0000000..8eca77a --- /dev/null +++ b/src/kernel/vfs/VFS.cpp @@ -0,0 +1,50 @@ +#include "VFS.h" +/* + * TODO: Implement this!! + * + */ + + + +void VirtualFileSystem::Initialize(FS* root) +{ + root = root; +} + +void VirtualFileSystem::Open(const char* path) +{ + /* + What does this mean? + 1. Parse the path string + 2. Traverse the graph (Finding the correct Node) + 3. Create some kind of open file pointer thingy + */ +} + +void VirtualFileSystem::Read() +{ + // NOTE: we need some way to know what file we wish to read from +} + +void VirtualFileSystem::Write() +{ + // NOTE: we need some way to know what file we wish to write to +} + +void VirtualFileSystem::Mount(const char* path, FS* FileSystem) +{ + /* + What does this mean? + 1. Parse the path string + 2. Add a node to our internal graph + */ +} + +void VirtualFileSystem::UnMount(FS* FileSystem) +{ + /* + What does this mean? + 1. Parse the path string + 2. Remve a node to our internal graph + */ +} \ No newline at end of file diff --git a/src/kernel/vfs/VFS.h b/src/kernel/vfs/VFS.h new file mode 100644 index 0000000..b525cc2 --- /dev/null +++ b/src/kernel/vfs/VFS.h @@ -0,0 +1,29 @@ +#pragma once + +class VirtualFileSystem{ +public: + void Initialize( FS* root); + void Open (const char* path); + void Read(); + void Write(); + + void Mount(const char* path,FS* FileSystem); + void UnMount(FS* FileSystem); + +private: + FS* root; + + +}; + +struct FS +{ + const char* name ; + int DeviceID; + int ManufacturerID; + FS* next; + char**(Read)(); + void*(Write)(); + void*(Open)(); +}; + -- 2.39.5 From 23c68d9863ad8ebfd436b94640b6f03914b5eb5e Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 18 Mar 2022 22:09:04 +0100 Subject: [PATCH 058/115] Setup paging function signatures... Ready to be implemented. --- Makefile | 5 ++- src/kernel/filesystems/FAT/FAT16.cpp | 0 src/kernel/filesystems/FAT/FAT16.h | 8 ++++ src/kernel/kernel.cpp | 3 ++ src/kernel/kernel.h | 1 + src/kernel/memory/PageDirectory.cpp | 43 -------------------- src/kernel/memory/PageDirectory.h | 31 --------------- src/kernel/memory/paging.cpp | 49 +++++++++++++++++++++++ src/kernel/memory/paging.definitions.h | 55 ++++++++++++++++++++++++++ src/kernel/memory/paging.h | 21 ++++++++++ 10 files changed, 141 insertions(+), 75 deletions(-) create mode 100644 src/kernel/filesystems/FAT/FAT16.cpp create mode 100644 src/kernel/filesystems/FAT/FAT16.h delete mode 100644 src/kernel/memory/PageDirectory.cpp delete mode 100644 src/kernel/memory/PageDirectory.h create mode 100644 src/kernel/memory/paging.cpp create mode 100644 src/kernel/memory/paging.definitions.h create mode 100644 src/kernel/memory/paging.h diff --git a/Makefile b/Makefile index c1b4aa0..eea8447 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -O2 -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o SRC_DIR = src BUILD_DIR = build @@ -96,3 +96,6 @@ $(BUILD_DIR)/sv-terminal.o: $(BUILD_DIR)/memory.o: $(CPP) -c $(SRC_DIR)/kernel/memory/memory.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/paging.o: + $(CPP) -c $(SRC_DIR)/kernel/memory/paging.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file diff --git a/src/kernel/filesystems/FAT/FAT16.cpp b/src/kernel/filesystems/FAT/FAT16.cpp new file mode 100644 index 0000000..e69de29 diff --git a/src/kernel/filesystems/FAT/FAT16.h b/src/kernel/filesystems/FAT/FAT16.h new file mode 100644 index 0000000..bc24274 --- /dev/null +++ b/src/kernel/filesystems/FAT/FAT16.h @@ -0,0 +1,8 @@ +#pragma once +#include "../../vfs/File.h" + + +class FAT16 : File { +public: + +}; \ No newline at end of file diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 9e78828..7d15fcf 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -4,6 +4,9 @@ extern "C" void kernel_main (BootInfo* bootinfo) { init_serial(); pit_initialise(); + InitializePaging(); + //Enable(); + startSuperVisorTerminal(bootinfo); } diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 604c4ff..c3b257b 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -14,6 +14,7 @@ extern "C" #include "memory/memory.h" #include "memory/memoryinfo.h" +#include "memory/paging.h" #include "bootcheck.h" #include "gdt/gdtc.h" diff --git a/src/kernel/memory/PageDirectory.cpp b/src/kernel/memory/PageDirectory.cpp deleted file mode 100644 index 5e4ab31..0000000 --- a/src/kernel/memory/PageDirectory.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include "PageDirectory.h" - -void PageDirectory::enable() -{ - - - // https://wiki.osdev.org/Setting_Up_Paging - //set each entry to not present - // int i; - // for(i = 0; i < 1024; i++) - // { - // // This sets the following flags to the pages: - // // Supervisor: Only kernel-mode can access them - // // Write Enabled: It can be both read from and written to - // // Not Present: The page table is not present - // this->page_directory[i] = 0x00000002; - // } - - // // holds the physical address where we want to start mapping these pages to. - // // in this case, we want to map these pages to the very beginning of memory. - - // //we will fill all 1024 entries in the table, mapping 4 megabytes - // for(unsigned int i = 0; i < 1024; i++) - // { - // // As the address is page aligned, it will always leave 12 bits zeroed. - // // Those bits are used by the attributes ;) - // first_page_table[i] = (i * 0x1000) | 3; // attributes: supervisor level, read/write, present. - // } - - // // attributes: supervisor level, read/write, present - // this->page_directory[0] = ((unsigned int)first_page_table) | 3; - - printf("Enable Paging!\n"); - - loadPageDirectory(this->page_directory); - enablePaging(); -} - - -void PageDirectory::MapPhysicalToVirtualAddress ( address_t PAddress , address_t VAddress, uint32_t size ) -{ - -} diff --git a/src/kernel/memory/PageDirectory.h b/src/kernel/memory/PageDirectory.h deleted file mode 100644 index c43c8fa..0000000 --- a/src/kernel/memory/PageDirectory.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -#include -#include "./memory.h" -#include "./../tty/kterm.h" -#define KB 1024 - - -typedef uintptr_t address_t; - -static const int MAX_PAGES = 1024 * KB; // 4GB , 4kB/page -static volatile address_t pmem_stack[MAX_PAGES]; -static volatile address_t pmem_stack_top = MAX_PAGES; // top down allocation - -extern "C" void loadPageDirectory (uint32_t* addr ); -extern "C" void enablePaging(); - -struct page_directory_entry {}; -struct page_table_entry{}; - - - -class PageDirectory { - public: - void enable (); - void MapPhysicalToVirtualAddress ( address_t PAddress , address_t VAddress, uint32_t size ); - - private: - uint32_t page_directory[1024] __attribute__((aligned(4096))); // align on 4 kiloByte pages - uint32_t first_page_table[1024] __attribute__((aligned(4096))); // align on 4 kiloByte pages - -}; \ No newline at end of file diff --git a/src/kernel/memory/paging.cpp b/src/kernel/memory/paging.cpp new file mode 100644 index 0000000..6f50e3c --- /dev/null +++ b/src/kernel/memory/paging.cpp @@ -0,0 +1,49 @@ +#include "paging.h" +PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]; + +void InitializePaging() +{ + // Identity map the first 8MB ... Physical addresses 0x00000000 to 0x007A1200 + + + // Identity map the kernel space || our map to 3GB space + + + // Identity map VGA memory + + +} + + +void AllocatePage(VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) +{ + +} + + +void FreePage(VIRTUAL_ADDRESS vaddr , PageDirectoryEntry& page_directory) +{ + +} + + +void Map ( PHYSICAL_ADDRESS paddr, VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) +{ + +} + +void Unmap(VIRTUAL_ADDRESS, PageDirectoryEntry& page_directory) +{ + // NOTE: I will implement lazy unmapping for now + +} + + +void Enable() +{ + printf("Load into CR3 address: 0x%x\n", (uint32_t)(&kernel_directory[0])); + loadPageDirectory(&kernel_directory[0]); + enablePaging(); + + printf("Paging enabled!\n"); +} diff --git a/src/kernel/memory/paging.definitions.h b/src/kernel/memory/paging.definitions.h new file mode 100644 index 0000000..bd9c089 --- /dev/null +++ b/src/kernel/memory/paging.definitions.h @@ -0,0 +1,55 @@ +#pragma once +#include +/* + This file contains some handy definitions for different types + that have to do with paging in atleast 32 bit and maybe sometime in the future + also 64 bit mode. +*/ + + + +#define MAX_DIRECTORY_ENTRIES 1024 +#define MAX_PAGE_TABLE_ENTRIES 1024 +#define MAX_PAGES 1024 + +#define PHYSICAL_ADDRESS uint32_t +#define VIRTUAL_ADDRESS uint32_t + +#define PageDirectoryEntry uint32_t +#define PageTableEntry uint32_t + + + + +// NOTE: FIXME: I am fairly certain these masks are off by one! + +#define PD32_PRESENT_MASK (0x1 << 0) +#define PD32_READ_WRITE_MASK (0x1 << 1) +#define PD32_SUPERVISOR_MASK (0x1 << 2) +#define PD32_WRITE_THROUGH_MASK (0x1 << 3) +#define PD32_CACHE_DISABLE_MASK (0x1 << 4) +#define PD32_ACCESSED_MASK (0x1 << 5) +#define PD32_AVAILABLE_1_4KB_MASK (0x1 << 6) +#define PD32_DISABLE_4MB_MASK (0x1 << 6) +#define PD32_PAGE_SIZE_MASK (0x1 << 7) +#define PD32_GLOBAL_4MB_MASK (0x1 << 8) +#define PD32_AVAILABLE_2_4MB_MASK ( 14 << 9) +#define PD32_AVAILABLE_2_4KB_MASK ( 15 << 8) +#define PD32_ADDRESS_4KB_MASK (0x8FFFF << 12) +#define PD32_PAGE_ATTRIBUTE_TABLE_4MB_MASK (0x1 << 12) +#define PD32_HIGH_HALF_ADDRESS_4MB_MASK (0x7F<< 13) +#define PD32_RESERVED_4MB_MASK (0x1 << 21) +#define PD32_LOWER_HALF_ADDRESS_4MB_MASK (0x1FF << 22) + +#define PT32_PRESENT_MASK (0x1 << 0) +#define PT32_READ_WRITE_MASK (0x1 << 1) +#define PT32_SUPERVISOR_MASK (0x1 << 2) +#define PT32_WRITE_THROUGH_MASK (0x1 << 3) +#define PT32_CACHE_DISABLE_MASK (0x1 << 4) +#define PT32_ACCESSED_MASK (0x1 << 5) +#define PT32_DIRTY_MASK (0x1 << 6) +#define PT32_PAGE_ATTRIBUTE_TABLE_MASK (0x1 << 7) +#define PT32_GLOBAL_MASK (0x1 << 8) +#define PT32_AVAILABLE_MASK (0x7 << 9) +#define PT32_CACHE_DISABLE_MASK (0x7FFFF << 12) + diff --git a/src/kernel/memory/paging.h b/src/kernel/memory/paging.h new file mode 100644 index 0000000..04aa2fb --- /dev/null +++ b/src/kernel/memory/paging.h @@ -0,0 +1,21 @@ +#pragma once +#include "./memory.h" +#include "./../tty/kterm.h" +#include "paging.definitions.h" + + +extern "C" void loadPageDirectory (uint32_t* addr ); +extern "C" void enablePaging(); + +void InitializePaging(); + +void Enable(); + +void AllocatePage(VIRTUAL_ADDRESS, PageDirectoryEntry&); + + +void FreePage(VIRTUAL_ADDRESS, PageDirectoryEntry&); + + +void Map(PHYSICAL_ADDRESS, VIRTUAL_ADDRESS, PageDirectoryEntry&); +void Unmap (VIRTUAL_ADDRESS, PageDirectoryEntry&); -- 2.39.5 From 9172da075af71d4c03cc60267e5acb0ec7d88f31 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 15 Aug 2022 19:51:22 +0200 Subject: [PATCH 059/115] Added identity paging basics Followed wiki.osdev.org/Setting_Up_Paging --- src/kernel/kernel.cpp | 11 +++-- src/kernel/memory/paging.cpp | 79 ++++++++++++++++++++++++++++++++---- src/kernel/memory/paging.h | 3 -- 3 files changed, 77 insertions(+), 16 deletions(-) diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 7d15fcf..12d1c79 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -4,7 +4,7 @@ extern "C" void kernel_main (BootInfo* bootinfo) { init_serial(); pit_initialise(); - InitializePaging(); + //InitializePaging(); //Enable(); startSuperVisorTerminal(bootinfo); @@ -90,8 +90,7 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ memAlloc.allocate_region(kernel_end, kernel_end - kernel_begin); // test alloc_block - - + /* uint8_t* memory = (uint8_t*) memAlloc.allocate_block(); printf("Got a new pointer: 0x%x\n", memory); @@ -102,13 +101,13 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ memAlloc.free_block((void*) memory); uint8_t* newBlockPlse = (uint8_t*) memAlloc.allocate_block(); - + */ // memAlloc.free_block((void*) memory); - - + InitializePaging(); + Enable(); } initGDT(); diff --git a/src/kernel/memory/paging.cpp b/src/kernel/memory/paging.cpp index 6f50e3c..9ea4859 100644 --- a/src/kernel/memory/paging.cpp +++ b/src/kernel/memory/paging.cpp @@ -1,16 +1,79 @@ #include "paging.h" -PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]; +PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]__attribute__((aligned(4096))); +PageTableEntry first_page_table[1024]__attribute__((aligned(4096))); + +#define KERNEL_VRT_MEMORY_BEGIN 0xC0000000 +#define KERNEL_VRT_MEMORY_END 0xCFFFFFFF +#define PAGE_SIZE 0xFA0; + void InitializePaging() { + + + printf("\nInit paging\n"); + // The basics as explained by wiki.osdev.org + + // Set all page_directories to not present + int i = 0; + while ( i < 1024) + { + kernel_directory[i] = 0x00000002; + i++; + } + + + // map 4 megabytes + unsigned int j ; + for( j = 0; j < 1024; j++ ) + { + first_page_table[j] = (j * 0x1000) | 3 ; + /* + Attributes: + Supervisor Level , + read/write, + present, + */ + + } + + // Put the page table in the page directory + // attributes: supervisor level, read/write, present; + kernel_directory[0] = ((unsigned int)first_page_table) | 3; + + printf("Init paging DONE\n"); + // NOTE: Adjust this as needed + + // BIOS Address Identity mapping // Identity map the first 8MB ... Physical addresses 0x00000000 to 0x007A1200 + /* + + PHYSICAL_ADDRESS BIOSAddr = 0x00000000; + PHYSICAL_ADDRESS BIOSAddr_Max = 0x007A1200; + + do + { + Map( BIOSAddr, BIOSAddr, *kernel_directory); + BIOSAddr += PAGE_SIZE + } while(BIOSAddr <= BIOSAddr_Max); + + // Identity map the kernel space + VIRTUAL_ADDRESS Vaddr = KERNEL_VRT_MEMORY_BEGIN; + PHYSICAL_ADDRESS KernelAddr = kernel_begin; + + do + { + Map(KernelAddr, Vaddr , *kernel_directory); + + Vaddr += PAGE_SIZE; + KernelAddr += PAGE_SIZE + + } + while(KernelAddr < kernel_end); - // Identity map the kernel space || our map to 3GB space - - - // Identity map VGA memory - + //TODO: Identity map VGA memory + */ } @@ -30,9 +93,11 @@ void FreePage(VIRTUAL_ADDRESS vaddr , PageDirectoryEntry& page_directory) void Map ( PHYSICAL_ADDRESS paddr, VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) { + + } -void Unmap(VIRTUAL_ADDRESS, PageDirectoryEntry& page_directory) +void Unmap(VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) { // NOTE: I will implement lazy unmapping for now diff --git a/src/kernel/memory/paging.h b/src/kernel/memory/paging.h index 04aa2fb..789574e 100644 --- a/src/kernel/memory/paging.h +++ b/src/kernel/memory/paging.h @@ -12,10 +12,7 @@ void InitializePaging(); void Enable(); void AllocatePage(VIRTUAL_ADDRESS, PageDirectoryEntry&); - - void FreePage(VIRTUAL_ADDRESS, PageDirectoryEntry&); - void Map(PHYSICAL_ADDRESS, VIRTUAL_ADDRESS, PageDirectoryEntry&); void Unmap (VIRTUAL_ADDRESS, PageDirectoryEntry&); -- 2.39.5 From 388ac8e7f95ce2dacf8bdaf283a18ce6d77e49b1 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 16 Aug 2022 19:06:16 +0200 Subject: [PATCH 060/115] Added checks to be sure paging is actually enabled on the cpu. - Made a special assembly file to put CPU check function in. E.G. functions to get the state of specific registers In this case I have created a simple assembly function to get the contents of the CR0 register. With the help of the c++ preprocessor the value can then be used to check if certains bits are set. For example to check if the PG (paging) bit is set, indicating that paging is enabled for the processor. --- src/kernel/boot.s | 2 +- src/kernel/cpu.h | 68 +++++++++++++++++++++++++++--------- src/kernel/cpu.s | 25 +++++++++++++ src/kernel/memory/paging.cpp | 24 ++++++++++++- src/kernel/memory/paging.h | 4 ++- src/kernel/paging.s | 28 +++++++++++++-- 6 files changed, 130 insertions(+), 21 deletions(-) create mode 100644 src/kernel/cpu.s diff --git a/src/kernel/boot.s b/src/kernel/boot.s index 4b38316..4e4ba36 100644 --- a/src/kernel/boot.s +++ b/src/kernel/boot.s @@ -26,7 +26,7 @@ stack_top: .include "./src/kernel/irq_table.s" .include "./src/kernel/idt/idt.s" .include "./src/kernel/paging.s" - +.include "./src/kernel/cpu.s" .global _start .type _start, @function diff --git a/src/kernel/cpu.h b/src/kernel/cpu.h index 6e9f95a..cd241c7 100644 --- a/src/kernel/cpu.h +++ b/src/kernel/cpu.h @@ -1,17 +1,53 @@ -#include // NOTE: Only available in GCC -// NOT currently usefull! -/* static int get_model(){ - int ebx, unused; - __cpuid(0, unused, ebx, unused, unused); - return ebx; - } +#pragma once - enum { - CPUID_FEAT_EDX_APIC = 1 << 9 - }; - static int check_apic (){ - unsigned int eax, unused, edx; - __get_cpuid(1, &eax, &unused, &unused, &edx); - return edx & CPUID_FEAT_EDX_APIC; - } -*/ \ No newline at end of file +/* +Based on Intel specifications. + +C++ interface for the cpu.s assembly file. + +©Nigel Barink - 2022 +*/ + + +/* +* EFLAGS FUNCTIONS +*/ + +extern "C" uint32_t GetEFLAGS(); + + + +/* +* CONTROL_REGISTER_0 FUNCTIONS +*/ +extern "C" uint32_t GetCR0(); + +/* + struct CR0_Register { + uint8_t PE :1; // Protection Mode Enabled 0 + uint8_t MP :1; // Monitor co-processor 1 + uint8_t EM :1; // Emulation 2 + uint8_t TS :1; // Task switched 3 + uint8_t ET :1; // Extension Type 4 + uint8_t NE :1; // Numeric error 5 + uint16_t Reserved :10; // 6,7,8,9,10,11,12,13,14,15 + uint8_t WP :1; // Write Protect 16 + uint8_t Reserved :1; // 17 + uint8_t AM :1; // Alligment Task 18 + uint16_t Reserved :10; // 19,20,21,22,23,24,25,26,27,28 + uint8_t NW :1; // Not-write through 29 + uint8_t CD :1; // Cache disable 30 + uint8_t PG :1; // Paging 31 + };*/ + + + +#define GET_PE_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0&0x1) +#define GET_MP_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0&0x2) +#define GET_EM_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0&0x3) +#define GET_TS_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0&0x4) +#define GET_ET_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0&0x5) +#define GET_NE_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0&0x6) + + +#define GET_PG_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0>>31) \ No newline at end of file diff --git a/src/kernel/cpu.s b/src/kernel/cpu.s new file mode 100644 index 0000000..aa662dd --- /dev/null +++ b/src/kernel/cpu.s @@ -0,0 +1,25 @@ +# Basic cpu functions +.globl GetCR0 +GetCR0: + push %ebp # save the base pointer on the stack + mov %esp, %ebp # Set the base pointer to the current stack pointer + + xor %eax, %eax # Clear EAX to make sure no weird stuff is going on + mov %cr0, %eax # Copy the value of the CR0 register into EAX + + mov %ebp, %esp # restore the base pointer + pop %ebp + ret + +.globl GetEFLAGS +GetEFLAGS: + push %ebp + mov %esp, %ebp + + xor %eax, %eax + pushfl # Push the EFLAGS register content onto the stack, should be pushfd but GAS apparently doesn't agree + mov 4(%esp) , %eax + + mov %ebp, %esp + pop %ebp + ret \ No newline at end of file diff --git a/src/kernel/memory/paging.cpp b/src/kernel/memory/paging.cpp index 9ea4859..70dd0a6 100644 --- a/src/kernel/memory/paging.cpp +++ b/src/kernel/memory/paging.cpp @@ -2,6 +2,9 @@ PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]__attribute__((aligned(4096))); PageTableEntry first_page_table[1024]__attribute__((aligned(4096))); + + + #define KERNEL_VRT_MEMORY_BEGIN 0xC0000000 #define KERNEL_VRT_MEMORY_END 0xCFFFFFFF #define PAGE_SIZE 0xFA0; @@ -105,10 +108,29 @@ void Unmap(VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) void Enable() -{ +{ + + //TODO: Write protect will not be turned on + // for the moment altough according to the intel + // developer manual this should happen. + + uint32_t CR0; + + CR0 = GetCR0(); + printf("PG bit = %d \n" , GET_PG_BIT(CR0)); + printf("Load into CR3 address: 0x%x\n", (uint32_t)(&kernel_directory[0])); loadPageDirectory(&kernel_directory[0]); enablePaging(); printf("Paging enabled!\n"); + + + CR0 = GetCR0(); + printf("PG bit = %d \n" , GET_PG_BIT(CR0) ); + + + uint32_t EFLAGS = GetEFLAGS(); + + } diff --git a/src/kernel/memory/paging.h b/src/kernel/memory/paging.h index 789574e..612c757 100644 --- a/src/kernel/memory/paging.h +++ b/src/kernel/memory/paging.h @@ -2,7 +2,7 @@ #include "./memory.h" #include "./../tty/kterm.h" #include "paging.definitions.h" - +#include "../cpu.h" extern "C" void loadPageDirectory (uint32_t* addr ); extern "C" void enablePaging(); @@ -16,3 +16,5 @@ void FreePage(VIRTUAL_ADDRESS, PageDirectoryEntry&); void Map(PHYSICAL_ADDRESS, VIRTUAL_ADDRESS, PageDirectoryEntry&); void Unmap (VIRTUAL_ADDRESS, PageDirectoryEntry&); + + diff --git a/src/kernel/paging.s b/src/kernel/paging.s index fa25003..ca25a7d 100644 --- a/src/kernel/paging.s +++ b/src/kernel/paging.s @@ -1,10 +1,17 @@ +# NOTE: I wish this wasn't AT&T Syntax its horrible +# REMINDER: INSTRUCTION FROM_REGISTER, TO_REGISTER .globl enablePaging enablePaging: + # Create a new call frame push %ebp mov %esp, %ebp + + # Set the PG bit of CR0 mov %cr0, %eax or $0x80000000, %eax mov %eax, %cr0 + + # Restore to the previous call frame mov %ebp, %esp pop %ebp ret @@ -13,8 +20,25 @@ enablePaging: loadPageDirectory: push %ebp mov %esp, %ebp - mov 8(%esp), %eax - mov %eax, %cr3 + + /* NOTE: We should probably check if paging is already enabled. + Changing the CR3 register whilst paging is enabled might + result in unwanted behaviour (in the worst case) or cause a + fault (in the best case). + */ + + mov 8(%esp), %eax # Move the first argument in the eax register + + mov %eax, %cr3 # Move the value of eax into the CR3 register + + /* + Moving the value of the argument passed to this function + into the CR3 register will allow the MMU to access the paging + structure we setup in memory once we enable paging + */ + mov %ebp, %esp pop %ebp ret + + -- 2.39.5 From 0b0e37b76253195c57100efc827e7bb7178d14ff Mon Sep 17 00:00:00 2001 From: Nigel Date: Wed, 17 Aug 2022 14:17:58 +0200 Subject: [PATCH 061/115] Paging cleanup, more cpu testing and psuedo code for higher half kernel --- src/kernel/cpu.h | 11 ++- src/kernel/cpu.s | 14 +++ src/kernel/idt/idt.cpp | 21 ++++- src/kernel/kernel.cpp | 5 +- src/kernel/memory/paging.cpp | 126 ++++++++++++++++--------- src/kernel/memory/paging.definitions.h | 5 +- src/kernel/memory/paging.h | 2 + 7 files changed, 130 insertions(+), 54 deletions(-) diff --git a/src/kernel/cpu.h b/src/kernel/cpu.h index cd241c7..97b50ab 100644 --- a/src/kernel/cpu.h +++ b/src/kernel/cpu.h @@ -50,4 +50,13 @@ extern "C" uint32_t GetCR0(); #define GET_NE_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0&0x6) -#define GET_PG_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0>>31) \ No newline at end of file +#define GET_PG_BIT(CONTROL_REGISTER_0) (CONTROL_REGISTER_0>>31) + +/* +* CONTROL_REGISTER_4 FUNCTIONS +*/ + +extern "C" uint32_t GetCR4(); + +#define GET_PSE_BIT(CONTROL_REGISTER_4) (CONTROL_REGISTER_4&0x4) +#define GET_PAE_BIT(CONTROL_REGISTER_4) (CONTROL_REGISTER_4&0x5) diff --git a/src/kernel/cpu.s b/src/kernel/cpu.s index aa662dd..9a40270 100644 --- a/src/kernel/cpu.s +++ b/src/kernel/cpu.s @@ -11,6 +11,20 @@ GetCR0: pop %ebp ret +.globl GetCR4 +GetCR4: + push %ebp + mov %esp, %ebp + + xor %eax, %eax + mov %cr4, %eax + + mov %ebp, %esp + pop %ebp + ret + + + .globl GetEFLAGS GetEFLAGS: push %ebp diff --git a/src/kernel/idt/idt.cpp b/src/kernel/idt/idt.cpp index 393902b..cc3db0c 100644 --- a/src/kernel/idt/idt.cpp +++ b/src/kernel/idt/idt.cpp @@ -128,9 +128,24 @@ void irs_handler (registers regs) { case 14: // Page Fault Exception #PF printf("#PF\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + + printf("EIP: 0x%x\n", regs.eip); // Points to faulting instruction ??? + printf("EAX: 0x%x\n", regs.eax); + printf("EBP: 0x%x\n", regs.ebp); // Base pointer pointing to the bottom of the stack + + + // Error code of 32 bits are on the stack + // CR2 register contains the 32-bit linear address that generated the exception + // See Intel Software Developers manual Volume 3A Part 1 page 236 for more info + + + /* + Check the error code to figure out what happened here + */ + + + + break; case 16: diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 12d1c79..25666ef 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -105,8 +105,9 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ - // memAlloc.free_block((void*) memory); - InitializePaging(); + //memAlloc.free_block((void*) memory); + //InitializePaging(); + IdentityMap(); Enable(); } diff --git a/src/kernel/memory/paging.cpp b/src/kernel/memory/paging.cpp index 70dd0a6..67df499 100644 --- a/src/kernel/memory/paging.cpp +++ b/src/kernel/memory/paging.cpp @@ -1,27 +1,17 @@ #include "paging.h" PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]__attribute__((aligned(4096))); -PageTableEntry first_page_table[1024]__attribute__((aligned(4096))); +PageTableEntry first_page_table[MAX_PAGE_TABLE_ENTRIES]__attribute__((aligned(4096))); - - -#define KERNEL_VRT_MEMORY_BEGIN 0xC0000000 -#define KERNEL_VRT_MEMORY_END 0xCFFFFFFF -#define PAGE_SIZE 0xFA0; - - -void InitializePaging() -{ - - - printf("\nInit paging\n"); +void IdentityMap (){ + printf("\nInit paging\n"); // The basics as explained by wiki.osdev.org // Set all page_directories to not present int i = 0; while ( i < 1024) { - kernel_directory[i] = 0x00000002; + kernel_directory[i] = 0x2; i++; } @@ -31,12 +21,12 @@ void InitializePaging() for( j = 0; j < 1024; j++ ) { first_page_table[j] = (j * 0x1000) | 3 ; - /* - Attributes: - Supervisor Level , - read/write, - present, - */ + + //Attributes: + //Supervisor Level , + //read/write, + //present, + } @@ -45,38 +35,75 @@ void InitializePaging() kernel_directory[0] = ((unsigned int)first_page_table) | 3; printf("Init paging DONE\n"); - // NOTE: Adjust this as needed - - // BIOS Address Identity mapping - // Identity map the first 8MB ... Physical addresses 0x00000000 to 0x007A1200 +} + +void InitializePaging() +{ /* - - PHYSICAL_ADDRESS BIOSAddr = 0x00000000; - PHYSICAL_ADDRESS BIOSAddr_Max = 0x007A1200; - - do + Initial kernel page directory + set all page tables to not present + */ + for (int i = 0; i < MAX_DIRECTORY_ENTRIES; i++) { - Map( BIOSAddr, BIOSAddr, *kernel_directory); - BIOSAddr += PAGE_SIZE - } while(BIOSAddr <= BIOSAddr_Max); + kernel_directory[i] = 0x2; + } - // Identity map the kernel space + // BIOS Address Identity mapping + // Identity map the first 8MiB ... Physical addresses 0x00000000 to 0x007A1200 + PHYSICAL_ADDRESS BIOSAddr = 0x00000000; + PHYSICAL_ADDRESS BIOSAddr_Max = 0x800000; + + // How many PDE's do we need + uint8_t NUM_PDE = BIOSAddr_Max / (4 * 1024 * 1024); + + printf("The first 8MiB require %d Page Directory Entries\n", NUM_PDE); +/* + for( int i = 0; i < NUM_PDE; i++) + { + // setup a page table + PageTableEntry pagetable[MAX_PAGE_TABLE_ENTRIES] = PhysicalMemory::allocate_block(); // TODO :: Physical memory manager functions should be available here. + + for(int j = 0; j < MAX_PAGE_TABLE_ENTRIES; j++) + { + pagetable[j] = ( j * 4096 ) | 3; + } + + // add page table as page directory entry + kernel_directory[i] = ( (unsigned int) pagetable ) | 3; + } +*/ + // map the kernel space VIRTUAL_ADDRESS Vaddr = KERNEL_VRT_MEMORY_BEGIN; PHYSICAL_ADDRESS KernelAddr = kernel_begin; + PHYSICAL_ADDRESS KernelEndAddr = kernel_end; - do + uint32_t KernelSizeInBytes = (KernelEndAddr - KernelAddr); + printf("Kernel is 0x%x bytes\n", KernelSizeInBytes); + NUM_PDE = KernelSizeInBytes / (4 * 1024* 1024); + printf("Kernel requires %d Page Directory Entries\n", NUM_PDE); + +/* + for(int i = 0; i < NUM_PDE; i++) { - Map(KernelAddr, Vaddr , *kernel_directory); + PageTableEntry pageTable [MAX_PAGE_TABLE_ENTRIES] = PhysicalMemory::allocate_block(); + + for(int j = 0; j < MAX_PAGE_TABLE_ENTRIES; j++) + { + pageTable[j] = ( j * 4096) | 3; // NOTE: Check if page is actually supposed to be present + } + + // TODO: Calculate Page Directory index + - Vaddr += PAGE_SIZE; - KernelAddr += PAGE_SIZE } - while(KernelAddr < kernel_end); + */ + + - //TODO: Identity map VGA memory - */ + // Identity map VGA memory + // Calc which PDE adn } @@ -86,13 +113,11 @@ void AllocatePage(VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) } - void FreePage(VIRTUAL_ADDRESS vaddr , PageDirectoryEntry& page_directory) { } - void Map ( PHYSICAL_ADDRESS paddr, VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) { @@ -106,7 +131,6 @@ void Unmap(VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) } - void Enable() { @@ -127,10 +151,20 @@ void Enable() CR0 = GetCR0(); - printf("PG bit = %d \n" , GET_PG_BIT(CR0) ); + uint32_t CR4 = GetCR4(); + printf("PG bit = %d\n" , GET_PG_BIT(CR0) ); + printf("PAE bit = %d\n", GET_PAE_BIT(CR4)); + if(GET_PAE_BIT(CR4) == 0){ + printf("Using 32bit paging\n"); - uint32_t EFLAGS = GetEFLAGS(); - + if(GET_PSE_BIT(CR4) == 0 ){ + printf("Page size is 4KiB\n"); + } else { + printf("Page size is 4MiB\n"); + } + } else { + printf("Using some extended version for paging\n"); + } } diff --git a/src/kernel/memory/paging.definitions.h b/src/kernel/memory/paging.definitions.h index bd9c089..2f771f7 100644 --- a/src/kernel/memory/paging.definitions.h +++ b/src/kernel/memory/paging.definitions.h @@ -6,8 +6,6 @@ also 64 bit mode. */ - - #define MAX_DIRECTORY_ENTRIES 1024 #define MAX_PAGE_TABLE_ENTRIES 1024 #define MAX_PAGES 1024 @@ -19,6 +17,9 @@ #define PageTableEntry uint32_t +#define KERNEL_VRT_MEMORY_BEGIN 0xC0000000 +#define KERNEL_VRT_MEMORY_END 0xCFFFFFFF +#define PAGE_SIZE 4096; // NOTE: FIXME: I am fairly certain these masks are off by one! diff --git a/src/kernel/memory/paging.h b/src/kernel/memory/paging.h index 612c757..0c1979e 100644 --- a/src/kernel/memory/paging.h +++ b/src/kernel/memory/paging.h @@ -7,6 +7,8 @@ extern "C" void loadPageDirectory (uint32_t* addr ); extern "C" void enablePaging(); + +void IdentityMap(); void InitializePaging(); void Enable(); -- 2.39.5 From 3b3e2597a15f56d5b514e3fe66ac3c955493fec3 Mon Sep 17 00:00:00 2001 From: Nigel Date: Wed, 17 Aug 2022 14:29:26 +0200 Subject: [PATCH 062/115] Restructering Kernel folder before moving to higher half kernel The boot up process will be changed somewhat dramatically, therefor a restructering of the kernel seems as a good starting point. --- src/kernel/{ => Drivers/PCI}/pci.cpp | 0 src/kernel/{ => Drivers/PCI}/pci.h | 0 src/kernel/{pic => Drivers/PIC}/pic.cpp | 0 src/kernel/{pic => Drivers/PIC}/pic.h | 0 src/kernel/{ => Drivers/PIT}/pit.cpp | 0 src/kernel/{ => Drivers/PIT}/pit.h | 0 src/kernel/{keyboard => Drivers/PS-2}/keyboard.cpp | 0 src/kernel/{keyboard => Drivers/PS-2}/keyboard.h | 0 src/kernel/{ports => Drivers/Serial}/serial.cpp | 0 src/kernel/{ports => Drivers/Serial}/serial.h | 0 src/kernel/{vga => Drivers/VGA}/VBE.h | 0 src/kernel/{vga => Drivers/VGA}/colors.h | 0 src/kernel/{drivers => Drivers}/cmos/cmos.cpp | 0 src/kernel/{filesystems => FileSystem}/FAT/FAT16.cpp | 0 src/kernel/{filesystems => FileSystem}/FAT/FAT16.h | 0 src/kernel/{ => Interrupts}/idt/idt.cpp | 0 src/kernel/{ => Interrupts}/idt/idt.h | 0 src/kernel/{ => Interrupts}/idt/idt.s | 0 src/kernel/{ => Interrupts}/idt/scancodes/set1.h | 0 src/kernel/{ => KernelLauncher}/boot.s | 0 src/kernel/{ => KernelLauncher}/bootcheck.h | 0 src/kernel/{ => KernelLauncher}/crti.s | 0 src/kernel/{ => KernelLauncher}/crtn.s | 0 src/kernel/{gdt => Memory/GDT}/gdt.s | 0 src/kernel/{gdt => Memory/GDT}/gdtc.cpp | 0 src/kernel/{gdt => Memory/GDT}/gdtc.h | 0 src/kernel/{memory => Memory}/memory.cpp | 0 src/kernel/{memory => Memory}/memory.h | 0 src/kernel/{memory => Memory}/memoryinfo.h | 0 src/kernel/{memory => Memory}/paging.cpp | 0 src/kernel/{memory => Memory}/paging.definitions.h | 0 src/kernel/{memory => Memory}/paging.h | 0 src/kernel/{ => Memory}/paging.s | 0 .../{sv-terminal => SuperVisorTerminal}/superVisorTerminal.cpp | 0 .../{sv-terminal => SuperVisorTerminal}/superVisorTerminal.h | 0 src/kernel/{tty => Terminal}/kterm.cpp | 0 src/kernel/{tty => Terminal}/kterm.h | 0 src/kernel/{kstructures => }/bitmap.h | 0 src/kernel/{bootloader => }/multiboot.h | 0 39 files changed, 0 insertions(+), 0 deletions(-) rename src/kernel/{ => Drivers/PCI}/pci.cpp (100%) rename src/kernel/{ => Drivers/PCI}/pci.h (100%) rename src/kernel/{pic => Drivers/PIC}/pic.cpp (100%) rename src/kernel/{pic => Drivers/PIC}/pic.h (100%) rename src/kernel/{ => Drivers/PIT}/pit.cpp (100%) rename src/kernel/{ => Drivers/PIT}/pit.h (100%) rename src/kernel/{keyboard => Drivers/PS-2}/keyboard.cpp (100%) rename src/kernel/{keyboard => Drivers/PS-2}/keyboard.h (100%) rename src/kernel/{ports => Drivers/Serial}/serial.cpp (100%) rename src/kernel/{ports => Drivers/Serial}/serial.h (100%) rename src/kernel/{vga => Drivers/VGA}/VBE.h (100%) rename src/kernel/{vga => Drivers/VGA}/colors.h (100%) rename src/kernel/{drivers => Drivers}/cmos/cmos.cpp (100%) rename src/kernel/{filesystems => FileSystem}/FAT/FAT16.cpp (100%) rename src/kernel/{filesystems => FileSystem}/FAT/FAT16.h (100%) rename src/kernel/{ => Interrupts}/idt/idt.cpp (100%) rename src/kernel/{ => Interrupts}/idt/idt.h (100%) rename src/kernel/{ => Interrupts}/idt/idt.s (100%) rename src/kernel/{ => Interrupts}/idt/scancodes/set1.h (100%) rename src/kernel/{ => KernelLauncher}/boot.s (100%) rename src/kernel/{ => KernelLauncher}/bootcheck.h (100%) rename src/kernel/{ => KernelLauncher}/crti.s (100%) rename src/kernel/{ => KernelLauncher}/crtn.s (100%) rename src/kernel/{gdt => Memory/GDT}/gdt.s (100%) rename src/kernel/{gdt => Memory/GDT}/gdtc.cpp (100%) rename src/kernel/{gdt => Memory/GDT}/gdtc.h (100%) rename src/kernel/{memory => Memory}/memory.cpp (100%) rename src/kernel/{memory => Memory}/memory.h (100%) rename src/kernel/{memory => Memory}/memoryinfo.h (100%) rename src/kernel/{memory => Memory}/paging.cpp (100%) rename src/kernel/{memory => Memory}/paging.definitions.h (100%) rename src/kernel/{memory => Memory}/paging.h (100%) rename src/kernel/{ => Memory}/paging.s (100%) rename src/kernel/{sv-terminal => SuperVisorTerminal}/superVisorTerminal.cpp (100%) rename src/kernel/{sv-terminal => SuperVisorTerminal}/superVisorTerminal.h (100%) rename src/kernel/{tty => Terminal}/kterm.cpp (100%) rename src/kernel/{tty => Terminal}/kterm.h (100%) rename src/kernel/{kstructures => }/bitmap.h (100%) rename src/kernel/{bootloader => }/multiboot.h (100%) diff --git a/src/kernel/pci.cpp b/src/kernel/Drivers/PCI/pci.cpp similarity index 100% rename from src/kernel/pci.cpp rename to src/kernel/Drivers/PCI/pci.cpp diff --git a/src/kernel/pci.h b/src/kernel/Drivers/PCI/pci.h similarity index 100% rename from src/kernel/pci.h rename to src/kernel/Drivers/PCI/pci.h diff --git a/src/kernel/pic/pic.cpp b/src/kernel/Drivers/PIC/pic.cpp similarity index 100% rename from src/kernel/pic/pic.cpp rename to src/kernel/Drivers/PIC/pic.cpp diff --git a/src/kernel/pic/pic.h b/src/kernel/Drivers/PIC/pic.h similarity index 100% rename from src/kernel/pic/pic.h rename to src/kernel/Drivers/PIC/pic.h diff --git a/src/kernel/pit.cpp b/src/kernel/Drivers/PIT/pit.cpp similarity index 100% rename from src/kernel/pit.cpp rename to src/kernel/Drivers/PIT/pit.cpp diff --git a/src/kernel/pit.h b/src/kernel/Drivers/PIT/pit.h similarity index 100% rename from src/kernel/pit.h rename to src/kernel/Drivers/PIT/pit.h diff --git a/src/kernel/keyboard/keyboard.cpp b/src/kernel/Drivers/PS-2/keyboard.cpp similarity index 100% rename from src/kernel/keyboard/keyboard.cpp rename to src/kernel/Drivers/PS-2/keyboard.cpp diff --git a/src/kernel/keyboard/keyboard.h b/src/kernel/Drivers/PS-2/keyboard.h similarity index 100% rename from src/kernel/keyboard/keyboard.h rename to src/kernel/Drivers/PS-2/keyboard.h diff --git a/src/kernel/ports/serial.cpp b/src/kernel/Drivers/Serial/serial.cpp similarity index 100% rename from src/kernel/ports/serial.cpp rename to src/kernel/Drivers/Serial/serial.cpp diff --git a/src/kernel/ports/serial.h b/src/kernel/Drivers/Serial/serial.h similarity index 100% rename from src/kernel/ports/serial.h rename to src/kernel/Drivers/Serial/serial.h diff --git a/src/kernel/vga/VBE.h b/src/kernel/Drivers/VGA/VBE.h similarity index 100% rename from src/kernel/vga/VBE.h rename to src/kernel/Drivers/VGA/VBE.h diff --git a/src/kernel/vga/colors.h b/src/kernel/Drivers/VGA/colors.h similarity index 100% rename from src/kernel/vga/colors.h rename to src/kernel/Drivers/VGA/colors.h diff --git a/src/kernel/drivers/cmos/cmos.cpp b/src/kernel/Drivers/cmos/cmos.cpp similarity index 100% rename from src/kernel/drivers/cmos/cmos.cpp rename to src/kernel/Drivers/cmos/cmos.cpp diff --git a/src/kernel/filesystems/FAT/FAT16.cpp b/src/kernel/FileSystem/FAT/FAT16.cpp similarity index 100% rename from src/kernel/filesystems/FAT/FAT16.cpp rename to src/kernel/FileSystem/FAT/FAT16.cpp diff --git a/src/kernel/filesystems/FAT/FAT16.h b/src/kernel/FileSystem/FAT/FAT16.h similarity index 100% rename from src/kernel/filesystems/FAT/FAT16.h rename to src/kernel/FileSystem/FAT/FAT16.h diff --git a/src/kernel/idt/idt.cpp b/src/kernel/Interrupts/idt/idt.cpp similarity index 100% rename from src/kernel/idt/idt.cpp rename to src/kernel/Interrupts/idt/idt.cpp diff --git a/src/kernel/idt/idt.h b/src/kernel/Interrupts/idt/idt.h similarity index 100% rename from src/kernel/idt/idt.h rename to src/kernel/Interrupts/idt/idt.h diff --git a/src/kernel/idt/idt.s b/src/kernel/Interrupts/idt/idt.s similarity index 100% rename from src/kernel/idt/idt.s rename to src/kernel/Interrupts/idt/idt.s diff --git a/src/kernel/idt/scancodes/set1.h b/src/kernel/Interrupts/idt/scancodes/set1.h similarity index 100% rename from src/kernel/idt/scancodes/set1.h rename to src/kernel/Interrupts/idt/scancodes/set1.h diff --git a/src/kernel/boot.s b/src/kernel/KernelLauncher/boot.s similarity index 100% rename from src/kernel/boot.s rename to src/kernel/KernelLauncher/boot.s diff --git a/src/kernel/bootcheck.h b/src/kernel/KernelLauncher/bootcheck.h similarity index 100% rename from src/kernel/bootcheck.h rename to src/kernel/KernelLauncher/bootcheck.h diff --git a/src/kernel/crti.s b/src/kernel/KernelLauncher/crti.s similarity index 100% rename from src/kernel/crti.s rename to src/kernel/KernelLauncher/crti.s diff --git a/src/kernel/crtn.s b/src/kernel/KernelLauncher/crtn.s similarity index 100% rename from src/kernel/crtn.s rename to src/kernel/KernelLauncher/crtn.s diff --git a/src/kernel/gdt/gdt.s b/src/kernel/Memory/GDT/gdt.s similarity index 100% rename from src/kernel/gdt/gdt.s rename to src/kernel/Memory/GDT/gdt.s diff --git a/src/kernel/gdt/gdtc.cpp b/src/kernel/Memory/GDT/gdtc.cpp similarity index 100% rename from src/kernel/gdt/gdtc.cpp rename to src/kernel/Memory/GDT/gdtc.cpp diff --git a/src/kernel/gdt/gdtc.h b/src/kernel/Memory/GDT/gdtc.h similarity index 100% rename from src/kernel/gdt/gdtc.h rename to src/kernel/Memory/GDT/gdtc.h diff --git a/src/kernel/memory/memory.cpp b/src/kernel/Memory/memory.cpp similarity index 100% rename from src/kernel/memory/memory.cpp rename to src/kernel/Memory/memory.cpp diff --git a/src/kernel/memory/memory.h b/src/kernel/Memory/memory.h similarity index 100% rename from src/kernel/memory/memory.h rename to src/kernel/Memory/memory.h diff --git a/src/kernel/memory/memoryinfo.h b/src/kernel/Memory/memoryinfo.h similarity index 100% rename from src/kernel/memory/memoryinfo.h rename to src/kernel/Memory/memoryinfo.h diff --git a/src/kernel/memory/paging.cpp b/src/kernel/Memory/paging.cpp similarity index 100% rename from src/kernel/memory/paging.cpp rename to src/kernel/Memory/paging.cpp diff --git a/src/kernel/memory/paging.definitions.h b/src/kernel/Memory/paging.definitions.h similarity index 100% rename from src/kernel/memory/paging.definitions.h rename to src/kernel/Memory/paging.definitions.h diff --git a/src/kernel/memory/paging.h b/src/kernel/Memory/paging.h similarity index 100% rename from src/kernel/memory/paging.h rename to src/kernel/Memory/paging.h diff --git a/src/kernel/paging.s b/src/kernel/Memory/paging.s similarity index 100% rename from src/kernel/paging.s rename to src/kernel/Memory/paging.s diff --git a/src/kernel/sv-terminal/superVisorTerminal.cpp b/src/kernel/SuperVisorTerminal/superVisorTerminal.cpp similarity index 100% rename from src/kernel/sv-terminal/superVisorTerminal.cpp rename to src/kernel/SuperVisorTerminal/superVisorTerminal.cpp diff --git a/src/kernel/sv-terminal/superVisorTerminal.h b/src/kernel/SuperVisorTerminal/superVisorTerminal.h similarity index 100% rename from src/kernel/sv-terminal/superVisorTerminal.h rename to src/kernel/SuperVisorTerminal/superVisorTerminal.h diff --git a/src/kernel/tty/kterm.cpp b/src/kernel/Terminal/kterm.cpp similarity index 100% rename from src/kernel/tty/kterm.cpp rename to src/kernel/Terminal/kterm.cpp diff --git a/src/kernel/tty/kterm.h b/src/kernel/Terminal/kterm.h similarity index 100% rename from src/kernel/tty/kterm.h rename to src/kernel/Terminal/kterm.h diff --git a/src/kernel/kstructures/bitmap.h b/src/kernel/bitmap.h similarity index 100% rename from src/kernel/kstructures/bitmap.h rename to src/kernel/bitmap.h diff --git a/src/kernel/bootloader/multiboot.h b/src/kernel/multiboot.h similarity index 100% rename from src/kernel/bootloader/multiboot.h rename to src/kernel/multiboot.h -- 2.39.5 From bbfea39c233c221af69532fdecb987adaebad12f Mon Sep 17 00:00:00 2001 From: Nigel Date: Wed, 17 Aug 2022 14:57:50 +0200 Subject: [PATCH 063/115] Fixing include paths for new structure Removed non-sensical libc folder from project --- Makefile | 26 +++++++++---------- src/kernel/Drivers/PIC/pic.h | 2 +- src/kernel/Drivers/PIT/pit.cpp | 2 +- src/kernel/Drivers/PIT/pit.h | 2 +- src/kernel/Drivers/PS-2/keyboard.h | 2 +- src/kernel/Interrupts/idt/idt.cpp | 4 +-- src/kernel/Interrupts/idt/idt.h | 6 ++--- src/kernel/KernelLauncher/boot.s | 6 ++--- src/kernel/KernelLauncher/bootcheck.h | 4 +-- src/{libc/include => kernel/Lib}/mem.h | 0 src/{libc/include => kernel/Lib}/string.c | 0 src/{libc/include => kernel/Lib}/string.h | 0 src/kernel/Memory/GDT/gdtc.cpp | 2 +- src/kernel/Memory/memory.h | 8 +++--- src/kernel/Memory/paging.h | 4 +-- .../SuperVisorTerminal/superVisorTerminal.h | 8 +++--- src/kernel/Terminal/kterm.h | 4 +-- src/kernel/bootinfo.h | 3 +-- src/kernel/definitions.h | 2 -- src/kernel/kernel.h | 24 ++++++++--------- src/kernel/serial.h | 2 +- 21 files changed, 54 insertions(+), 57 deletions(-) rename src/{libc/include => kernel/Lib}/mem.h (100%) rename src/{libc/include => kernel/Lib}/string.c (100%) rename src/{libc/include => kernel/Lib}/string.h (100%) diff --git a/Makefile b/Makefile index eea8447..d5443c0 100644 --- a/Makefile +++ b/Makefile @@ -51,51 +51,51 @@ $(BUILD_DIR)/kernel.o: $(CPP) -c $(SRC_DIR)/kernel/kernel.cpp -o $(BUILD_DIR)/kernel.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/kterm.o: - $(CPP) -c $(SRC_DIR)/kernel/tty/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/Terminal/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/boot.o: - $(AS) $(SRC_DIR)/kernel/boot.s -o $(BUILD_DIR)/boot.o + $(AS) $(SRC_DIR)/kernel/KernelLauncher/boot.s -o $(BUILD_DIR)/boot.o $(BUILD_DIR)/crti.o: - $(AS) $(SRC_DIR)/kernel/crti.s -o $(BUILD_DIR)/crti.o + $(AS) $(SRC_DIR)/kernel/KernelLauncher/crti.s -o $(BUILD_DIR)/crti.o $(BUILD_DIR)/crtn.o: - $(AS) $(SRC_DIR)/kernel/crtn.s -o $(BUILD_DIR)/crtn.o + $(AS) $(SRC_DIR)/kernel/KernelLauncher/crtn.s -o $(BUILD_DIR)/crtn.o $(BUILD_DIR)/io.o: $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/idt.o: - $(CPP) -c $(SRC_DIR)/kernel/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/Interrupts/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/gdtc.o: - $(CPP) -c $(SRC_DIR)/kernel/gdt/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/Memory/GDT/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pic.o: - $(CPP) -c $(SRC_DIR)/kernel/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/Drivers/PIC/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/string.o: - $(CC) -c $(SRC_DIR)/libc/include/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 + $(CC) -c $(SRC_DIR)/kernel/Lib/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 $(BUILD_DIR)/pit.o: - $(CPP) -c $(SRC_DIR)/kernel/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/Drivers/PIT/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/keyboard.o: - $(CPP) -c $(SRC_DIR)/kernel/keyboard/keyboard.cpp -o $(BUILD_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/Drivers/PS-2/keyboard.cpp -o $(BUILD_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/time.o: $(CPP) -c $(SRC_DIR)/kernel/time.cpp -o $(BUILD_DIR)/time.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/sv-terminal.o: - $(CPP) -c $(SRC_DIR)/kernel/sv-terminal/superVisorTerminal.cpp -o $(BUILD_DIR)/sv-terminal.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/SuperVisorTerminal/superVisorTerminal.cpp -o $(BUILD_DIR)/sv-terminal.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/memory.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/memory.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/Memory/memory.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/paging.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/paging.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file + $(CPP) -c $(SRC_DIR)/kernel/Memory/paging.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file diff --git a/src/kernel/Drivers/PIC/pic.h b/src/kernel/Drivers/PIC/pic.h index 9560cea..64a8188 100644 --- a/src/kernel/Drivers/PIC/pic.h +++ b/src/kernel/Drivers/PIC/pic.h @@ -1,5 +1,5 @@ #pragma once -#include "../io.h" +#include "../../io.h" #define PIC1 0x20 /* IO base address for master PIC */ #define PIC2 0xA0 /* IO base address for slave PIC */ diff --git a/src/kernel/Drivers/PIT/pit.cpp b/src/kernel/Drivers/PIT/pit.cpp index d2b6527..afe8536 100644 --- a/src/kernel/Drivers/PIT/pit.cpp +++ b/src/kernel/Drivers/PIT/pit.cpp @@ -1,5 +1,5 @@ #include "pit.h" -#include "tty/kterm.h" +#include "../../Terminal/kterm.h" uint32_t pit_tick = 0; diff --git a/src/kernel/Drivers/PIT/pit.h b/src/kernel/Drivers/PIT/pit.h index 361ed4b..7e4d0f1 100644 --- a/src/kernel/Drivers/PIT/pit.h +++ b/src/kernel/Drivers/PIT/pit.h @@ -1,6 +1,6 @@ #pragma once #include -#include "io.h" +#include "../../io.h" #define PIT_DATA_0 0x40 #define PIT_DATA_1 0x41 #define PIT_DATA_2 0x42 diff --git a/src/kernel/Drivers/PS-2/keyboard.h b/src/kernel/Drivers/PS-2/keyboard.h index 09ce1bb..f832178 100644 --- a/src/kernel/Drivers/PS-2/keyboard.h +++ b/src/kernel/Drivers/PS-2/keyboard.h @@ -1,6 +1,6 @@ #pragma once #include -#include "../tty/kterm.h" +#include "../../Terminal/kterm.h" typedef enum ScanCodeSet{ None = 0, ScanCodeSet1 = 1, diff --git a/src/kernel/Interrupts/idt/idt.cpp b/src/kernel/Interrupts/idt/idt.cpp index cc3db0c..c043c1b 100644 --- a/src/kernel/Interrupts/idt/idt.cpp +++ b/src/kernel/Interrupts/idt/idt.cpp @@ -1,6 +1,6 @@ #include "idt.h" -#include "../pit.h" -#include "../keyboard/keyboard.h" +#include "../../Drivers/PIT/pit.h" +#include "../../Drivers/PS-2/keyboard.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; diff --git a/src/kernel/Interrupts/idt/idt.h b/src/kernel/Interrupts/idt/idt.h index 04173d3..8157fbe 100644 --- a/src/kernel/Interrupts/idt/idt.h +++ b/src/kernel/Interrupts/idt/idt.h @@ -2,10 +2,10 @@ #include "stdint.h" #include "stddef.h" -#include "../vga/colors.h" -#include "../pic/pic.h" +#include "../../Drivers/VGA/colors.h" +#include "../../Drivers/PIC/pic.h" -#include "../tty/kterm.h" +#include "../../Terminal/kterm.h" extern "C" { diff --git a/src/kernel/KernelLauncher/boot.s b/src/kernel/KernelLauncher/boot.s index 4e4ba36..722c2d2 100644 --- a/src/kernel/KernelLauncher/boot.s +++ b/src/kernel/KernelLauncher/boot.s @@ -21,11 +21,11 @@ stack_bottom: stack_top: .section .text -.include "./src/kernel/gdt/gdt.s" +.include "./src/kernel/Memory/GDT/gdt.s" .include "./src/kernel/irs_table.s" .include "./src/kernel/irq_table.s" -.include "./src/kernel/idt/idt.s" -.include "./src/kernel/paging.s" +.include "./src/kernel/Interrupts/idt/idt.s" +.include "./src/kernel/Memory/paging.s" .include "./src/kernel/cpu.s" .global _start diff --git a/src/kernel/KernelLauncher/bootcheck.h b/src/kernel/KernelLauncher/bootcheck.h index 62765a5..1a11c05 100644 --- a/src/kernel/KernelLauncher/bootcheck.h +++ b/src/kernel/KernelLauncher/bootcheck.h @@ -1,8 +1,8 @@ #pragma once -#include "bootloader/multiboot.h" +#include "../multiboot.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) -#include "tty/kterm.h" +#include "../Terminal/kterm.h" diff --git a/src/libc/include/mem.h b/src/kernel/Lib/mem.h similarity index 100% rename from src/libc/include/mem.h rename to src/kernel/Lib/mem.h diff --git a/src/libc/include/string.c b/src/kernel/Lib/string.c similarity index 100% rename from src/libc/include/string.c rename to src/kernel/Lib/string.c diff --git a/src/libc/include/string.h b/src/kernel/Lib/string.h similarity index 100% rename from src/libc/include/string.h rename to src/kernel/Lib/string.h diff --git a/src/kernel/Memory/GDT/gdtc.cpp b/src/kernel/Memory/GDT/gdtc.cpp index c2d7ac6..e78b509 100644 --- a/src/kernel/Memory/GDT/gdtc.cpp +++ b/src/kernel/Memory/GDT/gdtc.cpp @@ -1,5 +1,5 @@ #include "gdtc.h" -#include "../tty/kterm.h" +#include "../../Terminal/kterm.h" #define NULL_SEGMENT 0 #define KERNEL_CODE_SEGMENT 1 diff --git a/src/kernel/Memory/memory.h b/src/kernel/Memory/memory.h index 2d0d309..7b04151 100644 --- a/src/kernel/Memory/memory.h +++ b/src/kernel/Memory/memory.h @@ -3,10 +3,10 @@ #include #include "memoryinfo.h" -#include "../bootloader/multiboot.h" -#include "../tty/kterm.h" -#include "../../libc/include/mem.h" -#include "../kstructures/bitmap.h" +#include "../multiboot.h" +#include "../Terminal/kterm.h" +#include "../Lib/mem.h" +#include "../bitmap.h" #define BLOCK_SIZE 4092 #define BLOCKS_PER_WORD 32 // A word is 16 bit in x86 machines according to my google search results! diff --git a/src/kernel/Memory/paging.h b/src/kernel/Memory/paging.h index 0c1979e..8e1e155 100644 --- a/src/kernel/Memory/paging.h +++ b/src/kernel/Memory/paging.h @@ -1,7 +1,7 @@ #pragma once -#include "./memory.h" -#include "./../tty/kterm.h" +#include "memory.h" #include "paging.definitions.h" +#include "../Terminal/kterm.h" #include "../cpu.h" extern "C" void loadPageDirectory (uint32_t* addr ); diff --git a/src/kernel/SuperVisorTerminal/superVisorTerminal.h b/src/kernel/SuperVisorTerminal/superVisorTerminal.h index 5d4519d..99d083d 100644 --- a/src/kernel/SuperVisorTerminal/superVisorTerminal.h +++ b/src/kernel/SuperVisorTerminal/superVisorTerminal.h @@ -1,9 +1,9 @@ #pragma once -#include "../tty/kterm.h" +#include "../Terminal/kterm.h" #include "../time.h" -#include "../pit.h" -#include "../keyboard/keyboard.h" -#include "../memory/memory.h" +#include "../Drivers/PIT/pit.h" +#include "../Drivers/PS-2/keyboard.h" +#include "../Memory/memory.h" #include "../bootinfo.h" void startSuperVisorTerminal(BootInfo * ); \ No newline at end of file diff --git a/src/kernel/Terminal/kterm.h b/src/kernel/Terminal/kterm.h index 4f048d0..b260b73 100644 --- a/src/kernel/Terminal/kterm.h +++ b/src/kernel/Terminal/kterm.h @@ -4,11 +4,11 @@ #include #include -#include "../vga/colors.h" +#include "../Drivers/VGA/colors.h" #include "../io.h" extern "C"{ - #include "./../../libc/include/string.h" + #include "../Lib/string.h" } void kterm_init(); diff --git a/src/kernel/bootinfo.h b/src/kernel/bootinfo.h index 575a048..1daa198 100644 --- a/src/kernel/bootinfo.h +++ b/src/kernel/bootinfo.h @@ -1,6 +1,5 @@ #pragma once -#include "memory/memoryinfo.h" - +#include "Memory/memoryinfo.h" struct BootInfo{ const char* BootStructureID = "BarinkOS"; diff --git a/src/kernel/definitions.h b/src/kernel/definitions.h index 1f99d57..942949d 100644 --- a/src/kernel/definitions.h +++ b/src/kernel/definitions.h @@ -3,8 +3,6 @@ * Kernel definitions */ - - #define __DEBUG__ false #define KERNEL_VERSION 0 diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index c3b257b..1f15f6a 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -1,32 +1,32 @@ #pragma once extern "C" { - #include "../libc/include/string.h" + #include "Lib/string.h" } #include "definitions.h" -#include "vga/VBE.h" -#include "tty/kterm.h" +#include "Drivers/VGA/VBE.h" +#include "Terminal/kterm.h" -#include "./bootloader/multiboot.h" +#include "multiboot.h" #include "bootinfo.h" -#include "memory/memory.h" -#include "memory/memoryinfo.h" -#include "memory/paging.h" -#include "bootcheck.h" +#include "Memory/memory.h" +#include "Memory/memoryinfo.h" +#include "Memory/paging.h" +#include "KernelLauncher/bootcheck.h" -#include "gdt/gdtc.h" -#include "idt/idt.h" +#include "Memory/GDT/gdtc.h" +#include "Interrupts/idt/idt.h" -#include "pit.h" +#include "Drivers/PIT/pit.h" #include "io.h" #include "cpu.h" #include "serial.h" #include "time.h" -#include "sv-terminal/superVisorTerminal.h" +#include "SuperVisorTerminal/superVisorTerminal.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) #define PANIC(message) {return;} diff --git a/src/kernel/serial.h b/src/kernel/serial.h index 369c117..343184b 100644 --- a/src/kernel/serial.h +++ b/src/kernel/serial.h @@ -1,6 +1,6 @@ #pragma once -#include "tty/kterm.h" +#include "Terminal/kterm.h" #include "io.h" #define PORT 0x3f8 static int init_serial() { -- 2.39.5 From 7d6c823d79dcfb819cec7c7ab1eab33255c26dfd Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 18 Aug 2022 01:26:49 +0200 Subject: [PATCH 064/115] Basic Launch of Higher half kernel We now can launch the kernel at 0xC0000000 (or 3 GiB mark) with paging enabled. A lot of early main is currently not executed to keep debugging as simple as possible during the initial testing of higher half kernel loading. A lot of the implementation is straight from wiki.osdev.org/Higher_Half_x86_Bare_Bones. Thanks to all the folks who keep that wiki updated, its really resourceful. --- Makefile | 9 ++- src/kernel/KernelLauncher/boot.s | 114 ++++++++++++++++++++++++++----- src/kernel/Terminal/kterm.cpp | 2 +- src/kernel/kernel.cpp | 26 +++---- src/kernel/linker.ld | 50 +++++++------- 5 files changed, 141 insertions(+), 60 deletions(-) diff --git a/Makefile b/Makefile index d5443c0..c8a3fa1 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ EMULATOR = qemu-system-i386 AS = ${HOME}/opt/cross/bin/i686-elf-as CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ -CFLAGS = -ffreestanding -O2 -Wall -Wextra +CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o @@ -34,11 +34,14 @@ iso: clean_iso clean build grub-mkrescue -o build/barinkOS.iso root run: all - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo + $(EMULATOR) -cdrom build/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo + +debug: all + $(EMULATOR) -cdrom build/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -s -d int build_kernel: $(OBJ_LINK_LIST) $(CC) -T $(SRC_DIR)/kernel//linker.ld -o $(BUILD_DIR)/myos.bin \ - -ffreestanding -O2 -nostdlib $(OBJ_LINK_LIST) -lgcc + -ffreestanding -ggdb -Og -nostdlib $(OBJ_LINK_LIST) -lgcc build_x86_64: $(AS) $(SRC_DIR)/cgc/x86_64/crti.s -o $(BUILD_DIR)/crti_64.o diff --git a/src/kernel/KernelLauncher/boot.s b/src/kernel/KernelLauncher/boot.s index 722c2d2..8b61af0 100644 --- a/src/kernel/KernelLauncher/boot.s +++ b/src/kernel/KernelLauncher/boot.s @@ -7,30 +7,104 @@ .set MAGIC, 0x1BADB002 /* 'magic number' lets bootloader find the header */ .set CHECKSUM, -(MAGIC + FLAGS) /* checksum of above, to prove we are multiboot */ -.section .multiboot +.section .multiboot.data, "aw" .align 4 .long MAGIC .long FLAGS .long CHECKSUM - -.section .bss -.align 16 +/* +* Allocate initial stack +*/ +.section .bootstrap_stack, "aw", @nobits stack_bottom: .skip 16384 # 16 KiB stack_top: - -.section .text -.include "./src/kernel/Memory/GDT/gdt.s" -.include "./src/kernel/irs_table.s" -.include "./src/kernel/irq_table.s" -.include "./src/kernel/Interrupts/idt/idt.s" -.include "./src/kernel/Memory/paging.s" -.include "./src/kernel/cpu.s" +/* +* Preallocate a couple pages to get us bootstrapped +* Being carefull to not use any address the bootloader might +* be using for its multiboot structures +*/ +.section .bss, "aw", @nobits + .align 4096 +boot_page_directory: + .skip 4096 +boot_page_table: + .skip 4096 +# More page tables may be required + +# Entry point +.section .multiboot.text, "a" .global _start -.type _start, @function +.type _start, @function _start: + # Get physical address of the boot_page_table + movl $(boot_page_table - 0xC0000000), %edi + # Map address 0 + movl $0, %esi + # Map 1023 pages the 1024th being the VGA text buffer + movl $1023, %ecx + +1: # Map the kernel + cmpl $_kernel_start, %esi + jl 2f + cmpl $(_kernel_end - 0xC0000000), %esi + jge 3f + + # Map physical address as "present and writable" + movl %esi, %edx + orl $0x003, %edx + movl %edx, (%edi) + +2: # Size of page is 4096 bytes + addl $4096, %esi + # Size of entries in boot_page_table is 4 bytes + addl $4, %edi + # Loop to the next entry if we haven't finished. + loop 1b + +3: # Map VGA video memory to 0xC03FF00 as "present, writable" + movl $(0x000B8000 | 0x003), boot_page_table - 0xC0000000 + 1023 * 4 + + + # IMPORTANT NOTE FROM WIKI.OSDEV.ORG/HIGHER_HALF_X86_BARE_BONES + + # The page table is used at both page directory entry 0 (virtually from 0x0 + # to 0x3FFFFF) (thus identity mapping the kernel) and page directory entry + # 768 (virtually from 0xC0000000 to 0xC03FFFFF) (thus mapping it in the + # higher half). The kernel is identity mapped because enabling paging does + # not change the next instruction, which continues to be physical. The CPU + # would instead page fault if there was no identity mapping.\ + + # Map the page table to both virtual addresss 0x00000000 and 0xC0000000 + movl $(boot_page_table - 0xC0000000 + 0x003), boot_page_directory - 0xC0000000 + 0 + movl $(boot_page_table - 0xC0000000 + 0x003), boot_page_directory - 0xC0000000 + 768 * 4 + + # Set cr3 to the address of the boot_page_directory + movl $(boot_page_directory - 0xC0000000), %ecx + movl %ecx, %cr3 + + # Enable paging and the write-protect bit + movl %cr0, %ecx + orl $0x80010000, %ecx + movl %ecx, %cr0 + + # Jump to higher half with an absolute jump + lea 4f, %ecx + jmp *%ecx + +.section .text +4: + # At this point, paging is fully set up and enabled +isPaging: + # Unmap the identity mapping as it is now unnecessary + movl $0, boot_page_directory + 0 + + # Reload cr3 to force tlb flush + movl %cr3, %ecx + movl %ecx, %cr3 + /*Setup the stack pointer to point to the beginning of our stack */ /* I believe its a high address growing down to lower adress for the stack on x86*/ mov $stack_top, %esp @@ -44,16 +118,15 @@ _start: /* push the magic value */ pushl %eax - - call early_main + call early_main mov %cr0, %eax or $1, %eax - mov %eax, %cr0 + mov %eax, %cr0 - call kernel_main + //call kernel_main cli @@ -61,6 +134,11 @@ _start: jmp 1b -.size _start, . - _start +.include "./src/kernel/Memory/GDT/gdt.s" +.include "./src/kernel/irs_table.s" +.include "./src/kernel/irq_table.s" +.include "./src/kernel/Interrupts/idt/idt.s" +.include "./src/kernel/Memory/paging.s" +.include "./src/kernel/cpu.s" diff --git a/src/kernel/Terminal/kterm.cpp b/src/kernel/Terminal/kterm.cpp index 94bc3f1..95573c6 100644 --- a/src/kernel/Terminal/kterm.cpp +++ b/src/kernel/Terminal/kterm.cpp @@ -21,7 +21,7 @@ void kterm_init () { kterm_row = 0; kterm_column = 0; kterm_color = vga_entry_color ( VGA_COLOR_LIGHT_GREY , VGA_COLOR_BLACK); - kterm_buffer = (uint16_t*) 0xB8000; + kterm_buffer = (uint16_t*) 0xC03FF000; for (size_t y = 0; y < VGA_HEIGHT; y++ ){ for( size_t x = 0; x < VGA_WIDTH; x++){ const size_t index = y * VGA_WIDTH + x; diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 25666ef..3251521 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -1,11 +1,9 @@ #include "kernel.h" + extern "C" void kernel_main (BootInfo* bootinfo) { init_serial(); - pit_initialise(); - - //InitializePaging(); - //Enable(); + //pit_initialise(); startSuperVisorTerminal(bootinfo); } @@ -16,8 +14,12 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ * Initialize terminal interface * NOTE: This should be done later on , the magic value should be checked first. */ + initGDT(); kterm_init(); - + init_serial(); + print_serial("Hello Higher half kernel!"); + printf("DDDDDDDDDDDDDDDD"); + return; /** * Check Multiboot magic number * NOTE: Printf call should not be a thing this early on ... @@ -31,7 +33,7 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ * Show a little banner for cuteness */ printf("|=== BarinkOS ===|\n"); - + printf("Kernel Begin AT(0x%x)", kernel_begin); /** * Use the address given as an argument as the pointer @@ -107,17 +109,17 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ //memAlloc.free_block((void*) memory); //InitializePaging(); - IdentityMap(); - Enable(); + //IdentityMap(); + //Enable(); } - initGDT(); - init_idt(); + //initGDT(); + //init_idt(); // Enable interrupts - asm volatile("STI"); + //asm volatile("STI"); - CheckMBT( (multiboot_info_t *) addr); + //CheckMBT( (multiboot_info_t *) addr); kernel_main(&bootinfo); diff --git a/src/kernel/linker.ld b/src/kernel/linker.ld index eb1aae8..bcb2584 100644 --- a/src/kernel/linker.ld +++ b/src/kernel/linker.ld @@ -1,47 +1,45 @@ -/* The bootloader will look at this image and start execution at the symbol - designated as the entry point. */ ENTRY(_start) /* Tell where the various sections of the object files will be put in the final kernel image. */ SECTIONS { - - /* Begin putting sections at 1 MiB, a conventional place for kernels to be - loaded at by the bootloader. */ - . = 1M; - kernel_begin = .; - /* First put the multiboot header, as it is required to be put very early - early in the image or the bootloader won't recognize the file format. - Next we'll put the .text section. */ - .text BLOCK(4K) : ALIGN(4K) + . = 0x00100000; /* place code at 1MB mark*/ + + _kernel_start = .; + kernel_begin = .; /* For legacy reasons */ + + + .multiboot.data : { + *(.multiboot.data) + } + + .multiboot.text : { + *(multiboot.text) + } + + . += 0xC0000000; /* Addresses in the following code need to be above the 3Gb mark */ + + + .text ALIGN (4K) : AT (ADDR (.text) - 0xC0000000) { - *(.multiboot) *(.text) } - - /* Read-only data. */ - .rodata BLOCK(4K) : ALIGN(4K) + .rodata ALIGN (4K) : AT (ADDR (.rodata) - 0xC0000000) { *(.rodata) } - - /* Read-write data (initialized) */ - .data BLOCK(4K) : ALIGN(4K) + .data ALIGN (4K) : AT (ADDR (.data) - 0xC0000000) { *(.data) } - - /* Read-write data (uninitialized) and stack */ - .bss BLOCK(4K) : ALIGN(4K) + .bss ALIGN (4K) : AT (ADDR (.bss) - 0xC0000000) { *(COMMON) *(.bss) + *(.bootstrap_stack) } - - /* The compiler may produce other sections, by default it will put them in - a segment with the same name. Simply add stuff here as needed. */ - - kernel_end = .; + _kernel_end = .; + kernel_end = .; /* For legacy reasons */ } -- 2.39.5 From d280aa0584a2334b16df03aab4b831e2644df87f Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 19 Aug 2022 00:44:52 +0200 Subject: [PATCH 065/115] Page faults and protetion faults will now hang with a helpful message to explain what is going on. I removed previously set barriers from the code to load the kernel further. --- Makefile | 1 + src/kernel/Interrupts/idt/idt.cpp | 80 ++++++++++++++++++++++++++----- src/kernel/Memory/memory.cpp | 2 +- src/kernel/cpu.h | 12 +++++ src/kernel/cpu.s | 26 +++++++++- src/kernel/kernel.cpp | 52 ++++++++++++++------ src/kernel/kernel.h | 2 +- 7 files changed, 145 insertions(+), 30 deletions(-) diff --git a/Makefile b/Makefile index c8a3fa1..8b655ac 100644 --- a/Makefile +++ b/Makefile @@ -37,6 +37,7 @@ run: all $(EMULATOR) -cdrom build/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo debug: all + objcopy --only-keep-debug build/myos.bin kernel.sym $(EMULATOR) -cdrom build/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -s -d int build_kernel: $(OBJ_LINK_LIST) diff --git a/src/kernel/Interrupts/idt/idt.cpp b/src/kernel/Interrupts/idt/idt.cpp index c043c1b..4c5f934 100644 --- a/src/kernel/Interrupts/idt/idt.cpp +++ b/src/kernel/Interrupts/idt/idt.cpp @@ -1,10 +1,11 @@ #include "idt.h" #include "../../Drivers/PIT/pit.h" #include "../../Drivers/PS-2/keyboard.h" - +#include "../../cpu.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; + void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ idt_table[num].offset_1 = base & 0xFFFF; idt_table[num].selector = sel; @@ -15,7 +16,7 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ }; void irs_handler (registers regs) { - + uint32_t FaultingAddress; //printf("(IRS) Interrupt number: %d \r", regs.int_no); switch (regs.int_no) { @@ -120,28 +121,83 @@ void irs_handler (registers regs) { case 13: // General Protection Exception #GP printf("#GP\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + + + printf("ERR_CODE: 0x%x", regs.err_code); + + if( regs.err_code & 0x1) + { + printf("Originated externally!"); + } + + if(regs.err_code & 0x3 >> 1 == 0 ){ + printf("Index references GDT"); + } + if(regs.err_code & 0x3 >> 1 == 1 ){ + printf("Index references IDT"); + } + + if(regs.err_code & 0x3 >> 1 == 2 ){ + printf("Index references LDT"); + } + + if(regs.err_code & 0x3 >> 1 == 4 ){ + printf("Index references IDT"); + } + + + printf("Index: ", (regs.err_code >> 3 & 0xFFF ) ); + + __asm__("cli;" "1: hlt;" "jmp 1b;"); + break; case 14: // Page Fault Exception #PF printf("#PF\n"); - printf("EIP: 0x%x\n", regs.eip); // Points to faulting instruction ??? - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); // Base pointer pointing to the bottom of the stack - - + FaultingAddress = GetCR2(); + printf("Faulting instruction adddress: 0x%x\n", FaultingAddress); + // Error code of 32 bits are on the stack - // CR2 register contains the 32-bit linear address that generated the exception + // CR2 register contains the 32-bit linear virtual address that generated the exception // See Intel Software Developers manual Volume 3A Part 1 page 236 for more info - + #define PF_ERR_PRESENT_BIT 0x1 + #define PF_ERR_WRITE_BIT 0x2 + #define PF_ERR_USER_BIT 0x3 + #define PF_ERR_RESERVERD_WRITE_BIT 0x4 + #define PF_ERR_INSTRUCTION_FETCH_BIT 0x5 + #define PF_ERR_PROTECTION_KEY_BIT 0x6 + #define PF_ERR_SHADOW_STACK_BIT 0x7 + #define PF_ERR_SOFTWARE_GUARD_EXTENSION_BIT 0xE + + printf("Determining cause of fault...\n"); + + + if (regs.err_code & PF_ERR_PRESENT_BIT ){ + printf("Page protection violation!\n"); + } else{ + printf("page not-present!\n"); + } + + if(regs.err_code & PF_ERR_WRITE_BIT){ + printf("Write access violation!\n"); + } else{ + printf("Read access violation!\n"); + } + + if(regs.err_code & PF_ERR_USER_BIT){ + printf("Violation from user-space (CPL=3)\n"); + } + + if(regs.err_code & PF_ERR_INSTRUCTION_FETCH_BIT){ + printf("Caused by an instruction fetch. \n"); + } /* Check the error code to figure out what happened here */ + __asm__("cli;" "1: hlt;" "jmp 1b;"); diff --git a/src/kernel/Memory/memory.cpp b/src/kernel/Memory/memory.cpp index b72e786..3106c7c 100644 --- a/src/kernel/Memory/memory.cpp +++ b/src/kernel/Memory/memory.cpp @@ -10,7 +10,7 @@ void PhysicalMemory::setup( MemoryInfo* memory) { used_blocks = 0; - memoryBitMap = (uint32_t*) 0x00a00000; + memoryBitMap = (uint32_t*) 0xCCA00000; printf("Maximum Number of blocks: 0x%x, Number of bytes for memMap: 0x%x\n", max_blocks , (max_blocks/8)); diff --git a/src/kernel/cpu.h b/src/kernel/cpu.h index 97b50ab..94d9485 100644 --- a/src/kernel/cpu.h +++ b/src/kernel/cpu.h @@ -60,3 +60,15 @@ extern "C" uint32_t GetCR4(); #define GET_PSE_BIT(CONTROL_REGISTER_4) (CONTROL_REGISTER_4&0x4) #define GET_PAE_BIT(CONTROL_REGISTER_4) (CONTROL_REGISTER_4&0x5) + +/* +* CONTROL_REGISTER_2 FUNCTIONS +*/ + +extern "C" uint32_t GetCR2(); + +/* +* CONTROL_REGISTER_3 FUNCTIONS +*/ + +extern "C" uint32_t GetCR3(); \ No newline at end of file diff --git a/src/kernel/cpu.s b/src/kernel/cpu.s index 9a40270..2df41db 100644 --- a/src/kernel/cpu.s +++ b/src/kernel/cpu.s @@ -36,4 +36,28 @@ GetEFLAGS: mov %ebp, %esp pop %ebp - ret \ No newline at end of file + ret + +.globl GetCR2 +GetCR2: + push %ebp + mov %esp, %ebp + + xor %eax, %eax + mov %cr2, %eax + + mov %ebp, %esp + pop %ebp + ret + +.globl GetCR3 +GetCR3: + push %ebp + mov %esp, %ebp + + xor %eax, %eax + mov %cr3, %eax + + mov %ebp, %esp + pop %ebp + ret diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 3251521..8409b44 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -2,8 +2,7 @@ extern "C" void kernel_main (BootInfo* bootinfo) { - init_serial(); - //pit_initialise(); + pit_initialise(); startSuperVisorTerminal(bootinfo); } @@ -17,9 +16,38 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ initGDT(); kterm_init(); init_serial(); - print_serial("Hello Higher half kernel!"); - printf("DDDDDDDDDDDDDDDD"); - return; + print_serial("Hello Higher half kernel!\n"); + + init_idt(); + // Enable interrupts + asm volatile("STI"); + + // map the multiboot structure into virtual memory + // so we can gather the necessary data from it. + /* const uint32_t KERNEL_BASE_ADDR = 0xC0000000; + + uint32_t pageDirectoryIndex = (addr + KERNEL_BASE_ADDR) >> 22; + printf("pageDirectoryIndex: %d\n", pageDirectoryIndex); + + uint32_t pageTableIndex = (addr + KERNEL_BASE_ADDR >> 12) & 0x1FFF; + printf("PagTableIndex: %d\n", pageTableIndex); + + printf("boot_page_directory addr: 0x%x\n", &boot_page_directory); + printf("boot_page_table addr: 0x%x\n", &boot_page_table); + + uint32_t* pageDirectoryEntry = (uint32_t*) ((uint32_t) &boot_page_directory) + (pageDirectoryIndex * 4); + printf("page_directory_entry addr: 0x%x\n", pageDirectoryEntry); + + *pageDirectoryEntry = ( addr & 0xFFFFF000 ) | 0x003; + + uint32_t* page_table_entry = (uint32_t*) ((uint32_t) &boot_page_table) + ( pageTableIndex * 4); + printf("page_table_entry addr: 0x%x\n" , page_table_entry); + + *page_table_entry = addr | 0x003; + + // Reload CR3 to force a flush + asm("movl %cr3, %ecx;" "movl %ecx, %cr3" ); + */ /** * Check Multiboot magic number * NOTE: Printf call should not be a thing this early on ... @@ -33,8 +61,7 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ * Show a little banner for cuteness */ printf("|=== BarinkOS ===|\n"); - printf("Kernel Begin AT(0x%x)", kernel_begin); - + /** * Use the address given as an argument as the pointer * to a Multiboot information structure. @@ -111,16 +138,11 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ //InitializePaging(); //IdentityMap(); //Enable(); + } else{ + printf("memory flag not set!"); } - //initGDT(); - //init_idt(); - // Enable interrupts - //asm volatile("STI"); - - - //CheckMBT( (multiboot_info_t *) addr); - + CheckMBT( (multiboot_info_t *) addr); kernel_main(&bootinfo); diff --git a/src/kernel/kernel.h b/src/kernel/kernel.h index 1f15f6a..d9c6a9c 100644 --- a/src/kernel/kernel.h +++ b/src/kernel/kernel.h @@ -28,7 +28,7 @@ extern "C" #include "time.h" #include "SuperVisorTerminal/superVisorTerminal.h" -#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) +#define CHECK_FLAG(flag, bit) ( flag & (1 << bit )) #define PANIC(message) {return;} -- 2.39.5 From 9436e6e0332ee2564b01497b81e272ac379166e2 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 19 Aug 2022 01:05:10 +0200 Subject: [PATCH 066/115] End of the day cleanup. * Added symbol files to .gitignore * Improved text in #PG and #GP handlers * Added the printing of the multiboot structure address and the magic value * Added page fault screenshot to readme --- .gitignore | 2 ++ README.md | 5 ++++ screenshots/PageFault.png | 3 +++ src/kernel/Interrupts/idt/idt.cpp | 38 +++++++++++++++---------------- src/kernel/kernel.cpp | 6 +++-- 5 files changed, 32 insertions(+), 22 deletions(-) create mode 100644 screenshots/PageFault.png diff --git a/.gitignore b/.gitignore index 3ac905f..82ca499 100644 --- a/.gitignore +++ b/.gitignore @@ -5,4 +5,6 @@ isodir/ root/ *.iso *.img +*.sym + diff --git a/README.md b/README.md index 2e5fbb6..155afd0 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,11 @@ W.I.P - Working on interrupt handling ![Multiboot integration](screenshots/multiboot.png) \ Multiboot information can be read by the kernel. + +![Page faulting](screenshots/PageFault.png) \ +Enabled paging and am getting page faults! + + ________________________ ### The goal diff --git a/screenshots/PageFault.png b/screenshots/PageFault.png new file mode 100644 index 0000000..adc5332 --- /dev/null +++ b/screenshots/PageFault.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:edf3a8ff640f0a3fbf58756d10526ee3bc03068d0cea4d81d64a897d52e29c85 +size 10406 diff --git a/src/kernel/Interrupts/idt/idt.cpp b/src/kernel/Interrupts/idt/idt.cpp index 4c5f934..8b4fd83 100644 --- a/src/kernel/Interrupts/idt/idt.cpp +++ b/src/kernel/Interrupts/idt/idt.cpp @@ -122,31 +122,29 @@ void irs_handler (registers regs) { // General Protection Exception #GP printf("#GP\n"); - - printf("ERR_CODE: 0x%x", regs.err_code); + printf("Accessing memory caused a general protectuion exception.\n"); - if( regs.err_code & 0x1) - { - printf("Originated externally!"); - } + printf("Fault due to entry at index: %d", (regs.err_code >> 3 & 0xFFF ) ); if(regs.err_code & 0x3 >> 1 == 0 ){ - printf("Index references GDT"); + printf("* Index references GDT"); } if(regs.err_code & 0x3 >> 1 == 1 ){ - printf("Index references IDT"); + printf("* Index references IDT"); } if(regs.err_code & 0x3 >> 1 == 2 ){ - printf("Index references LDT"); + printf("* Index references LDT"); } if(regs.err_code & 0x3 >> 1 == 4 ){ - printf("Index references IDT"); + printf("* Index references IDT"); } - - printf("Index: ", (regs.err_code >> 3 & 0xFFF ) ); + if( regs.err_code & 0x1) + { + printf("* Originated externally!"); + } __asm__("cli;" "1: hlt;" "jmp 1b;"); @@ -157,7 +155,7 @@ void irs_handler (registers regs) { printf("#PF\n"); FaultingAddress = GetCR2(); - printf("Faulting instruction adddress: 0x%x\n", FaultingAddress); + printf("Accessing the linear address 0x%x resulted in a page fault!\n\n", FaultingAddress); // Error code of 32 bits are on the stack // CR2 register contains the 32-bit linear virtual address that generated the exception @@ -171,27 +169,27 @@ void irs_handler (registers regs) { #define PF_ERR_SHADOW_STACK_BIT 0x7 #define PF_ERR_SOFTWARE_GUARD_EXTENSION_BIT 0xE - printf("Determining cause of fault...\n"); + printf("REASON: \n\n"); if (regs.err_code & PF_ERR_PRESENT_BIT ){ - printf("Page protection violation!\n"); + printf("* Page protection violation!\n"); } else{ - printf("page not-present!\n"); + printf("* Page not-present!\n"); } if(regs.err_code & PF_ERR_WRITE_BIT){ - printf("Write access violation!\n"); + printf("* Write access violation!\n"); } else{ - printf("Read access violation!\n"); + printf("* Read access violation!\n"); } if(regs.err_code & PF_ERR_USER_BIT){ - printf("Violation from user-space (CPL=3)\n"); + printf("* Violation from user-space (CPL=3)\n"); } if(regs.err_code & PF_ERR_INSTRUCTION_FETCH_BIT){ - printf("Caused by an instruction fetch. \n"); + printf("* Caused by an instruction fetch. \n"); } /* diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 8409b44..22aa47f 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -48,6 +48,8 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ // Reload CR3 to force a flush asm("movl %cr3, %ecx;" "movl %ecx, %cr3" ); */ + + printf("DEBUG:\n Magic: 0x%x\n MBT_addr: 0x%x\n", magic, addr); /** * Check Multiboot magic number * NOTE: Printf call should not be a thing this early on ... @@ -61,12 +63,12 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ * Show a little banner for cuteness */ printf("|=== BarinkOS ===|\n"); - + const uint32_t KERNEL_BASE_ADDR = 0xC0000000; /** * Use the address given as an argument as the pointer * to a Multiboot information structure. */ - multiboot_info_t* mbt = (multiboot_info_t*) addr; + multiboot_info_t* mbt = (multiboot_info_t*) (addr + KERNEL_BASE_ADDR); /** * Construct our own bootInfo structure -- 2.39.5 From 560dd64e64d54230254db7143381e3a7982dd447 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 19 Aug 2022 23:44:38 +0200 Subject: [PATCH 067/115] Kernel is working in its full former glory as a higher half kernel --- src/kernel/KernelLauncher/boot.s | 8 ++- src/kernel/Memory/paging.cpp | 13 +++-- src/kernel/kernel.cpp | 95 +++++++++++++++++--------------- 3 files changed, 66 insertions(+), 50 deletions(-) diff --git a/src/kernel/KernelLauncher/boot.s b/src/kernel/KernelLauncher/boot.s index 8b61af0..b627cfa 100644 --- a/src/kernel/KernelLauncher/boot.s +++ b/src/kernel/KernelLauncher/boot.s @@ -28,10 +28,14 @@ stack_top: */ .section .bss, "aw", @nobits .align 4096 +.globl boot_page_directory boot_page_directory: .skip 4096 boot_page_table: .skip 4096 +.globl multiboot_page_table +multiboot_page_table: + .skip 4096 # More page tables may be required # Entry point @@ -98,9 +102,9 @@ _start: 4: # At this point, paging is fully set up and enabled isPaging: - # Unmap the identity mapping as it is now unnecessary + # Unmap the identity mapping as it is now unnecessary movl $0, boot_page_directory + 0 - + # Reload cr3 to force tlb flush movl %cr3, %ecx movl %ecx, %cr3 diff --git a/src/kernel/Memory/paging.cpp b/src/kernel/Memory/paging.cpp index 67df499..41274f1 100644 --- a/src/kernel/Memory/paging.cpp +++ b/src/kernel/Memory/paging.cpp @@ -1,7 +1,7 @@ #include "paging.h" -PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]__attribute__((aligned(4096))); +/*PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]__attribute__((aligned(4096))); -PageTableEntry first_page_table[MAX_PAGE_TABLE_ENTRIES]__attribute__((aligned(4096))); +//PageTableEntry first_page_table[MAX_PAGE_TABLE_ENTRIES]__attribute__((aligned(4096))); void IdentityMap (){ printf("\nInit paging\n"); @@ -43,6 +43,7 @@ void InitializePaging() Initial kernel page directory set all page tables to not present */ + /* for (int i = 0; i < MAX_DIRECTORY_ENTRIES; i++) { kernel_directory[i] = 0x2; @@ -57,6 +58,7 @@ void InitializePaging() uint8_t NUM_PDE = BIOSAddr_Max / (4 * 1024 * 1024); printf("The first 8MiB require %d Page Directory Entries\n", NUM_PDE); + */ /* for( int i = 0; i < NUM_PDE; i++) { @@ -71,7 +73,7 @@ void InitializePaging() // add page table as page directory entry kernel_directory[i] = ( (unsigned int) pagetable ) | 3; } -*/ + // map the kernel space VIRTUAL_ADDRESS Vaddr = KERNEL_VRT_MEMORY_BEGIN; PHYSICAL_ADDRESS KernelAddr = kernel_begin; @@ -82,7 +84,7 @@ void InitializePaging() NUM_PDE = KernelSizeInBytes / (4 * 1024* 1024); printf("Kernel requires %d Page Directory Entries\n", NUM_PDE); -/* + for(int i = 0; i < NUM_PDE; i++) { PageTableEntry pageTable [MAX_PAGE_TABLE_ENTRIES] = PhysicalMemory::allocate_block(); @@ -97,7 +99,7 @@ void InitializePaging() } - */ + @@ -168,3 +170,4 @@ void Enable() } } +*/ \ No newline at end of file diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index 22aa47f..bbab188 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -1,13 +1,11 @@ #include "kernel.h" +void map_multiboot_info_structure(unsigned long addr); +extern "C" void kernel_main (BootInfo* bootinfo); +extern "C" uint32_t boot_page_directory; +extern "C" uint32_t multiboot_page_table; -extern "C" void kernel_main (BootInfo* bootinfo) { - pit_initialise(); - - startSuperVisorTerminal(bootinfo); -} - - +const uint32_t KERNEL_BASE_ADDR = 0xC0000000; extern "C" void early_main(unsigned long magic, unsigned long addr){ /** * Initialize terminal interface @@ -21,34 +19,9 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ init_idt(); // Enable interrupts asm volatile("STI"); - - // map the multiboot structure into virtual memory - // so we can gather the necessary data from it. - /* const uint32_t KERNEL_BASE_ADDR = 0xC0000000; - - uint32_t pageDirectoryIndex = (addr + KERNEL_BASE_ADDR) >> 22; - printf("pageDirectoryIndex: %d\n", pageDirectoryIndex); - - uint32_t pageTableIndex = (addr + KERNEL_BASE_ADDR >> 12) & 0x1FFF; - printf("PagTableIndex: %d\n", pageTableIndex); - - printf("boot_page_directory addr: 0x%x\n", &boot_page_directory); - printf("boot_page_table addr: 0x%x\n", &boot_page_table); - - uint32_t* pageDirectoryEntry = (uint32_t*) ((uint32_t) &boot_page_directory) + (pageDirectoryIndex * 4); - printf("page_directory_entry addr: 0x%x\n", pageDirectoryEntry); - - *pageDirectoryEntry = ( addr & 0xFFFFF000 ) | 0x003; - - uint32_t* page_table_entry = (uint32_t*) ((uint32_t) &boot_page_table) + ( pageTableIndex * 4); - printf("page_table_entry addr: 0x%x\n" , page_table_entry); - - *page_table_entry = addr | 0x003; - - // Reload CR3 to force a flush - asm("movl %cr3, %ecx;" "movl %ecx, %cr3" ); - */ + map_multiboot_info_structure(addr); + printf("DEBUG:\n Magic: 0x%x\n MBT_addr: 0x%x\n", magic, addr); /** * Check Multiboot magic number @@ -63,12 +36,11 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ * Show a little banner for cuteness */ printf("|=== BarinkOS ===|\n"); - const uint32_t KERNEL_BASE_ADDR = 0xC0000000; /** * Use the address given as an argument as the pointer * to a Multiboot information structure. */ - multiboot_info_t* mbt = (multiboot_info_t*) (addr + KERNEL_BASE_ADDR); + multiboot_info_t* mbt = (multiboot_info_t*) (addr ); /** * Construct our own bootInfo structure @@ -79,10 +51,10 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ /* If we got a memory map from our bootloader we should be parsing it to find out the memory regions available. - */ + */ if (CHECK_FLAG(mbt->flags, 6)) { - + /* Setup Physical memory managment */ @@ -92,15 +64,19 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ mapMultibootMemoryMap(bootinfo.memory , mbt); printf("Memory size: 0x%x bytes\n", bootinfo.memory->TotalMemory ); + /* PhysicalMemory memAlloc = PhysicalMemory{}; memAlloc.setup(bootinfo.memory ); + */ + // TODO: FIX physical allocator /* Mark already in use sections */ // Mark kernel memory as used - printf("Kernel Begin Pointer: 0x%x, Kernel end pointer: 0x%x\n", kernel_begin , kernel_end ); + printf("Kernel Begin Pointer: 0x%x, Kernel end pointer: 0x%x\n", &kernel_begin , &kernel_end ); + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; @@ -110,16 +86,16 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ } else{ printf("allocate region: 0x%x, size : 0x%x bytes\n", (unsigned) mmap->addr,(unsigned) mmap->len ); - memAlloc.allocate_region((unsigned)mmap->addr , (unsigned)mmap->len); + // memAlloc.allocate_region((unsigned)mmap->addr , (unsigned)mmap->len); } } - printf("allocate region: 0x%x, size : 0x%x bytes\n", kernel_begin, kernel_end - kernel_begin ); - memAlloc.allocate_region(kernel_end, kernel_end - kernel_begin); - + printf("allocate region: 0x%x, size : 0x%x bytes\n", &kernel_begin, &kernel_end - &kernel_begin ); + //memAlloc.allocate_region(kernel_end, kernel_end - kernel_begin); + // test alloc_block /* uint8_t* memory = (uint8_t*) memAlloc.allocate_block(); @@ -150,3 +126,36 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ } +void map_multiboot_info_structure(unsigned long addr){ + // map the multiboot structure into virtual memory + // so we can gather the necessary data from it. + + uint32_t pageDirectoryIndex = (addr ) >> 22; + printf("pageDirectoryIndex: %d\n", pageDirectoryIndex); + + uint32_t pageTableIndex = (addr >> 12) & 0x1FFF; + printf("PagTableIndex: %d\n", pageTableIndex); + + + printf("boot_page_directory addr: 0x%x\n", &boot_page_directory); + printf("boot_page_table addr: 0x%x\n", &multiboot_page_table); + + uint32_t* current_page_directory = &boot_page_directory; + uint32_t* needed_page_table = &multiboot_page_table - KERNEL_BASE_ADDR; + // set the page tabel reference; + current_page_directory[pageDirectoryIndex] = (uint32_t)&multiboot_page_table - KERNEL_BASE_ADDR + 0x003; + + // set the page reference; + needed_page_table[ pageTableIndex ] = addr | 0x003; + + + // Reload CR3 to force a flush + asm("movl %cr3, %ecx;" "movl %ecx, %cr3" ); +} + + +extern "C" void kernel_main (BootInfo* bootinfo) { + pit_initialise(); + + startSuperVisorTerminal(bootinfo); +} \ No newline at end of file -- 2.39.5 From e70f56a0053c7429fed3a1b16155e91e54921efe Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 21 Aug 2022 21:15:15 +0200 Subject: [PATCH 068/115] Improving the memory mapping boot code Removed the need to map the extra MBI structure in as a seperate pagetable Renaming / Restructuring the memory folder --- Makefile | 7 ++-- screenshots/must frustrating bug ever.png | 3 ++ src/grub.cfg | 5 --- src/kernel/KernelLauncher/boot.s | 13 ++----- src/kernel/KernelLauncher/bootcheck.h | 2 +- src/kernel/KernelLauncher/launcher.cpp | 28 +++++++++++++++ src/kernel/Memory/KernelHeap.h | 2 ++ .../{memory.cpp => PhysicalMemoryManager.cpp} | 8 +++-- .../{memory.h => PhysicalMemoryManager.h} | 4 ++- .../{paging.cpp => VirtualMemoryManager.cpp} | 36 +++++++++---------- .../{paging.h => VirtualMemoryManager.h} | 0 src/kernel/Terminal/kterm.h | 1 - src/kernel/kernel.cpp | 12 ++++--- src/kernel/linker.ld | 1 + 14 files changed, 75 insertions(+), 47 deletions(-) create mode 100644 screenshots/must frustrating bug ever.png create mode 100644 src/kernel/KernelLauncher/launcher.cpp create mode 100644 src/kernel/Memory/KernelHeap.h rename src/kernel/Memory/{memory.cpp => PhysicalMemoryManager.cpp} (92%) rename src/kernel/Memory/{memory.h => PhysicalMemoryManager.h} (91%) rename src/kernel/Memory/{paging.cpp => VirtualMemoryManager.cpp} (75%) rename src/kernel/Memory/{paging.h => VirtualMemoryManager.h} (100%) diff --git a/Makefile b/Makefile index 8b655ac..95f137b 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/launcher.o SRC_DIR = src BUILD_DIR = build @@ -102,4 +102,7 @@ $(BUILD_DIR)/memory.o: $(CPP) -c $(SRC_DIR)/kernel/Memory/memory.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/paging.o: - $(CPP) -c $(SRC_DIR)/kernel/Memory/paging.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file + $(CPP) -c $(SRC_DIR)/kernel/Memory/paging.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/launcher.o: + $(CPP) -c $(SRC_DIR)/kernel/KernelLauncher/launcher.cpp -o $(BUILD_DIR)/launcher.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file diff --git a/screenshots/must frustrating bug ever.png b/screenshots/must frustrating bug ever.png new file mode 100644 index 0000000..5b908d8 --- /dev/null +++ b/screenshots/must frustrating bug ever.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a55e6e0d5beb8d3d390c6877c9eabc7f8e7aa539d124e24f433ae4eda4cf4c21 +size 10397 diff --git a/src/grub.cfg b/src/grub.cfg index 27391d2..df39e08 100644 --- a/src/grub.cfg +++ b/src/grub.cfg @@ -1,8 +1,3 @@ -GRUB_DEFAULT=0 -GRUB_TIMEOUT=-1 -GRUB_HIDDEN_TIMEOUT=0 -GRUB_HIDDEN_TIMEOUT_QUITE=true - menuentry "BarinkOS" { multiboot /boot/myos.bin } diff --git a/src/kernel/KernelLauncher/boot.s b/src/kernel/KernelLauncher/boot.s index b627cfa..140630c 100644 --- a/src/kernel/KernelLauncher/boot.s +++ b/src/kernel/KernelLauncher/boot.s @@ -47,12 +47,7 @@ _start: movl $(boot_page_table - 0xC0000000), %edi # Map address 0 movl $0, %esi - # Map 1023 pages the 1024th being the VGA text buffer - movl $1023, %ecx - -1: # Map the kernel - cmpl $_kernel_start, %esi - jl 2f +1: cmpl $(_kernel_end - 0xC0000000), %esi jge 3f @@ -125,12 +120,8 @@ isPaging: call early_main - mov %cr0, %eax - or $1, %eax - mov %eax, %cr0 - - //call kernel_main + cli diff --git a/src/kernel/KernelLauncher/bootcheck.h b/src/kernel/KernelLauncher/bootcheck.h index 1a11c05..50335d2 100644 --- a/src/kernel/KernelLauncher/bootcheck.h +++ b/src/kernel/KernelLauncher/bootcheck.h @@ -1,7 +1,7 @@ #pragma once #include "../multiboot.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) - +#define __VERBOSE__ #include "../Terminal/kterm.h" diff --git a/src/kernel/KernelLauncher/launcher.cpp b/src/kernel/KernelLauncher/launcher.cpp new file mode 100644 index 0000000..471053c --- /dev/null +++ b/src/kernel/KernelLauncher/launcher.cpp @@ -0,0 +1,28 @@ +#include +#include + +void put_char(char ch, size_t x, size_t y ){ + *((uint16_t*)0xb8000+(y * 80 + x)) = ch | ((7 | 0 << 4) << 8); +} + +void write_ln(char* s, size_t length, size_t x , size_t y) +{ + // Because read only data is linked at a virtual address we'll need to convert + // the string adddres from virtual to phys. + s = s - 0xC0000000; + size_t column , row; + column = x; + row = y; + for(int i = 0; i < length ; i ++) + { + + put_char(s[i] , column,row ); + column ++; + + } + +} + +extern "C" void testLauncher () { + write_ln("hello", 5 ,0,0); +} \ No newline at end of file diff --git a/src/kernel/Memory/KernelHeap.h b/src/kernel/Memory/KernelHeap.h new file mode 100644 index 0000000..84a1624 --- /dev/null +++ b/src/kernel/Memory/KernelHeap.h @@ -0,0 +1,2 @@ +#pragma once + diff --git a/src/kernel/Memory/memory.cpp b/src/kernel/Memory/PhysicalMemoryManager.cpp similarity index 92% rename from src/kernel/Memory/memory.cpp rename to src/kernel/Memory/PhysicalMemoryManager.cpp index 3106c7c..a24ff3d 100644 --- a/src/kernel/Memory/memory.cpp +++ b/src/kernel/Memory/PhysicalMemoryManager.cpp @@ -102,11 +102,13 @@ void PhysicalMemory::deallocate_region(uint32_t StartAddress , uint32_t size ) void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt) { - printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", - (unsigned) mbt->mmap_addr, (unsigned) mbt->mmap_length); + + printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", (unsigned) mbt->mmap_addr , (unsigned) mbt->mmap_length ); + + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; - for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ diff --git a/src/kernel/Memory/memory.h b/src/kernel/Memory/PhysicalMemoryManager.h similarity index 91% rename from src/kernel/Memory/memory.h rename to src/kernel/Memory/PhysicalMemoryManager.h index 7b04151..cef690c 100644 --- a/src/kernel/Memory/memory.h +++ b/src/kernel/Memory/PhysicalMemoryManager.h @@ -8,8 +8,10 @@ #include "../Lib/mem.h" #include "../bitmap.h" +// Asumming 32 bit x86 for now! #define BLOCK_SIZE 4092 -#define BLOCKS_PER_WORD 32 // A word is 16 bit in x86 machines according to my google search results! +#define WORD_SIZE 2 +#define BLOCKS_PER_WORD 32 #define KB_TO_BLOCKS(x) (x / BLOCK_SIZE) #define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) diff --git a/src/kernel/Memory/paging.cpp b/src/kernel/Memory/VirtualMemoryManager.cpp similarity index 75% rename from src/kernel/Memory/paging.cpp rename to src/kernel/Memory/VirtualMemoryManager.cpp index 41274f1..45f0344 100644 --- a/src/kernel/Memory/paging.cpp +++ b/src/kernel/Memory/VirtualMemoryManager.cpp @@ -1,7 +1,6 @@ #include "paging.h" -/*PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]__attribute__((aligned(4096))); - -//PageTableEntry first_page_table[MAX_PAGE_TABLE_ENTRIES]__attribute__((aligned(4096))); +// PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]__attribute__((aligned(4096))); +// PageTableEntry first_page_table[MAX_PAGE_TABLE_ENTRIES]__attribute__((aligned(4096))); void IdentityMap (){ printf("\nInit paging\n"); @@ -11,7 +10,7 @@ void IdentityMap (){ int i = 0; while ( i < 1024) { - kernel_directory[i] = 0x2; + // kernel_directory[i] = 0x2; i++; } @@ -20,7 +19,7 @@ void IdentityMap (){ unsigned int j ; for( j = 0; j < 1024; j++ ) { - first_page_table[j] = (j * 0x1000) | 3 ; + // first_page_table[j] = (j * 0x1000) | 3 ; //Attributes: //Supervisor Level , @@ -32,7 +31,7 @@ void IdentityMap (){ // Put the page table in the page directory // attributes: supervisor level, read/write, present; - kernel_directory[0] = ((unsigned int)first_page_table) | 3; + // kernel_directory[0] = ((unsigned int)first_page_table) | 3; printf("Init paging DONE\n"); } @@ -43,10 +42,10 @@ void InitializePaging() Initial kernel page directory set all page tables to not present */ - /* + for (int i = 0; i < MAX_DIRECTORY_ENTRIES; i++) { - kernel_directory[i] = 0x2; + // kernel_directory[i] = 0x2; } // BIOS Address Identity mapping @@ -58,20 +57,20 @@ void InitializePaging() uint8_t NUM_PDE = BIOSAddr_Max / (4 * 1024 * 1024); printf("The first 8MiB require %d Page Directory Entries\n", NUM_PDE); - */ -/* + + for( int i = 0; i < NUM_PDE; i++) { // setup a page table - PageTableEntry pagetable[MAX_PAGE_TABLE_ENTRIES] = PhysicalMemory::allocate_block(); // TODO :: Physical memory manager functions should be available here. + // PageTableEntry pagetable[MAX_PAGE_TABLE_ENTRIES] = PhysicalMemory::allocate_block(); // TODO :: Physical memory manager functions should be available here. for(int j = 0; j < MAX_PAGE_TABLE_ENTRIES; j++) { - pagetable[j] = ( j * 4096 ) | 3; + // pagetable[j] = ( j * 4096 ) | 3; } // add page table as page directory entry - kernel_directory[i] = ( (unsigned int) pagetable ) | 3; + // kernel_directory[i] = ( (unsigned int) pagetable ) | 3; } // map the kernel space @@ -87,11 +86,11 @@ void InitializePaging() for(int i = 0; i < NUM_PDE; i++) { - PageTableEntry pageTable [MAX_PAGE_TABLE_ENTRIES] = PhysicalMemory::allocate_block(); + // PageTableEntry pageTable [MAX_PAGE_TABLE_ENTRIES] = PhysicalMemory::allocate_block(); for(int j = 0; j < MAX_PAGE_TABLE_ENTRIES; j++) { - pageTable[j] = ( j * 4096) | 3; // NOTE: Check if page is actually supposed to be present + // pageTable[j] = ( j * 4096) | 3; // NOTE: Check if page is actually supposed to be present } // TODO: Calculate Page Directory index @@ -145,9 +144,9 @@ void Enable() CR0 = GetCR0(); printf("PG bit = %d \n" , GET_PG_BIT(CR0)); - printf("Load into CR3 address: 0x%x\n", (uint32_t)(&kernel_directory[0])); - loadPageDirectory(&kernel_directory[0]); - enablePaging(); + // printf("Load into CR3 address: 0x%x\n", (uint32_t)(&kernel_directory[0])); + // loadPageDirectory(&kernel_directory[0]); + // enablePaging(); printf("Paging enabled!\n"); @@ -170,4 +169,3 @@ void Enable() } } -*/ \ No newline at end of file diff --git a/src/kernel/Memory/paging.h b/src/kernel/Memory/VirtualMemoryManager.h similarity index 100% rename from src/kernel/Memory/paging.h rename to src/kernel/Memory/VirtualMemoryManager.h diff --git a/src/kernel/Terminal/kterm.h b/src/kernel/Terminal/kterm.h index b260b73..915c08a 100644 --- a/src/kernel/Terminal/kterm.h +++ b/src/kernel/Terminal/kterm.h @@ -1,7 +1,6 @@ #pragma once #include #include -#include #include #include "../Drivers/VGA/colors.h" diff --git a/src/kernel/kernel.cpp b/src/kernel/kernel.cpp index bbab188..e120dab 100644 --- a/src/kernel/kernel.cpp +++ b/src/kernel/kernel.cpp @@ -7,6 +7,9 @@ extern "C" uint32_t multiboot_page_table; const uint32_t KERNEL_BASE_ADDR = 0xC0000000; extern "C" void early_main(unsigned long magic, unsigned long addr){ + + // Convert MBI address to higher quarter kernel space + addr += KERNEL_BASE_ADDR; /** * Initialize terminal interface * NOTE: This should be done later on , the magic value should be checked first. @@ -20,7 +23,6 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ // Enable interrupts asm volatile("STI"); - map_multiboot_info_structure(addr); printf("DEBUG:\n Magic: 0x%x\n MBT_addr: 0x%x\n", magic, addr); /** @@ -78,7 +80,7 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ printf("Kernel Begin Pointer: 0x%x, Kernel end pointer: 0x%x\n", &kernel_begin , &kernel_end ); - multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) (mbt->mmap_addr + KERNEL_BASE_ADDR) ; for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ @@ -120,8 +122,10 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ printf("memory flag not set!"); } - CheckMBT( (multiboot_info_t *) addr); - + CheckMBT( (multiboot_info_t *) addr); + asm volatile("mov %cr0, %eax "); + asm volatile("or $1, %eax"); + asm volatile("mov %eax, %cr0"); kernel_main(&bootinfo); } diff --git a/src/kernel/linker.ld b/src/kernel/linker.ld index bcb2584..b564172 100644 --- a/src/kernel/linker.ld +++ b/src/kernel/linker.ld @@ -16,6 +16,7 @@ SECTIONS .multiboot.text : { *(multiboot.text) + *launcher.o(.text) } . += 0xC0000000; /* Addresses in the following code need to be above the 3Gb mark */ -- 2.39.5 From 0f0fc9f252ca030f3b28878c9f81f38b9d931c1d Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 21 Aug 2022 21:18:53 +0200 Subject: [PATCH 069/115] Adding a skeleton for the memory management code Moved the PMM away from being object orientated as it is just plain annoying renamed src folder to source Set timeout to 5 seconds in the grub config --- Makefile | 6 +- {src => source}/grub.cfg | 0 {src => source}/kernel/Drivers/PCI/pci.cpp | 0 {src => source}/kernel/Drivers/PCI/pci.h | 0 {src => source}/kernel/Drivers/PIC/pic.cpp | 0 {src => source}/kernel/Drivers/PIC/pic.h | 0 {src => source}/kernel/Drivers/PIT/pit.cpp | 0 {src => source}/kernel/Drivers/PIT/pit.h | 0 .../kernel/Drivers/PS-2/keyboard.cpp | 0 .../kernel/Drivers/PS-2/keyboard.h | 0 .../kernel/Drivers/Serial/serial.cpp | 0 .../kernel/Drivers/Serial/serial.h | 0 {src => source}/kernel/Drivers/VGA/VBE.h | 0 {src => source}/kernel/Drivers/VGA/colors.h | 0 {src => source}/kernel/Drivers/cmos/cmos.cpp | 0 .../kernel/FileSystem/FAT/FAT16.cpp | 0 {src => source}/kernel/FileSystem/FAT/FAT16.h | 0 {src => source}/kernel/Interrupts/idt/idt.cpp | 0 {src => source}/kernel/Interrupts/idt/idt.h | 0 {src => source}/kernel/Interrupts/idt/idt.s | 0 .../kernel/Interrupts/idt/scancodes/set1.h | 0 {src => source}/kernel/KernelLauncher/boot.s | 0 .../kernel/KernelLauncher/bootcheck.h | 2 +- {src => source}/kernel/KernelLauncher/crti.s | 0 {src => source}/kernel/KernelLauncher/crtn.s | 0 .../kernel/KernelLauncher/launcher.cpp | 0 {src => source}/kernel/Lib/mem.h | 0 {src => source}/kernel/Lib/string.c | 0 {src => source}/kernel/Lib/string.h | 0 {src => source}/kernel/Memory/GDT/gdt.s | 0 {src => source}/kernel/Memory/GDT/gdtc.cpp | 0 {src => source}/kernel/Memory/GDT/gdtc.h | 0 source/kernel/Memory/KernelHeap.cpp | 51 ++++++ source/kernel/Memory/KernelHeap.h | 9 + source/kernel/Memory/MBIMMap/MBI_MMap.cpp | 43 +++++ source/kernel/Memory/MBIMMap/MBI_MMap.h | 16 ++ .../kernel/Memory/PhysicalMemoryManager.cpp | 102 +++++++++++ source/kernel/Memory/PhysicalMemoryManager.h | 30 +++ source/kernel/Memory/VirtualMemoryManager.cpp | 24 +++ source/kernel/Memory/VirtualMemoryManager.h | 12 ++ {src => source}/kernel/Memory/memoryinfo.h | 0 .../kernel/Memory/paging.definitions.h | 0 {src => source}/kernel/Memory/paging.s | 0 .../SuperVisorTerminal/superVisorTerminal.cpp | 2 +- .../SuperVisorTerminal/superVisorTerminal.h | 2 +- {src => source}/kernel/Terminal/kterm.cpp | 0 {src => source}/kernel/Terminal/kterm.h | 0 {src => source}/kernel/bitmap.h | 0 {src => source}/kernel/bootinfo.h | 0 {src => source}/kernel/cpu.h | 0 {src => source}/kernel/cpu.s | 0 {src => source}/kernel/definitions.h | 0 {src => source}/kernel/io.cpp | 0 {src => source}/kernel/io.h | 0 {src => source}/kernel/irq_table.s | 0 {src => source}/kernel/irs_table.s | 0 {src => source}/kernel/kernel.cpp | 8 +- {src => source}/kernel/kernel.h | 16 +- {src => source}/kernel/linker.ld | 0 {src => source}/kernel/multiboot.h | 0 {src => source}/kernel/serial.h | 0 {src => source}/kernel/time.cpp | 0 {src => source}/kernel/time.h | 0 {src => source}/kernel/timer.cpp | 0 {src => source}/kernel/timer.h | 0 src/kernel/Memory/KernelHeap.h | 2 - src/kernel/Memory/PhysicalMemoryManager.cpp | 144 --------------- src/kernel/Memory/PhysicalMemoryManager.h | 50 ----- src/kernel/Memory/VirtualMemoryManager.cpp | 171 ------------------ src/kernel/Memory/VirtualMemoryManager.h | 22 --- 70 files changed, 308 insertions(+), 404 deletions(-) rename {src => source}/grub.cfg (100%) rename {src => source}/kernel/Drivers/PCI/pci.cpp (100%) rename {src => source}/kernel/Drivers/PCI/pci.h (100%) rename {src => source}/kernel/Drivers/PIC/pic.cpp (100%) rename {src => source}/kernel/Drivers/PIC/pic.h (100%) rename {src => source}/kernel/Drivers/PIT/pit.cpp (100%) rename {src => source}/kernel/Drivers/PIT/pit.h (100%) rename {src => source}/kernel/Drivers/PS-2/keyboard.cpp (100%) rename {src => source}/kernel/Drivers/PS-2/keyboard.h (100%) rename {src => source}/kernel/Drivers/Serial/serial.cpp (100%) rename {src => source}/kernel/Drivers/Serial/serial.h (100%) rename {src => source}/kernel/Drivers/VGA/VBE.h (100%) rename {src => source}/kernel/Drivers/VGA/colors.h (100%) rename {src => source}/kernel/Drivers/cmos/cmos.cpp (100%) rename {src => source}/kernel/FileSystem/FAT/FAT16.cpp (100%) rename {src => source}/kernel/FileSystem/FAT/FAT16.h (100%) rename {src => source}/kernel/Interrupts/idt/idt.cpp (100%) rename {src => source}/kernel/Interrupts/idt/idt.h (100%) rename {src => source}/kernel/Interrupts/idt/idt.s (100%) rename {src => source}/kernel/Interrupts/idt/scancodes/set1.h (100%) rename {src => source}/kernel/KernelLauncher/boot.s (100%) rename {src => source}/kernel/KernelLauncher/bootcheck.h (97%) rename {src => source}/kernel/KernelLauncher/crti.s (100%) rename {src => source}/kernel/KernelLauncher/crtn.s (100%) rename {src => source}/kernel/KernelLauncher/launcher.cpp (100%) rename {src => source}/kernel/Lib/mem.h (100%) rename {src => source}/kernel/Lib/string.c (100%) rename {src => source}/kernel/Lib/string.h (100%) rename {src => source}/kernel/Memory/GDT/gdt.s (100%) rename {src => source}/kernel/Memory/GDT/gdtc.cpp (100%) rename {src => source}/kernel/Memory/GDT/gdtc.h (100%) create mode 100644 source/kernel/Memory/KernelHeap.cpp create mode 100644 source/kernel/Memory/KernelHeap.h create mode 100644 source/kernel/Memory/MBIMMap/MBI_MMap.cpp create mode 100644 source/kernel/Memory/MBIMMap/MBI_MMap.h create mode 100644 source/kernel/Memory/PhysicalMemoryManager.cpp create mode 100644 source/kernel/Memory/PhysicalMemoryManager.h create mode 100644 source/kernel/Memory/VirtualMemoryManager.cpp create mode 100644 source/kernel/Memory/VirtualMemoryManager.h rename {src => source}/kernel/Memory/memoryinfo.h (100%) rename {src => source}/kernel/Memory/paging.definitions.h (100%) rename {src => source}/kernel/Memory/paging.s (100%) rename {src => source}/kernel/SuperVisorTerminal/superVisorTerminal.cpp (96%) rename {src => source}/kernel/SuperVisorTerminal/superVisorTerminal.h (65%) rename {src => source}/kernel/Terminal/kterm.cpp (100%) rename {src => source}/kernel/Terminal/kterm.h (100%) rename {src => source}/kernel/bitmap.h (100%) rename {src => source}/kernel/bootinfo.h (100%) rename {src => source}/kernel/cpu.h (100%) rename {src => source}/kernel/cpu.s (100%) rename {src => source}/kernel/definitions.h (100%) rename {src => source}/kernel/io.cpp (100%) rename {src => source}/kernel/io.h (100%) rename {src => source}/kernel/irq_table.s (100%) rename {src => source}/kernel/irs_table.s (100%) rename {src => source}/kernel/kernel.cpp (93%) rename {src => source}/kernel/kernel.h (58%) rename {src => source}/kernel/linker.ld (100%) rename {src => source}/kernel/multiboot.h (100%) rename {src => source}/kernel/serial.h (100%) rename {src => source}/kernel/time.cpp (100%) rename {src => source}/kernel/time.h (100%) rename {src => source}/kernel/timer.cpp (100%) rename {src => source}/kernel/timer.h (100%) delete mode 100644 src/kernel/Memory/KernelHeap.h delete mode 100644 src/kernel/Memory/PhysicalMemoryManager.cpp delete mode 100644 src/kernel/Memory/PhysicalMemoryManager.h delete mode 100644 src/kernel/Memory/VirtualMemoryManager.cpp delete mode 100644 src/kernel/Memory/VirtualMemoryManager.h diff --git a/Makefile b/Makefile index 95f137b..038150f 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/launcher.o -SRC_DIR = src +SRC_DIR = source BUILD_DIR = build CRTBEGIN_OBJ = $(shell $(CC) $(CFLAGS) -print-file-name=crtbegin.o) @@ -99,10 +99,10 @@ $(BUILD_DIR)/sv-terminal.o: $(CPP) -c $(SRC_DIR)/kernel/SuperVisorTerminal/superVisorTerminal.cpp -o $(BUILD_DIR)/sv-terminal.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/memory.o: - $(CPP) -c $(SRC_DIR)/kernel/Memory/memory.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/Memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/paging.o: - $(CPP) -c $(SRC_DIR)/kernel/Memory/paging.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/Memory/VirtualMemoryManager.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/launcher.o: $(CPP) -c $(SRC_DIR)/kernel/KernelLauncher/launcher.cpp -o $(BUILD_DIR)/launcher.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file diff --git a/src/grub.cfg b/source/grub.cfg similarity index 100% rename from src/grub.cfg rename to source/grub.cfg diff --git a/src/kernel/Drivers/PCI/pci.cpp b/source/kernel/Drivers/PCI/pci.cpp similarity index 100% rename from src/kernel/Drivers/PCI/pci.cpp rename to source/kernel/Drivers/PCI/pci.cpp diff --git a/src/kernel/Drivers/PCI/pci.h b/source/kernel/Drivers/PCI/pci.h similarity index 100% rename from src/kernel/Drivers/PCI/pci.h rename to source/kernel/Drivers/PCI/pci.h diff --git a/src/kernel/Drivers/PIC/pic.cpp b/source/kernel/Drivers/PIC/pic.cpp similarity index 100% rename from src/kernel/Drivers/PIC/pic.cpp rename to source/kernel/Drivers/PIC/pic.cpp diff --git a/src/kernel/Drivers/PIC/pic.h b/source/kernel/Drivers/PIC/pic.h similarity index 100% rename from src/kernel/Drivers/PIC/pic.h rename to source/kernel/Drivers/PIC/pic.h diff --git a/src/kernel/Drivers/PIT/pit.cpp b/source/kernel/Drivers/PIT/pit.cpp similarity index 100% rename from src/kernel/Drivers/PIT/pit.cpp rename to source/kernel/Drivers/PIT/pit.cpp diff --git a/src/kernel/Drivers/PIT/pit.h b/source/kernel/Drivers/PIT/pit.h similarity index 100% rename from src/kernel/Drivers/PIT/pit.h rename to source/kernel/Drivers/PIT/pit.h diff --git a/src/kernel/Drivers/PS-2/keyboard.cpp b/source/kernel/Drivers/PS-2/keyboard.cpp similarity index 100% rename from src/kernel/Drivers/PS-2/keyboard.cpp rename to source/kernel/Drivers/PS-2/keyboard.cpp diff --git a/src/kernel/Drivers/PS-2/keyboard.h b/source/kernel/Drivers/PS-2/keyboard.h similarity index 100% rename from src/kernel/Drivers/PS-2/keyboard.h rename to source/kernel/Drivers/PS-2/keyboard.h diff --git a/src/kernel/Drivers/Serial/serial.cpp b/source/kernel/Drivers/Serial/serial.cpp similarity index 100% rename from src/kernel/Drivers/Serial/serial.cpp rename to source/kernel/Drivers/Serial/serial.cpp diff --git a/src/kernel/Drivers/Serial/serial.h b/source/kernel/Drivers/Serial/serial.h similarity index 100% rename from src/kernel/Drivers/Serial/serial.h rename to source/kernel/Drivers/Serial/serial.h diff --git a/src/kernel/Drivers/VGA/VBE.h b/source/kernel/Drivers/VGA/VBE.h similarity index 100% rename from src/kernel/Drivers/VGA/VBE.h rename to source/kernel/Drivers/VGA/VBE.h diff --git a/src/kernel/Drivers/VGA/colors.h b/source/kernel/Drivers/VGA/colors.h similarity index 100% rename from src/kernel/Drivers/VGA/colors.h rename to source/kernel/Drivers/VGA/colors.h diff --git a/src/kernel/Drivers/cmos/cmos.cpp b/source/kernel/Drivers/cmos/cmos.cpp similarity index 100% rename from src/kernel/Drivers/cmos/cmos.cpp rename to source/kernel/Drivers/cmos/cmos.cpp diff --git a/src/kernel/FileSystem/FAT/FAT16.cpp b/source/kernel/FileSystem/FAT/FAT16.cpp similarity index 100% rename from src/kernel/FileSystem/FAT/FAT16.cpp rename to source/kernel/FileSystem/FAT/FAT16.cpp diff --git a/src/kernel/FileSystem/FAT/FAT16.h b/source/kernel/FileSystem/FAT/FAT16.h similarity index 100% rename from src/kernel/FileSystem/FAT/FAT16.h rename to source/kernel/FileSystem/FAT/FAT16.h diff --git a/src/kernel/Interrupts/idt/idt.cpp b/source/kernel/Interrupts/idt/idt.cpp similarity index 100% rename from src/kernel/Interrupts/idt/idt.cpp rename to source/kernel/Interrupts/idt/idt.cpp diff --git a/src/kernel/Interrupts/idt/idt.h b/source/kernel/Interrupts/idt/idt.h similarity index 100% rename from src/kernel/Interrupts/idt/idt.h rename to source/kernel/Interrupts/idt/idt.h diff --git a/src/kernel/Interrupts/idt/idt.s b/source/kernel/Interrupts/idt/idt.s similarity index 100% rename from src/kernel/Interrupts/idt/idt.s rename to source/kernel/Interrupts/idt/idt.s diff --git a/src/kernel/Interrupts/idt/scancodes/set1.h b/source/kernel/Interrupts/idt/scancodes/set1.h similarity index 100% rename from src/kernel/Interrupts/idt/scancodes/set1.h rename to source/kernel/Interrupts/idt/scancodes/set1.h diff --git a/src/kernel/KernelLauncher/boot.s b/source/kernel/KernelLauncher/boot.s similarity index 100% rename from src/kernel/KernelLauncher/boot.s rename to source/kernel/KernelLauncher/boot.s diff --git a/src/kernel/KernelLauncher/bootcheck.h b/source/kernel/KernelLauncher/bootcheck.h similarity index 97% rename from src/kernel/KernelLauncher/bootcheck.h rename to source/kernel/KernelLauncher/bootcheck.h index 50335d2..cb7e30c 100644 --- a/src/kernel/KernelLauncher/bootcheck.h +++ b/source/kernel/KernelLauncher/bootcheck.h @@ -31,7 +31,7 @@ void CheckMBT ( multiboot_info_t* mbt ){ if (CHECK_FLAG ( mbi->flags,2)) { #ifdef __VERBOSE__ - printf("cmdline = %s\n", (char *) mbi->cmdline); + printf("cmdline = %s\n", (char *) (mbi->cmdline + 0xC0000000)); #endif } diff --git a/src/kernel/KernelLauncher/crti.s b/source/kernel/KernelLauncher/crti.s similarity index 100% rename from src/kernel/KernelLauncher/crti.s rename to source/kernel/KernelLauncher/crti.s diff --git a/src/kernel/KernelLauncher/crtn.s b/source/kernel/KernelLauncher/crtn.s similarity index 100% rename from src/kernel/KernelLauncher/crtn.s rename to source/kernel/KernelLauncher/crtn.s diff --git a/src/kernel/KernelLauncher/launcher.cpp b/source/kernel/KernelLauncher/launcher.cpp similarity index 100% rename from src/kernel/KernelLauncher/launcher.cpp rename to source/kernel/KernelLauncher/launcher.cpp diff --git a/src/kernel/Lib/mem.h b/source/kernel/Lib/mem.h similarity index 100% rename from src/kernel/Lib/mem.h rename to source/kernel/Lib/mem.h diff --git a/src/kernel/Lib/string.c b/source/kernel/Lib/string.c similarity index 100% rename from src/kernel/Lib/string.c rename to source/kernel/Lib/string.c diff --git a/src/kernel/Lib/string.h b/source/kernel/Lib/string.h similarity index 100% rename from src/kernel/Lib/string.h rename to source/kernel/Lib/string.h diff --git a/src/kernel/Memory/GDT/gdt.s b/source/kernel/Memory/GDT/gdt.s similarity index 100% rename from src/kernel/Memory/GDT/gdt.s rename to source/kernel/Memory/GDT/gdt.s diff --git a/src/kernel/Memory/GDT/gdtc.cpp b/source/kernel/Memory/GDT/gdtc.cpp similarity index 100% rename from src/kernel/Memory/GDT/gdtc.cpp rename to source/kernel/Memory/GDT/gdtc.cpp diff --git a/src/kernel/Memory/GDT/gdtc.h b/source/kernel/Memory/GDT/gdtc.h similarity index 100% rename from src/kernel/Memory/GDT/gdtc.h rename to source/kernel/Memory/GDT/gdtc.h diff --git a/source/kernel/Memory/KernelHeap.cpp b/source/kernel/Memory/KernelHeap.cpp new file mode 100644 index 0000000..bc5abce --- /dev/null +++ b/source/kernel/Memory/KernelHeap.cpp @@ -0,0 +1,51 @@ +#include "KernelHeap.h" + +// Size of heap meta data is 5 bytes +struct heap_block{ + uint8_t Used; + uint32_t Size; +} + +uint32_t heap_size; +heap_block* start ; + +void* malloc(size_t size) +{ + printf("Received request for %d bytes of memory", size); + heap_block* current = start; + + while(current < start + heap_size) + { + if(current->size >= size && current->Used == false ) + { + // We found a spot + // Set the spot to in-use + current->Used = false; + // return the free address + // NOTE: added an offset from the initial address to accomodate for + // meta-data. + return current + sizeof(heap_block); + + } + + current += current->Size + sizeof(heap_block); + } + + // If we are here we need more memory so we should + // probably ask the VMM for more + // TODO: ask for more memory + +} + +void free(void* addr) +{ + // clear the free boolean that corresponds to this adddress + // This should be fairly simple + heap_block* allocatedBlock = addr - sizeof(heap_block); + allocate_block->Used = false; +} + +void initHeap() +{ + +} \ No newline at end of file diff --git a/source/kernel/Memory/KernelHeap.h b/source/kernel/Memory/KernelHeap.h new file mode 100644 index 0000000..e38110b --- /dev/null +++ b/source/kernel/Memory/KernelHeap.h @@ -0,0 +1,9 @@ +#pragma once +#include + + +void initHeap(); + +void* malloc (size_t size ); +void free(void* addr); + diff --git a/source/kernel/Memory/MBIMMap/MBI_MMap.cpp b/source/kernel/Memory/MBIMMap/MBI_MMap.cpp new file mode 100644 index 0000000..dc5da2f --- /dev/null +++ b/source/kernel/Memory/MBIMMap/MBI_MMap.cpp @@ -0,0 +1,43 @@ +#include "MBI_MMap.h" + + +void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt) { + + printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", (unsigned) mbt->mmap_addr , (unsigned) mbt->mmap_length ); + + + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; + + for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + + if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ + + memInfo->TotalMemory += mmap->len; + } else { + memInfo->ReservedMemory += mmap->len; + } + + print_Multiboot_memory_Map(mmap); + + } +} + + + +/** + * @brief Debug Verbose functions + * + * @param mmap + */ + +void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap) { + printf( + "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", + (unsigned) mmap->size, + (unsigned) (mmap->addr >> 32), + (unsigned) (mmap->addr & 0xffffffff), + (unsigned) (mmap->len >> 32), + (unsigned) (mmap->len & 0xffffffff), + (unsigned) mmap->type + ); +} diff --git a/source/kernel/Memory/MBIMMap/MBI_MMap.h b/source/kernel/Memory/MBIMMap/MBI_MMap.h new file mode 100644 index 0000000..bd24198 --- /dev/null +++ b/source/kernel/Memory/MBIMMap/MBI_MMap.h @@ -0,0 +1,16 @@ +#pragma once +#include +#include "../../multiboot.h" +#include "../memoryinfo.h" + +void initialise_available_regions(uint32_t memoryMapAddr, uint32_t memoryMapLastAddr, uint32_t* memoryBitMap, int* used_blocks); + + +void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt); + +/** + * @brief Debug Verbose Functions + * + * @param mmap + */ +void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap); diff --git a/source/kernel/Memory/PhysicalMemoryManager.cpp b/source/kernel/Memory/PhysicalMemoryManager.cpp new file mode 100644 index 0000000..dd8bd5c --- /dev/null +++ b/source/kernel/Memory/PhysicalMemoryManager.cpp @@ -0,0 +1,102 @@ +#include "./PhysicalMemoryManager.h" + +PhysicalMemoryManagerInfoBlock* PMMInfoBlock; + + +void initPMM( MemoryInfo* memory) { + + // NOTE: Lets for now puts the Physical memoryManagerBlock at a random address + // We'll think of a more proper solution a bit later + PMMInfoBlock = (PhysicalMemoryManagerInfoBlock*) 0xCC900000; + + + // calculate the maximum number of blocks + PMMInfoBlock->max_blocks = KB_TO_BLOCKS(memory->TotalMemory); + PMMInfoBlock->used_blocks = 0; + PMMInfoBlock->memoryBitMap = (uint32_t*) 0xCCA00000; + + printf("Maximum Number of blocks: 0x%x, Number of bytes for memMap: 0x%x\n", PMMInfoBlock->max_blocks , (PMMInfoBlock->max_blocks/8)); + + //Size of memory map + uint32_t memMap_size = (PMMInfoBlock->max_blocks / 8 ) ; + + printf("Memory Map size: 0x%x\n", memMap_size ); + printf("size of int in bytes: 0x%x \n" , sizeof(int)); + + // Set all places in memory as free + memset(PMMInfoBlock->memoryBitMap, 0xFF, memMap_size ); +} + +// NOTE: this can only give blocks of 4kb at a time! +void* allocate_block() { + uint8_t blocks_available = PMMInfoBlock->max_blocks - PMMInfoBlock->used_blocks; + // Are there any blocks available? + if( blocks_available <= 0) + { + printf("No blocks available. Blocks Delta: 0x%x\n", blocks_available); + return 0; + } + + // Find 1 free block somewhere + int free_block_index = bitmap_first_unset(PMMInfoBlock->memoryBitMap, (PMMInfoBlock->max_blocks /8) /*memMap Size*/ ); + + + + if(free_block_index == -1) + { + printf("Could not find a good block!\n"); + // Could not find a block + return (void*)0xFFFF; + } + + if(free_block_index == 0) + printf("Somethings wrong!!!\n"); + + // Set the block to be used! + bitmap_unset(PMMInfoBlock->memoryBitMap, free_block_index); + // Increase the used_block count! + PMMInfoBlock->used_blocks++; + printf("used blocks: 0x%x\n", PMMInfoBlock->used_blocks); + // return the pointer to the physical address + return (void*) (BLOCK_SIZE * free_block_index); +} + +void free_block(void* p) { + // If it is a null pointer we don't need to do anything. + if(p==0) { + return; + } + // calculate the index into the bitmap + int index = ((uint32_t) p) / BLOCK_SIZE; + + // set the block to be free + bitmap_set(PMMInfoBlock->memoryBitMap, index); + PMMInfoBlock->used_blocks--; + printf("used blocks: 0x%x, after free\n", PMMInfoBlock->used_blocks); + +} + +void allocate_region(uint32_t startAddress, uint32_t size) { + // every bit should be 4KiB + // every byte is 8*4KiB = 32KiB + + int NumberOfBlocksToAllocate = ( size / 1024) / 4 / 8 + 1; + int startBlock = (startAddress / 1024) / 4 / 8 ; + + // printf("NumberOfBlocksToAllocate: 0x%x\n", NumberOfBlocksToAllocate); + //printf( "start block: 0x%x\n" , startBlock); + for( int i = 0; i < NumberOfBlocksToAllocate; i++) + { + + //printf("ALLOCATE BLOCK: 0x%x\n" , startBlock + i ); + bitmap_unset(PMMInfoBlock->memoryBitMap, startBlock+ i); + PMMInfoBlock->used_blocks++; + } + + +} +void deallocate_region(uint32_t StartAddress , uint32_t size ) { + // NOT IMPLEMENTED YET +} + + diff --git a/source/kernel/Memory/PhysicalMemoryManager.h b/source/kernel/Memory/PhysicalMemoryManager.h new file mode 100644 index 0000000..649c922 --- /dev/null +++ b/source/kernel/Memory/PhysicalMemoryManager.h @@ -0,0 +1,30 @@ +#pragma once +#include +#include "memoryinfo.h" + +#include "../Terminal/kterm.h" +#include "../Lib/mem.h" +#include "../bitmap.h" + +// Asumming 32 bit x86 for now! +#define BLOCK_SIZE 4092 +#define WORD_SIZE 2 +#define BLOCKS_PER_WORD 32 + +#define KB_TO_BLOCKS(x) (x / BLOCK_SIZE) +#define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) +#define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) + +struct PhysicalMemoryManagerInfoBlock +{ + uint32_t* memoryBitMap; + size_t pmmap_size; + size_t max_blocks; + int used_blocks; +}; + +void initPMM(MemoryInfo* memory); +void free_block(void* ptr); +void* allocate_block(); +void allocate_region(uint32_t, uint32_t); +void deallocate_region(uint32_t , uint32_t ); diff --git a/source/kernel/Memory/VirtualMemoryManager.cpp b/source/kernel/Memory/VirtualMemoryManager.cpp new file mode 100644 index 0000000..2af5da6 --- /dev/null +++ b/source/kernel/Memory/VirtualMemoryManager.cpp @@ -0,0 +1,24 @@ +#include "VirtualMemoryManager.h" + +extern "C" void loadPageDirectory (uint32_t* addr ); +extern "C" void enablePaging(); + +void AllocatePage(uint32_t vaddr) +{ + +} + +void FreePage(uint32_t vaddr ) +{ + +} + +void Map ( uint32_t vaddr, uint32_t paddr) +{ + +} + +void Unmap(uint32_t vaddr) +{ + // NOTE: I will implement lazy unmapping for now +} diff --git a/source/kernel/Memory/VirtualMemoryManager.h b/source/kernel/Memory/VirtualMemoryManager.h new file mode 100644 index 0000000..32abf0c --- /dev/null +++ b/source/kernel/Memory/VirtualMemoryManager.h @@ -0,0 +1,12 @@ +#pragma once +#include "PhysicalMemoryManager.h" +#include "../Terminal/kterm.h" +#include "../cpu.h" + +void AllocatePage(uint32_t v_addr ); +void FreePage(uint32_t v_addr); + +void Map(uint32_t p_addr, uint32_t v_addr); +void Unmap (uint32_t v_addr); + + diff --git a/src/kernel/Memory/memoryinfo.h b/source/kernel/Memory/memoryinfo.h similarity index 100% rename from src/kernel/Memory/memoryinfo.h rename to source/kernel/Memory/memoryinfo.h diff --git a/src/kernel/Memory/paging.definitions.h b/source/kernel/Memory/paging.definitions.h similarity index 100% rename from src/kernel/Memory/paging.definitions.h rename to source/kernel/Memory/paging.definitions.h diff --git a/src/kernel/Memory/paging.s b/source/kernel/Memory/paging.s similarity index 100% rename from src/kernel/Memory/paging.s rename to source/kernel/Memory/paging.s diff --git a/src/kernel/SuperVisorTerminal/superVisorTerminal.cpp b/source/kernel/SuperVisorTerminal/superVisorTerminal.cpp similarity index 96% rename from src/kernel/SuperVisorTerminal/superVisorTerminal.cpp rename to source/kernel/SuperVisorTerminal/superVisorTerminal.cpp index b568208..79dd349 100644 --- a/src/kernel/SuperVisorTerminal/superVisorTerminal.cpp +++ b/source/kernel/SuperVisorTerminal/superVisorTerminal.cpp @@ -39,7 +39,7 @@ void startSuperVisorTerminal(BootInfo* bootinfo){ // Show memory layout printf("========= Memory ==========\n"); printf("Kernel MemoryMap:\n"); - printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); + //printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); printf("Frames used: 0x%x blocks of 4 KiB\n", 0); const int bytesInGiB = 1073741824; int64_t bytesLeft = (bootinfo->memory->TotalMemory % bytesInGiB) / bytesInGiB; diff --git a/src/kernel/SuperVisorTerminal/superVisorTerminal.h b/source/kernel/SuperVisorTerminal/superVisorTerminal.h similarity index 65% rename from src/kernel/SuperVisorTerminal/superVisorTerminal.h rename to source/kernel/SuperVisorTerminal/superVisorTerminal.h index 99d083d..eeed1df 100644 --- a/src/kernel/SuperVisorTerminal/superVisorTerminal.h +++ b/source/kernel/SuperVisorTerminal/superVisorTerminal.h @@ -3,7 +3,7 @@ #include "../time.h" #include "../Drivers/PIT/pit.h" #include "../Drivers/PS-2/keyboard.h" -#include "../Memory/memory.h" +#include "../Memory/PhysicalMemoryManager.h" #include "../bootinfo.h" void startSuperVisorTerminal(BootInfo * ); \ No newline at end of file diff --git a/src/kernel/Terminal/kterm.cpp b/source/kernel/Terminal/kterm.cpp similarity index 100% rename from src/kernel/Terminal/kterm.cpp rename to source/kernel/Terminal/kterm.cpp diff --git a/src/kernel/Terminal/kterm.h b/source/kernel/Terminal/kterm.h similarity index 100% rename from src/kernel/Terminal/kterm.h rename to source/kernel/Terminal/kterm.h diff --git a/src/kernel/bitmap.h b/source/kernel/bitmap.h similarity index 100% rename from src/kernel/bitmap.h rename to source/kernel/bitmap.h diff --git a/src/kernel/bootinfo.h b/source/kernel/bootinfo.h similarity index 100% rename from src/kernel/bootinfo.h rename to source/kernel/bootinfo.h diff --git a/src/kernel/cpu.h b/source/kernel/cpu.h similarity index 100% rename from src/kernel/cpu.h rename to source/kernel/cpu.h diff --git a/src/kernel/cpu.s b/source/kernel/cpu.s similarity index 100% rename from src/kernel/cpu.s rename to source/kernel/cpu.s diff --git a/src/kernel/definitions.h b/source/kernel/definitions.h similarity index 100% rename from src/kernel/definitions.h rename to source/kernel/definitions.h diff --git a/src/kernel/io.cpp b/source/kernel/io.cpp similarity index 100% rename from src/kernel/io.cpp rename to source/kernel/io.cpp diff --git a/src/kernel/io.h b/source/kernel/io.h similarity index 100% rename from src/kernel/io.h rename to source/kernel/io.h diff --git a/src/kernel/irq_table.s b/source/kernel/irq_table.s similarity index 100% rename from src/kernel/irq_table.s rename to source/kernel/irq_table.s diff --git a/src/kernel/irs_table.s b/source/kernel/irs_table.s similarity index 100% rename from src/kernel/irs_table.s rename to source/kernel/irs_table.s diff --git a/src/kernel/kernel.cpp b/source/kernel/kernel.cpp similarity index 93% rename from src/kernel/kernel.cpp rename to source/kernel/kernel.cpp index e120dab..0387146 100644 --- a/src/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -1,11 +1,5 @@ #include "kernel.h" -void map_multiboot_info_structure(unsigned long addr); -extern "C" void kernel_main (BootInfo* bootinfo); -extern "C" uint32_t boot_page_directory; -extern "C" uint32_t multiboot_page_table; - -const uint32_t KERNEL_BASE_ADDR = 0xC0000000; extern "C" void early_main(unsigned long magic, unsigned long addr){ // Convert MBI address to higher quarter kernel space @@ -63,7 +57,7 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ MemoryInfo meminfo = {}; bootinfo.memory = &meminfo; - mapMultibootMemoryMap(bootinfo.memory , mbt); + ///mapMultibootMemoryMap(bootinfo.memory , mbt); printf("Memory size: 0x%x bytes\n", bootinfo.memory->TotalMemory ); /* diff --git a/src/kernel/kernel.h b/source/kernel/kernel.h similarity index 58% rename from src/kernel/kernel.h rename to source/kernel/kernel.h index d9c6a9c..529fb5e 100644 --- a/src/kernel/kernel.h +++ b/source/kernel/kernel.h @@ -12,9 +12,9 @@ extern "C" #include "multiboot.h" #include "bootinfo.h" -#include "Memory/memory.h" +#include "Memory/PhysicalMemoryManager.h" #include "Memory/memoryinfo.h" -#include "Memory/paging.h" +#include "Memory/VirtualMemoryManager.h" #include "KernelLauncher/bootcheck.h" #include "Memory/GDT/gdtc.h" @@ -32,3 +32,15 @@ extern "C" #define PANIC(message) {return;} +void map_multiboot_info_structure(unsigned long addr); + +extern "C" void kernel_main (BootInfo* bootinfo); + +extern "C" const void* kernel_begin; +extern "C" const void* kernel_end; + +extern "C" uint32_t boot_page_directory; +extern "C" uint32_t multiboot_page_table; + + +const uint32_t KERNEL_BASE_ADDR = 0xC0000000; \ No newline at end of file diff --git a/src/kernel/linker.ld b/source/kernel/linker.ld similarity index 100% rename from src/kernel/linker.ld rename to source/kernel/linker.ld diff --git a/src/kernel/multiboot.h b/source/kernel/multiboot.h similarity index 100% rename from src/kernel/multiboot.h rename to source/kernel/multiboot.h diff --git a/src/kernel/serial.h b/source/kernel/serial.h similarity index 100% rename from src/kernel/serial.h rename to source/kernel/serial.h diff --git a/src/kernel/time.cpp b/source/kernel/time.cpp similarity index 100% rename from src/kernel/time.cpp rename to source/kernel/time.cpp diff --git a/src/kernel/time.h b/source/kernel/time.h similarity index 100% rename from src/kernel/time.h rename to source/kernel/time.h diff --git a/src/kernel/timer.cpp b/source/kernel/timer.cpp similarity index 100% rename from src/kernel/timer.cpp rename to source/kernel/timer.cpp diff --git a/src/kernel/timer.h b/source/kernel/timer.h similarity index 100% rename from src/kernel/timer.h rename to source/kernel/timer.h diff --git a/src/kernel/Memory/KernelHeap.h b/src/kernel/Memory/KernelHeap.h deleted file mode 100644 index 84a1624..0000000 --- a/src/kernel/Memory/KernelHeap.h +++ /dev/null @@ -1,2 +0,0 @@ -#pragma once - diff --git a/src/kernel/Memory/PhysicalMemoryManager.cpp b/src/kernel/Memory/PhysicalMemoryManager.cpp deleted file mode 100644 index a24ff3d..0000000 --- a/src/kernel/Memory/PhysicalMemoryManager.cpp +++ /dev/null @@ -1,144 +0,0 @@ -#include "./memory.h" -uint32_t* memoryBitMap; -/* - -*/ -void PhysicalMemory::setup( MemoryInfo* memory) { - - // calculate the maximum number of blocks - max_blocks = KB_TO_BLOCKS(memory->TotalMemory); - - used_blocks = 0; - - memoryBitMap = (uint32_t*) 0xCCA00000; - - - printf("Maximum Number of blocks: 0x%x, Number of bytes for memMap: 0x%x\n", max_blocks , (max_blocks/8)); - - //Size of memory map - uint32_t memMap_size = (max_blocks / 8 ) ; - - printf("Memory Map size: 0x%x\n", memMap_size ); - printf("size of int in bytes: 0x%x \n" , sizeof(int)); - - // Set all places in memory as free - memset(memoryBitMap, 0xFF, memMap_size ); -} - -// NOTE: this can only give blocks of 4kb at a time! -void* PhysicalMemory::allocate_block() { - uint8_t blocks_available = max_blocks - used_blocks; - // Are there any blocks available? - if( blocks_available <= 0) - { - printf("No blocks available. Blocks Delta: 0x%x\n", blocks_available); - return 0; - } - - // Find 1 free block somewhere - int free_block_index = bitmap_first_unset(memoryBitMap, (max_blocks /8) /*memMap Size*/ ); - - - - if(free_block_index == -1) - { - printf("Could not find a good block!\n"); - // Could not find a block - return (void*)0xFFFF; - } - - if(free_block_index == 0) - printf("Somethings wrong!!!\n"); - - // Set the block to be used! - bitmap_unset(memoryBitMap, free_block_index); - // Increase the used_block count! - used_blocks++; - printf("used blocks: 0x%x\n", used_blocks); - // return the pointer to the physical address - return (void*) (BLOCK_SIZE * free_block_index); -} - - -void PhysicalMemory::free_block(void* p) { - // If it is a null pointer we don't need to do anything. - if(p==0) { - return; - } - // calculate the index into the bitmap - int index = ((uint32_t) p) / BLOCK_SIZE; - - // set the block to be free - bitmap_set(memoryBitMap, index); - used_blocks--; - printf("used blocks: 0x%x, after free\n", used_blocks); - -} - - - -void PhysicalMemory::allocate_region(uint32_t startAddress, uint32_t size) { - // every bit should be 4KiB - // every byte is 8*4KiB = 32KiB - - int NumberOfBlocksToAllocate = ( size / 1024) / 4 / 8 + 1; - int startBlock = (startAddress / 1024) / 4 / 8 ; - - // printf("NumberOfBlocksToAllocate: 0x%x\n", NumberOfBlocksToAllocate); - //printf( "start block: 0x%x\n" , startBlock); - for( int i = 0; i < NumberOfBlocksToAllocate; i++) - { - - //printf("ALLOCATE BLOCK: 0x%x\n" , startBlock + i ); - bitmap_unset(memoryBitMap, startBlock+ i); - used_blocks++; - } - - -} -void PhysicalMemory::deallocate_region(uint32_t StartAddress , uint32_t size ) { - // NOT IMPLEMENTED YET -} - - -void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt) { - - printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", (unsigned) mbt->mmap_addr , (unsigned) mbt->mmap_length ); - - - multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; - - for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ - - if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ - - memInfo->TotalMemory += mmap->len; - } else { - memInfo->ReservedMemory += mmap->len; - } - - print_Multiboot_memory_Map(mmap); - - } - -} - - -/** - * @brief Debug Verbose functions - * - * @param mmap - */ - -void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap) { - printf( - "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", - (unsigned) mmap->size, - (unsigned) (mmap->addr >> 32), - (unsigned) (mmap->addr & 0xffffffff), - (unsigned) (mmap->len >> 32), - (unsigned) (mmap->len & 0xffffffff), - (unsigned) mmap->type - ); -} - diff --git a/src/kernel/Memory/PhysicalMemoryManager.h b/src/kernel/Memory/PhysicalMemoryManager.h deleted file mode 100644 index cef690c..0000000 --- a/src/kernel/Memory/PhysicalMemoryManager.h +++ /dev/null @@ -1,50 +0,0 @@ -#pragma once -#include -#include - -#include "memoryinfo.h" -#include "../multiboot.h" -#include "../Terminal/kterm.h" -#include "../Lib/mem.h" -#include "../bitmap.h" - -// Asumming 32 bit x86 for now! -#define BLOCK_SIZE 4092 -#define WORD_SIZE 2 -#define BLOCKS_PER_WORD 32 - -#define KB_TO_BLOCKS(x) (x / BLOCK_SIZE) -#define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) -#define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) - -extern uint32_t kernel_begin; -extern uint32_t kernel_end; - -void initialise_available_regions(uint32_t memoryMapAddr, uint32_t memoryMapLastAddr, uint32_t* memoryBitMap, int* used_blocks); - -extern uint32_t* memoryBitMap; - -class PhysicalMemory -{ - public: - void setup(MemoryInfo* memory); - void destroy(); - void free_block(void* ptr); - void* allocate_block(); - void allocate_region(uint32_t, uint32_t); - void deallocate_region(uint32_t , uint32_t ); - - private: - size_t pmmap_size; - size_t max_blocks; - int used_blocks; -}; - -void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt); - -/** - * @brief Debug Verbose Functions - * - * @param mmap - */ -void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap); diff --git a/src/kernel/Memory/VirtualMemoryManager.cpp b/src/kernel/Memory/VirtualMemoryManager.cpp deleted file mode 100644 index 45f0344..0000000 --- a/src/kernel/Memory/VirtualMemoryManager.cpp +++ /dev/null @@ -1,171 +0,0 @@ -#include "paging.h" -// PageDirectoryEntry kernel_directory[MAX_DIRECTORY_ENTRIES]__attribute__((aligned(4096))); -// PageTableEntry first_page_table[MAX_PAGE_TABLE_ENTRIES]__attribute__((aligned(4096))); - -void IdentityMap (){ - printf("\nInit paging\n"); - // The basics as explained by wiki.osdev.org - - // Set all page_directories to not present - int i = 0; - while ( i < 1024) - { - // kernel_directory[i] = 0x2; - i++; - } - - - // map 4 megabytes - unsigned int j ; - for( j = 0; j < 1024; j++ ) - { - // first_page_table[j] = (j * 0x1000) | 3 ; - - //Attributes: - //Supervisor Level , - //read/write, - //present, - - - } - - // Put the page table in the page directory - // attributes: supervisor level, read/write, present; - // kernel_directory[0] = ((unsigned int)first_page_table) | 3; - - printf("Init paging DONE\n"); -} - -void InitializePaging() -{ - /* - Initial kernel page directory - set all page tables to not present - */ - - for (int i = 0; i < MAX_DIRECTORY_ENTRIES; i++) - { - // kernel_directory[i] = 0x2; - } - - // BIOS Address Identity mapping - // Identity map the first 8MiB ... Physical addresses 0x00000000 to 0x007A1200 - PHYSICAL_ADDRESS BIOSAddr = 0x00000000; - PHYSICAL_ADDRESS BIOSAddr_Max = 0x800000; - - // How many PDE's do we need - uint8_t NUM_PDE = BIOSAddr_Max / (4 * 1024 * 1024); - - printf("The first 8MiB require %d Page Directory Entries\n", NUM_PDE); - - - for( int i = 0; i < NUM_PDE; i++) - { - // setup a page table - // PageTableEntry pagetable[MAX_PAGE_TABLE_ENTRIES] = PhysicalMemory::allocate_block(); // TODO :: Physical memory manager functions should be available here. - - for(int j = 0; j < MAX_PAGE_TABLE_ENTRIES; j++) - { - // pagetable[j] = ( j * 4096 ) | 3; - } - - // add page table as page directory entry - // kernel_directory[i] = ( (unsigned int) pagetable ) | 3; - } - - // map the kernel space - VIRTUAL_ADDRESS Vaddr = KERNEL_VRT_MEMORY_BEGIN; - PHYSICAL_ADDRESS KernelAddr = kernel_begin; - PHYSICAL_ADDRESS KernelEndAddr = kernel_end; - - uint32_t KernelSizeInBytes = (KernelEndAddr - KernelAddr); - printf("Kernel is 0x%x bytes\n", KernelSizeInBytes); - NUM_PDE = KernelSizeInBytes / (4 * 1024* 1024); - printf("Kernel requires %d Page Directory Entries\n", NUM_PDE); - - - for(int i = 0; i < NUM_PDE; i++) - { - // PageTableEntry pageTable [MAX_PAGE_TABLE_ENTRIES] = PhysicalMemory::allocate_block(); - - for(int j = 0; j < MAX_PAGE_TABLE_ENTRIES; j++) - { - // pageTable[j] = ( j * 4096) | 3; // NOTE: Check if page is actually supposed to be present - } - - // TODO: Calculate Page Directory index - - - - } - - - - - - // Identity map VGA memory - // Calc which PDE adn - -} - - -void AllocatePage(VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) -{ - -} - -void FreePage(VIRTUAL_ADDRESS vaddr , PageDirectoryEntry& page_directory) -{ - -} - -void Map ( PHYSICAL_ADDRESS paddr, VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) -{ - - - -} - -void Unmap(VIRTUAL_ADDRESS vaddr, PageDirectoryEntry& page_directory) -{ - // NOTE: I will implement lazy unmapping for now - -} - -void Enable() -{ - - //TODO: Write protect will not be turned on - // for the moment altough according to the intel - // developer manual this should happen. - - uint32_t CR0; - - CR0 = GetCR0(); - printf("PG bit = %d \n" , GET_PG_BIT(CR0)); - - // printf("Load into CR3 address: 0x%x\n", (uint32_t)(&kernel_directory[0])); - // loadPageDirectory(&kernel_directory[0]); - // enablePaging(); - - printf("Paging enabled!\n"); - - - CR0 = GetCR0(); - uint32_t CR4 = GetCR4(); - printf("PG bit = %d\n" , GET_PG_BIT(CR0) ); - printf("PAE bit = %d\n", GET_PAE_BIT(CR4)); - - if(GET_PAE_BIT(CR4) == 0){ - printf("Using 32bit paging\n"); - - if(GET_PSE_BIT(CR4) == 0 ){ - printf("Page size is 4KiB\n"); - } else { - printf("Page size is 4MiB\n"); - } - } else { - printf("Using some extended version for paging\n"); - } - -} diff --git a/src/kernel/Memory/VirtualMemoryManager.h b/src/kernel/Memory/VirtualMemoryManager.h deleted file mode 100644 index 8e1e155..0000000 --- a/src/kernel/Memory/VirtualMemoryManager.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#include "memory.h" -#include "paging.definitions.h" -#include "../Terminal/kterm.h" -#include "../cpu.h" - -extern "C" void loadPageDirectory (uint32_t* addr ); -extern "C" void enablePaging(); - - -void IdentityMap(); -void InitializePaging(); - -void Enable(); - -void AllocatePage(VIRTUAL_ADDRESS, PageDirectoryEntry&); -void FreePage(VIRTUAL_ADDRESS, PageDirectoryEntry&); - -void Map(PHYSICAL_ADDRESS, VIRTUAL_ADDRESS, PageDirectoryEntry&); -void Unmap (VIRTUAL_ADDRESS, PageDirectoryEntry&); - - -- 2.39.5 From 5051b8903c2d9636beef4a1a0ca49e71daf8888c Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 22 Aug 2022 21:16:34 +0200 Subject: [PATCH 070/115] Divided the kernel into seperate distinct phases The first stage after GRUB will be Pre-Kernel. This stage will organize the information we receive from the bootloader. (in our case that will be grub) The second stage is for now called early_main. The program will at this point already be running in virtual higher-half / higher-quarter address space. The goal of the second stage is to set up the kernel in such a way that we are ready to jump in to usermode. The third stage is for now called kernel_main. This stage will jump us into usermode and load the startup programs. - Added a GRUB entry for tests - Started writing the pre-kernel stage - Removed knowledge of multiboot from early_main - Edited the linkerscript to link variables in pre-kernel to lower address space. ( from 1MB and up) --- Makefile | 14 +- source/grub.cfg | 6 + source/kernel/{KernelLauncher => Boot}/boot.s | 24 +-- source/kernel/KernelLauncher/bootcheck.h | 91 ----------- source/kernel/KernelLauncher/launcher.cpp | 28 ---- source/kernel/Memory/MBIMMap/MBI_MMap.cpp | 7 +- source/kernel/Memory/MBIMMap/MBI_MMap.h | 8 +- source/kernel/PreKernel/bootstructure.h | 28 ++++ source/kernel/{ => PreKernel}/multiboot.h | 0 source/kernel/PreKernel/prekernel.cpp | 93 +++++++++++ source/kernel/Terminal/kterm.cpp | 4 +- source/kernel/{KernelLauncher => }/crti.s | 0 source/kernel/{KernelLauncher => }/crtn.s | 0 source/kernel/kernel.cpp | 145 ++++++------------ source/kernel/kernel.h | 9 +- source/kernel/linker.ld | 2 +- 16 files changed, 206 insertions(+), 253 deletions(-) rename source/kernel/{KernelLauncher => Boot}/boot.s (92%) delete mode 100644 source/kernel/KernelLauncher/bootcheck.h delete mode 100644 source/kernel/KernelLauncher/launcher.cpp create mode 100644 source/kernel/PreKernel/bootstructure.h rename source/kernel/{ => PreKernel}/multiboot.h (100%) create mode 100644 source/kernel/PreKernel/prekernel.cpp rename source/kernel/{KernelLauncher => }/crti.s (100%) rename source/kernel/{KernelLauncher => }/crtn.s (100%) diff --git a/Makefile b/Makefile index 038150f..2e1aff2 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/launcher.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o SRC_DIR = source BUILD_DIR = build @@ -30,7 +30,7 @@ clean_iso: iso: clean_iso clean build mkdir -p root/boot/grub cp build/myos.bin root/boot/myos.bin - cp src/grub.cfg root/boot/grub/grub.cfg + cp source/grub.cfg root/boot/grub/grub.cfg grub-mkrescue -o build/barinkOS.iso root run: all @@ -58,13 +58,13 @@ $(BUILD_DIR)/kterm.o: $(CPP) -c $(SRC_DIR)/kernel/Terminal/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/boot.o: - $(AS) $(SRC_DIR)/kernel/KernelLauncher/boot.s -o $(BUILD_DIR)/boot.o + $(AS) $(SRC_DIR)/kernel/Boot/boot.s -o $(BUILD_DIR)/boot.o $(BUILD_DIR)/crti.o: - $(AS) $(SRC_DIR)/kernel/KernelLauncher/crti.s -o $(BUILD_DIR)/crti.o + $(AS) $(SRC_DIR)/kernel/crti.s -o $(BUILD_DIR)/crti.o $(BUILD_DIR)/crtn.o: - $(AS) $(SRC_DIR)/kernel/KernelLauncher/crtn.s -o $(BUILD_DIR)/crtn.o + $(AS) $(SRC_DIR)/kernel/crtn.s -o $(BUILD_DIR)/crtn.o $(BUILD_DIR)/io.o: $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -104,5 +104,5 @@ $(BUILD_DIR)/memory.o: $(BUILD_DIR)/paging.o: $(CPP) -c $(SRC_DIR)/kernel/Memory/VirtualMemoryManager.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti -$(BUILD_DIR)/launcher.o: - $(CPP) -c $(SRC_DIR)/kernel/KernelLauncher/launcher.cpp -o $(BUILD_DIR)/launcher.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file +$(BUILD_DIR)/prekernel.o: + $(CPP) -c $(SRC_DIR)/kernel/PreKernel/prekernel.cpp -o $(BUILD_DIR)/prekernel.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file diff --git a/source/grub.cfg b/source/grub.cfg index df39e08..30bb80f 100644 --- a/source/grub.cfg +++ b/source/grub.cfg @@ -1,3 +1,9 @@ menuentry "BarinkOS" { multiboot /boot/myos.bin } + +menuentry "BarinkOS Tests" { + multiboot /boot/myos.bin +} + + diff --git a/source/kernel/KernelLauncher/boot.s b/source/kernel/Boot/boot.s similarity index 92% rename from source/kernel/KernelLauncher/boot.s rename to source/kernel/Boot/boot.s index 140630c..fb98575 100644 --- a/source/kernel/KernelLauncher/boot.s +++ b/source/kernel/Boot/boot.s @@ -43,6 +43,14 @@ multiboot_page_table: .global _start .type _start, @function _start: + + /* push the pointer to the Multiboot information structure*/ + pushl %ebx + + /* push the magic value */ + pushl %eax + call testLauncher + # Get physical address of the boot_page_table movl $(boot_page_table - 0xC0000000), %edi # Map address 0 @@ -112,11 +120,7 @@ isPaging: pushl $0 popf - /* push the pointer to the Multiboot information structure*/ - pushl %ebx - /* push the magic value */ - pushl %eax call early_main @@ -129,11 +133,11 @@ isPaging: jmp 1b -.include "./src/kernel/Memory/GDT/gdt.s" -.include "./src/kernel/irs_table.s" -.include "./src/kernel/irq_table.s" -.include "./src/kernel/Interrupts/idt/idt.s" -.include "./src/kernel/Memory/paging.s" -.include "./src/kernel/cpu.s" +.include "./source/kernel/Memory/GDT/gdt.s" +.include "./source/kernel/irs_table.s" +.include "./source/kernel/irq_table.s" +.include "./source/kernel/Interrupts/idt/idt.s" +.include "./source/kernel/Memory/paging.s" +.include "./source/kernel/cpu.s" diff --git a/source/kernel/KernelLauncher/bootcheck.h b/source/kernel/KernelLauncher/bootcheck.h deleted file mode 100644 index cb7e30c..0000000 --- a/source/kernel/KernelLauncher/bootcheck.h +++ /dev/null @@ -1,91 +0,0 @@ -#pragma once -#include "../multiboot.h" -#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) -#define __VERBOSE__ -#include "../Terminal/kterm.h" - - - -void CheckMBT ( multiboot_info_t* mbt ){ - /* Set MBI to the addresss of the multiboot information structure*/ - multiboot_info_t * mbi = (multiboot_info_t *) mbt; - -#ifdef __VERBOSE__ - /* Print out the flags */ - printf("flags = 0x%x\n", (unsigned) mbi->flags); -#endif - /* Are mem_* valid? */ - if ( CHECK_FLAG(mbi->flags,0)){ - // Do nothing - } - - /* is boot device valid ? */ - if (CHECK_FLAG (mbi->flags, 1)) - { -#ifdef __VERBOSE__ - printf("boot_device = 0x0%x\n", (unsigned) mbi->boot_device); -#endif - } - - /* is the command line passed? */ - if (CHECK_FLAG ( mbi->flags,2)) - { -#ifdef __VERBOSE__ - printf("cmdline = %s\n", (char *) (mbi->cmdline + 0xC0000000)); -#endif - } - - /* Are mods_* valid? */ - if(CHECK_FLAG ( mbi->flags, 3)){ - multiboot_module_t *mod; - uint32_t i; -#ifdef __VERBOSE__ - printf("mods count = %d, mods_addr = 0x%x\n", (int) mbi->mods_count, (int) mbi->mods_addr); - - for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ - printf(" mod start = 0x%x, mod_end = 0x%x, cmdline = %s\n", (unsigned) mod->mod_start, (unsigned) mod->mod_end, (char*) mod->cmdline); - } -#endif - } - - /* Bits 4 and 5 are mutually exclusive! */ - if (CHECK_FLAG (mbi->flags, 4) && CHECK_FLAG(mbi->flags, 5)) - { -#ifdef __VERBOSE__ - printf("Both bits 4 and 5 are set.\n"); -#endif - return; - } - - /* Is the symbol table of a.out valid? */ - if (CHECK_FLAG(mbi->flags, 4)){ - multiboot_aout_symbol_table_t *multiboot_aout_sym = &(mbi->u.aout_sym); -#ifdef __VERBOSE__ - printf( "multiboot_aout_symbol_table: tabsize = 0x%0x, strsize = 0x%x, addr = 0x%x\n", - (unsigned) multiboot_aout_sym->tabsize, - (unsigned) multiboot_aout_sym->strsize, - (unsigned) multiboot_aout_sym->addr); -#endif - } - - /* Is the section header table of ELF valid? */ - if (CHECK_FLAG(mbi->flags, 5)){ - multiboot_elf_section_header_table_t *multiboot_elf_sec = &(mbi->u.elf_sec); -#ifdef __VERBOSE__ - printf("multiboot_elf_sec: num = %u, size = 0x%x, addr = 0x%x, shnd = 0x%x\n", - - (unsigned) multiboot_elf_sec->num, (unsigned) multiboot_elf_sec->size, - (unsigned) multiboot_elf_sec->addr, (unsigned) multiboot_elf_sec->shndx); -#endif - - } - - /* Draw diagonal blue line */ - if (CHECK_FLAG (mbt->flags, 12)){ -#ifdef __VERBOSE__ - printf("Can draw!\n"); -#endif - } - - -} \ No newline at end of file diff --git a/source/kernel/KernelLauncher/launcher.cpp b/source/kernel/KernelLauncher/launcher.cpp deleted file mode 100644 index 471053c..0000000 --- a/source/kernel/KernelLauncher/launcher.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include -#include - -void put_char(char ch, size_t x, size_t y ){ - *((uint16_t*)0xb8000+(y * 80 + x)) = ch | ((7 | 0 << 4) << 8); -} - -void write_ln(char* s, size_t length, size_t x , size_t y) -{ - // Because read only data is linked at a virtual address we'll need to convert - // the string adddres from virtual to phys. - s = s - 0xC0000000; - size_t column , row; - column = x; - row = y; - for(int i = 0; i < length ; i ++) - { - - put_char(s[i] , column,row ); - column ++; - - } - -} - -extern "C" void testLauncher () { - write_ln("hello", 5 ,0,0); -} \ No newline at end of file diff --git a/source/kernel/Memory/MBIMMap/MBI_MMap.cpp b/source/kernel/Memory/MBIMMap/MBI_MMap.cpp index dc5da2f..4dffba6 100644 --- a/source/kernel/Memory/MBIMMap/MBI_MMap.cpp +++ b/source/kernel/Memory/MBIMMap/MBI_MMap.cpp @@ -1,6 +1,6 @@ #include "MBI_MMap.h" - +/* void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt) { printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", (unsigned) mbt->mmap_addr , (unsigned) mbt->mmap_length ); @@ -23,13 +23,13 @@ void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt) { } - +*/ /** * @brief Debug Verbose functions * * @param mmap */ - +/* void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap) { printf( "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", @@ -41,3 +41,4 @@ void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap) { (unsigned) mmap->type ); } +*/ \ No newline at end of file diff --git a/source/kernel/Memory/MBIMMap/MBI_MMap.h b/source/kernel/Memory/MBIMMap/MBI_MMap.h index bd24198..1bd1ad3 100644 --- a/source/kernel/Memory/MBIMMap/MBI_MMap.h +++ b/source/kernel/Memory/MBIMMap/MBI_MMap.h @@ -1,16 +1,18 @@ #pragma once #include -#include "../../multiboot.h" +//#include "../../multiboot.h" #include "../memoryinfo.h" void initialise_available_regions(uint32_t memoryMapAddr, uint32_t memoryMapLastAddr, uint32_t* memoryBitMap, int* used_blocks); - +/* void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt); - +*/ /** * @brief Debug Verbose Functions * * @param mmap */ +/* void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap); +*/ diff --git a/source/kernel/PreKernel/bootstructure.h b/source/kernel/PreKernel/bootstructure.h new file mode 100644 index 0000000..6d87ab1 --- /dev/null +++ b/source/kernel/PreKernel/bootstructure.h @@ -0,0 +1,28 @@ +#pragma once +#include +#include + + +extern "C" const uint32_t kernel_begin; +extern "C" const uint32_t kernel_end; +struct BootInfoBlock { + bool MapIsInvalid; + uint32_t bootDeviceID ; + + uint32_t GrubModuleCount; + + bool ValidSymbolTable; + uint32_t SymbolTableAddr; + uint32_t SymbolTabSize; + uint32_t SymbolStrSize; + + bool ValidELFHeader; + + bool EnabledVBE; + + bool PhysicalMemoryMapAvailable; + +}; + +// Put the BootInfoBlock 1MB above the kernel. +const uint32_t BootInfoBlock_pptr = kernel_end - 0xC0000000 + 0x1000; diff --git a/source/kernel/multiboot.h b/source/kernel/PreKernel/multiboot.h similarity index 100% rename from source/kernel/multiboot.h rename to source/kernel/PreKernel/multiboot.h diff --git a/source/kernel/PreKernel/prekernel.cpp b/source/kernel/PreKernel/prekernel.cpp new file mode 100644 index 0000000..6b910a2 --- /dev/null +++ b/source/kernel/PreKernel/prekernel.cpp @@ -0,0 +1,93 @@ +#include +#include +#include "multiboot.h" +#include "bootstructure.h" +#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) + + +extern "C" void testLauncher ( unsigned long magic, multiboot_info_t* mbi) { + + // Create the bootInfoBlock at its location + BootInfoBlock* BIB = (BootInfoBlock*) BootInfoBlock_pptr; + + /* + * Check Multiboot magic number + */ + if (magic != MULTIBOOT_BOOTLOADER_MAGIC) + { + BIB->MapIsInvalid = true; + return; + } else{ + BIB->MapIsInvalid = false; + } + + /* is boot device valid ? */ + if (CHECK_FLAG (mbi->flags, 1)) + { + BIB->bootDeviceID = mbi->boot_device; + } + + /* Are mods_* valid? */ + if(CHECK_FLAG ( mbi->flags, 3)){ + multiboot_module_t *mod; + uint32_t i; + + BIB->GrubModuleCount = mbi->mods_count; + + + for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ + + } + } + + /* Is the symbol table of a.out valid? */ + if (CHECK_FLAG(mbi->flags, 4)) + { + BIB->ValidSymbolTable = true; + multiboot_aout_symbol_table_t *multiboot_aout_sym = &(mbi->u.aout_sym); + + } else{ + BIB->ValidSymbolTable = false; + } + + /* Is the section header table of ELF valid? */ + if (CHECK_FLAG(mbi->flags, 5)) + { + BIB->ValidELFHeader = true; + multiboot_elf_section_header_table_t *multiboot_elf_sec = &(mbi->u.elf_sec); + + }else{ + BIB->ValidELFHeader = false; + } +/* + If we got a memory map from our bootloader we + should be parsing it to find out the memory regions available. + */ + if (CHECK_FLAG(mbi->flags, 6)) + { + BIB->PhysicalMemoryMapAvailable = true; + multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) (mbi->mmap_addr) ; + + for (; (unsigned long) mmap < mbi->mmap_addr + mbi->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + + if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ + + } else{ + + + } + + + } + + } else{ + BIB->PhysicalMemoryMapAvailable = false; + } + + /* Draw diagonal blue line */ + if (CHECK_FLAG (mbi->flags, 12)){ + BIB->EnabledVBE = true; + } else{ + BIB->EnabledVBE; + } +} diff --git a/source/kernel/Terminal/kterm.cpp b/source/kernel/Terminal/kterm.cpp index 95573c6..ede8bbd 100644 --- a/source/kernel/Terminal/kterm.cpp +++ b/source/kernel/Terminal/kterm.cpp @@ -22,6 +22,7 @@ void kterm_init () { kterm_column = 0; kterm_color = vga_entry_color ( VGA_COLOR_LIGHT_GREY , VGA_COLOR_BLACK); kterm_buffer = (uint16_t*) 0xC03FF000; + for (size_t y = 0; y < VGA_HEIGHT; y++ ){ for( size_t x = 0; x < VGA_WIDTH; x++){ const size_t index = y * VGA_WIDTH + x; @@ -31,7 +32,6 @@ void kterm_init () { } } - void kterm_resetcolor(){ kterm_color = vga_entry_color ( VGA_COLOR_LIGHT_GREY , VGA_COLOR_BLACK); } @@ -42,9 +42,7 @@ void kterm_setcolor(uint8_t color){ void kterm_putat (char c, uint8_t color, size_t x, size_t y ) { const size_t index = y * VGA_WIDTH + x; - kterm_buffer[index] = vga_entry(c, color); - } void enable_cursor (uint8_t start_cursor , uint8_t end_cursor ){ diff --git a/source/kernel/KernelLauncher/crti.s b/source/kernel/crti.s similarity index 100% rename from source/kernel/KernelLauncher/crti.s rename to source/kernel/crti.s diff --git a/source/kernel/KernelLauncher/crtn.s b/source/kernel/crtn.s similarity index 100% rename from source/kernel/KernelLauncher/crtn.s rename to source/kernel/crtn.s diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 0387146..0b232a9 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -1,15 +1,13 @@ #include "kernel.h" - -extern "C" void early_main(unsigned long magic, unsigned long addr){ - - // Convert MBI address to higher quarter kernel space - addr += KERNEL_BASE_ADDR; - /** +extern "C" void early_main() +{ + /* * Initialize terminal interface - * NOTE: This should be done later on , the magic value should be checked first. */ initGDT(); + kterm_init(); + init_serial(); print_serial("Hello Higher half kernel!\n"); @@ -17,110 +15,38 @@ extern "C" void early_main(unsigned long magic, unsigned long addr){ // Enable interrupts asm volatile("STI"); - - printf("DEBUG:\n Magic: 0x%x\n MBT_addr: 0x%x\n", magic, addr); - /** - * Check Multiboot magic number - * NOTE: Printf call should not be a thing this early on ... - */ - if (magic != MULTIBOOT_BOOTLOADER_MAGIC){ - printf("Invalid magic number: 0x%x\n", magic); - return; - } - - /** + /* * Show a little banner for cuteness */ printf("|=== BarinkOS ===|\n"); - /** - * Use the address given as an argument as the pointer - * to a Multiboot information structure. - */ - multiboot_info_t* mbt = (multiboot_info_t*) (addr ); - /** - * Construct our own bootInfo structure - */ - BootInfo bootinfo = {}; - - - /* - If we got a memory map from our bootloader we - should be parsing it to find out the memory regions available. - */ - if (CHECK_FLAG(mbt->flags, 6)) - { - - /* - Setup Physical memory managment - */ - MemoryInfo meminfo = {}; - bootinfo.memory = &meminfo; - - ///mapMultibootMemoryMap(bootinfo.memory , mbt); - printf("Memory size: 0x%x bytes\n", bootinfo.memory->TotalMemory ); + BootInfoBlock* BootInfo = (BootInfoBlock*) ( BootInfoBlock_pptr + 0xC0000000 ); - /* - PhysicalMemory memAlloc = PhysicalMemory{}; - memAlloc.setup(bootinfo.memory ); - */ + printf("Bootloader information:\n"); + if( BootInfo->ValidELFHeader ) + { + printf("- Valid ELF Header is available!\n"); + } - // TODO: FIX physical allocator - /* - Mark already in use sections - */ - - // Mark kernel memory as used - printf("Kernel Begin Pointer: 0x%x, Kernel end pointer: 0x%x\n", &kernel_begin , &kernel_end ); - - - multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) (mbt->mmap_addr + KERNEL_BASE_ADDR) ; + if(BootInfo->EnabledVBE) + { + printf("- VBE graphics mode is available!\n"); + } - for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ + if(BootInfo->ValidSymbolTable) + { + printf("- Valid Symbol Table available at 0x%x.\n Tab Size: %d, str Size: %d\n", BootInfo->SymbolTableAddr, BootInfo->SymbolTabSize, BootInfo->SymbolStrSize); + } - if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ - - } else{ - printf("allocate region: 0x%x, size : 0x%x bytes\n", (unsigned) mmap->addr,(unsigned) mmap->len ); - // memAlloc.allocate_region((unsigned)mmap->addr , (unsigned)mmap->len); - } - - - } - - - printf("allocate region: 0x%x, size : 0x%x bytes\n", &kernel_begin, &kernel_end - &kernel_begin ); - //memAlloc.allocate_region(kernel_end, kernel_end - kernel_begin); - - // test alloc_block - /* - uint8_t* memory = (uint8_t*) memAlloc.allocate_block(); - printf("Got a new pointer: 0x%x\n", memory); - - uint8_t* memory2 = (uint8_t*) memAlloc.allocate_block(); - printf("Got a new pointer: 0x%x\n", memory2); - - - memAlloc.free_block((void*) memory); - - uint8_t* newBlockPlse = (uint8_t*) memAlloc.allocate_block(); - */ - - - - //memAlloc.free_block((void*) memory); - //InitializePaging(); - //IdentityMap(); - //Enable(); - } else{ - printf("memory flag not set!"); + if(BootInfo->PhysicalMemoryMapAvailable) + { + printf("- Physical Memory Map available!\n"); } - CheckMBT( (multiboot_info_t *) addr); asm volatile("mov %cr0, %eax "); asm volatile("or $1, %eax"); asm volatile("mov %eax, %cr0"); - kernel_main(&bootinfo); + kernel_main(); } @@ -151,9 +77,28 @@ void map_multiboot_info_structure(unsigned long addr){ asm("movl %cr3, %ecx;" "movl %ecx, %cr3" ); } - -extern "C" void kernel_main (BootInfo* bootinfo) { +void PhysicalMemoryAllocatorTest(){ +#ifdef UNIT_TESTS + // test alloc_block + uint8_t* memory = (uint8_t*) memAlloc.allocate_block(); + printf("Got a new pointer: 0x%x\n", memory); + + uint8_t* memory2 = (uint8_t*) memAlloc.allocate_block(); + printf("Got a new pointer: 0x%x\n", memory2); + + memAlloc.free_block((void*) memory); + uint8_t* newBlockPlse = (uint8_t*) memAlloc.allocate_block(); +#endif +} + + +extern "C" void kernel_main () { pit_initialise(); + // Create a dummy BootInfo object + // TODO: This should be done properly or the dependency should + // be removed from the SuperVisorTerminal. + BootInfo* bootinfo = {}; + startSuperVisorTerminal(bootinfo); } \ No newline at end of file diff --git a/source/kernel/kernel.h b/source/kernel/kernel.h index 529fb5e..86bf667 100644 --- a/source/kernel/kernel.h +++ b/source/kernel/kernel.h @@ -3,19 +3,16 @@ extern "C" { #include "Lib/string.h" } - #include "definitions.h" #include "Drivers/VGA/VBE.h" #include "Terminal/kterm.h" -#include "multiboot.h" #include "bootinfo.h" #include "Memory/PhysicalMemoryManager.h" #include "Memory/memoryinfo.h" #include "Memory/VirtualMemoryManager.h" -#include "KernelLauncher/bootcheck.h" #include "Memory/GDT/gdtc.h" #include "Interrupts/idt/idt.h" @@ -27,17 +24,15 @@ extern "C" #include "time.h" #include "SuperVisorTerminal/superVisorTerminal.h" +#include "PreKernel/bootstructure.h" #define CHECK_FLAG(flag, bit) ( flag & (1 << bit )) #define PANIC(message) {return;} - void map_multiboot_info_structure(unsigned long addr); -extern "C" void kernel_main (BootInfo* bootinfo); +extern "C" void kernel_main (); -extern "C" const void* kernel_begin; -extern "C" const void* kernel_end; extern "C" uint32_t boot_page_directory; extern "C" uint32_t multiboot_page_table; diff --git a/source/kernel/linker.ld b/source/kernel/linker.ld index b564172..ef2b6a1 100644 --- a/source/kernel/linker.ld +++ b/source/kernel/linker.ld @@ -16,7 +16,7 @@ SECTIONS .multiboot.text : { *(multiboot.text) - *launcher.o(.text) + *prekernel.o(.text) } . += 0xC0000000; /* Addresses in the following code need to be above the 3Gb mark */ -- 2.39.5 From 59ba41f3d2d04d793893e8703f8dfaac42ec4f26 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 23 Aug 2022 21:35:19 +0200 Subject: [PATCH 071/115] Multiboot Memory Map get copied to a "safe" place --- source/kernel/Boot/Multiboot.S | 15 ++++++ source/kernel/Boot/boot.s | 22 +------- source/kernel/PreKernel/bootstructure.h | 21 +++++++- source/kernel/PreKernel/prekernel.cpp | 64 +++++++++++++++------- source/kernel/kernel.cpp | 72 +++++++++++++++++++++++++ 5 files changed, 151 insertions(+), 43 deletions(-) create mode 100644 source/kernel/Boot/Multiboot.S diff --git a/source/kernel/Boot/Multiboot.S b/source/kernel/Boot/Multiboot.S new file mode 100644 index 0000000..041f103 --- /dev/null +++ b/source/kernel/Boot/Multiboot.S @@ -0,0 +1,15 @@ +/* + * Multiboot + */ +.set ALIGN, 1<<0 /* align loaded modules on page boundaries */ +.set MEMINFO, 1<<1 /* provide memory map */ +.set FLAGS, ALIGN | MEMINFO /* this is the Multiboot 'flag' field */ +.set MAGIC, 0x1BADB002 /* 'magic number' lets bootloader find the header */ +.set CHECKSUM, -(MAGIC + FLAGS) /* checksum of above, to prove we are multiboot */ + +.section .multiboot.data, "aw" +.align 4 +.long MAGIC +.long FLAGS +.long CHECKSUM + \ No newline at end of file diff --git a/source/kernel/Boot/boot.s b/source/kernel/Boot/boot.s index fb98575..b32fdaa 100644 --- a/source/kernel/Boot/boot.s +++ b/source/kernel/Boot/boot.s @@ -1,18 +1,4 @@ -/* - * Multiboot - */ -.set ALIGN, 1<<0 /* align loaded modules on page boundaries */ -.set MEMINFO, 1<<1 /* provide memory map */ -.set FLAGS, ALIGN | MEMINFO /* this is the Multiboot 'flag' field */ -.set MAGIC, 0x1BADB002 /* 'magic number' lets bootloader find the header */ -.set CHECKSUM, -(MAGIC + FLAGS) /* checksum of above, to prove we are multiboot */ - -.section .multiboot.data, "aw" -.align 4 -.long MAGIC -.long FLAGS -.long CHECKSUM - +.include "./source/kernel/Boot/Multiboot.S" /* * Allocate initial stack */ @@ -120,14 +106,8 @@ isPaging: pushl $0 popf - - call early_main - - - - cli 1: hlt jmp 1b diff --git a/source/kernel/PreKernel/bootstructure.h b/source/kernel/PreKernel/bootstructure.h index 6d87ab1..70f9abf 100644 --- a/source/kernel/PreKernel/bootstructure.h +++ b/source/kernel/PreKernel/bootstructure.h @@ -5,6 +5,24 @@ extern "C" const uint32_t kernel_begin; extern "C" const uint32_t kernel_end; +// Put the BootInfoBlock 1MB above the kernel. +const uint32_t BootInfoBlock_pptr = (uint32_t)&kernel_end - 0xC0000000 + 0x1; +const uint32_t MemoryMapHeap_pptr = BootInfoBlock_pptr + 0x1; + + +#define IS_AVAILABLE_MEM(MEM_TYPE) MEM_TYPE & 0x1 +#define IS_ACPI_MEM(MEM_TYPE) MEM_TYPE & 0x2 +#define IS_RESERVED_MEM(MEM_TYPE) MEM_TYPE & 0x3 +#define IS_NVS_MEMORY(MEM_TYPE) MEM_TYPE & 0x8 +#define IS_BADRAM_MEMORY(MEM_TYPE) MEM_TYPE & 0x10 + +struct MemoryInfoBlock { + uint32_t Base_addr ; + uint32_t Memory_Size; + MemoryInfoBlock* next; + uint8_t type; + +}; struct BootInfoBlock { bool MapIsInvalid; uint32_t bootDeviceID ; @@ -21,8 +39,7 @@ struct BootInfoBlock { bool EnabledVBE; bool PhysicalMemoryMapAvailable; + MemoryInfoBlock* MemoryMap; }; -// Put the BootInfoBlock 1MB above the kernel. -const uint32_t BootInfoBlock_pptr = kernel_end - 0xC0000000 + 0x1000; diff --git a/source/kernel/PreKernel/prekernel.cpp b/source/kernel/PreKernel/prekernel.cpp index 6b910a2..48ab238 100644 --- a/source/kernel/PreKernel/prekernel.cpp +++ b/source/kernel/PreKernel/prekernel.cpp @@ -25,6 +25,8 @@ extern "C" void testLauncher ( unsigned long magic, multiboot_info_t* mbi) { if (CHECK_FLAG (mbi->flags, 1)) { BIB->bootDeviceID = mbi->boot_device; + } else{ + BIB->bootDeviceID = 0x11111111; } /* Are mods_* valid? */ @@ -36,7 +38,7 @@ extern "C" void testLauncher ( unsigned long magic, multiboot_info_t* mbi) { for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ - + } } @@ -60,29 +62,51 @@ extern "C" void testLauncher ( unsigned long magic, multiboot_info_t* mbi) { BIB->ValidELFHeader = false; } /* - If we got a memory map from our bootloader we - should be parsing it to find out the memory regions available. - */ - if (CHECK_FLAG(mbi->flags, 6)) - { +If we got a memory map from our bootloader we +should be parsing it to find out the memory regions available. +*/ +if (CHECK_FLAG(mbi->flags, 6)) +{ BIB->PhysicalMemoryMapAvailable = true; + BIB->MemoryMap = (MemoryInfoBlock*) MemoryMapHeap_pptr; multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) (mbi->mmap_addr) ; - - for (; (unsigned long) mmap < mbi->mmap_addr + mbi->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ - - if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ - - } else{ - - - } - - - } + auto MemoryMapEnd = mbi->mmap_addr + mbi->mmap_length; - } else{ + auto CurrentInfoBlock = BIB->MemoryMap; + + + while((unsigned long) mmap < MemoryMapEnd){ + + CurrentInfoBlock->Base_addr = mmap->addr; + CurrentInfoBlock->Memory_Size = mmap->len; + + + if(mmap->type == MULTIBOOT_MEMORY_AVAILABLE) + CurrentInfoBlock->type &= 0x1; + if(mmap->type == MULTIBOOT_MEMORY_ACPI_RECLAIMABLE) + CurrentInfoBlock->type &= 0x2; + if(mmap->type == MULTIBOOT_MEMORY_RESERVED) + CurrentInfoBlock->type &= 0x4; + if(mmap->type == MULTIBOOT_MEMORY_NVS) + CurrentInfoBlock->type &= 0x8; + if(mmap->type == MULTIBOOT_MEMORY_BADRAM) + CurrentInfoBlock->type &= 0x10; + + + // continue to the next block + mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size)); + + CurrentInfoBlock->next = (MemoryInfoBlock*) ((uint32_t)CurrentInfoBlock) + sizeof(MemoryInfoBlock); + CurrentInfoBlock = CurrentInfoBlock->next; + + } + + CurrentInfoBlock->next = (MemoryInfoBlock*) 0x0; + +} else +{ BIB->PhysicalMemoryMapAvailable = false; - } +} /* Draw diagonal blue line */ if (CHECK_FLAG (mbi->flags, 12)){ diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 0b232a9..c9b8aff 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -19,6 +19,22 @@ extern "C" void early_main() * Show a little banner for cuteness */ printf("|=== BarinkOS ===|\n"); + printf("Kernel End Addr: 0x%x\n" , &kernel_end + KERNEL_BASE_ADDR); + + uint32_t PageDirectoryEntryIndex = ((uint32_t)&kernel_end + KERNEL_BASE_ADDR ) >> 2 ; + + uint32_t PageTableEntryIndex = (((uint32_t)&kernel_end + KERNEL_BASE_ADDR) >> 12) & 0x1FFF; + + printf("Kernel End PDE: %d, PTE: %d\n" , PageDirectoryEntryIndex, PageTableEntryIndex); + + uint32_t BootInfoStruct = BootInfoBlock_pptr + 0xC0000000; + printf("Addr BootInfostruct: 0x%x\n", BootInfoStruct); + + uint32_t PageDirectoryEntryIndex2 = (BootInfoStruct ) >> 2 ; + + uint32_t PageTableEntryIndex2 = (BootInfoStruct >> 12) & 0x1FFF; + + printf("PDE: 0x%x, PTE: 0x%x\n", PageDirectoryEntryIndex2 , PageTableEntryIndex2 ); BootInfoBlock* BootInfo = (BootInfoBlock*) ( BootInfoBlock_pptr + 0xC0000000 ); @@ -41,6 +57,62 @@ extern "C" void early_main() if(BootInfo->PhysicalMemoryMapAvailable) { printf("- Physical Memory Map available!\n"); + + // Print the memory regions + MemoryInfoBlock* currentBlock = (MemoryInfoBlock*) ((uint32_t)BootInfo->MemoryMap + KERNEL_BASE_ADDR) ; + + kterm_setcolor(VGA_COLOR_RED); + printf("size of MemoryInfoBlock: 0x%x\n", sizeof(MemoryInfoBlock)); + kterm_setcolor(VGA_COLOR_CYAN); + printf("Kernel End is at address: 0x%x\n", &kernel_end); + printf("BootInfo is at address: 0x%x\n", BootInfo); + printf("map is at address: 0x%x\n", currentBlock + KERNEL_BASE_ADDR); + kterm_setcolor(VGA_COLOR_WHITE); + while( (uint32_t)currentBlock->next != 0x0 ) + { + kterm_setcolor(VGA_COLOR_CYAN); + printf("map is at address: 0x%x\n", ( (uint32_t)currentBlock )); + kterm_setcolor(VGA_COLOR_WHITE); + + /* + uint32_t pageDirectoryIndex = ((uint32_t)¤tBlock ) >> 22; + printf("pageDirectoryIndex: %d\n", pageDirectoryIndex); + + uint32_t pageTableIndex = ((uint32_t)¤tBlock >> 12) & 0x1FFF; + printf("PagTableIndex: %d\n", pageTableIndex); + */ + + //printf("boot_page_directory addr: 0x%x\n", &boot_page_directory); + //printf("boot_page_table addr: 0x%x\n", &multiboot_page_table); + printf("Memory Region: \n"); + + if(IS_AVAILABLE_MEM(currentBlock->type)){ + //printf("AVAILABLE RAM\n"); + } + else if(IS_ACPI_MEM(currentBlock->type)){ + printf("ACPI MEMORY\n"); + } + else if(IS_RESERVED_MEM(currentBlock->type)){ + printf("RESERVED MEMORY\n"); + } + else if(IS_NVS_MEMORY(currentBlock->type)){ + printf("NVS MEMORY \n"); + } + else if(IS_BADRAM_MEMORY(currentBlock->type)){ + printf("BADRAM MEMORY \n"); + } + else { + // printf("(TYPE 0x%x )TYPE NOT SPECIFIED\n", currentBlock->type); + } + + // printf("Base address: 0x%x, Memory size: 0x%x\n", currentBlock->Base_addr, currentBlock->Memory_Size); + + currentBlock = (MemoryInfoBlock*) ((uint32_t)currentBlock->next + KERNEL_BASE_ADDR ); + + } + + + } asm volatile("mov %cr0, %eax "); -- 2.39.5 From a5e7fdd07e9cd4a625c331c0ad3cbcf2eae90351 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 1 Sep 2022 16:11:35 +0200 Subject: [PATCH 072/115] KERNEL: Physical Page Frame allocation Rewriting the setup to allow for physical memory allocation again to work. --- source/kernel/Boot/boot.s | 3 +- source/kernel/Memory/GDT/gdtc.cpp | 2 +- .../kernel/Memory/PhysicalMemoryManager.cpp | 82 +++++++++++++------ source/kernel/Memory/PhysicalMemoryManager.h | 12 +-- source/kernel/PreKernel/bootstructure.h | 12 +-- source/kernel/PreKernel/prekernel.cpp | 20 +++-- source/kernel/kernel.cpp | 60 ++++++-------- 7 files changed, 107 insertions(+), 84 deletions(-) diff --git a/source/kernel/Boot/boot.s b/source/kernel/Boot/boot.s index b32fdaa..f8eb7f6 100644 --- a/source/kernel/Boot/boot.s +++ b/source/kernel/Boot/boot.s @@ -35,7 +35,7 @@ _start: /* push the magic value */ pushl %eax - call testLauncher + call prekernelSetup # Get physical address of the boot_page_table movl $(boot_page_table - 0xC0000000), %edi @@ -60,7 +60,6 @@ _start: 3: # Map VGA video memory to 0xC03FF00 as "present, writable" movl $(0x000B8000 | 0x003), boot_page_table - 0xC0000000 + 1023 * 4 - # IMPORTANT NOTE FROM WIKI.OSDEV.ORG/HIGHER_HALF_X86_BARE_BONES # The page table is used at both page directory entry 0 (virtually from 0x0 diff --git a/source/kernel/Memory/GDT/gdtc.cpp b/source/kernel/Memory/GDT/gdtc.cpp index e78b509..bd10a08 100644 --- a/source/kernel/Memory/GDT/gdtc.cpp +++ b/source/kernel/Memory/GDT/gdtc.cpp @@ -51,7 +51,7 @@ void initGDT(){ gdtDescriptor.limit = ((sizeof(SegmentDescriptor ) * 5 ) - 1); gdtDescriptor.base = (unsigned int) &GlobalDescriptorTable; - + printf("GDT at address 0x%x, with an size of 0x%x bytes\n" , (unsigned int)GlobalDescriptorTable, sizeof(GlobalDescriptorTable)); LoadGlobalDescriptorTable(); diff --git a/source/kernel/Memory/PhysicalMemoryManager.cpp b/source/kernel/Memory/PhysicalMemoryManager.cpp index dd8bd5c..7551f91 100644 --- a/source/kernel/Memory/PhysicalMemoryManager.cpp +++ b/source/kernel/Memory/PhysicalMemoryManager.cpp @@ -2,32 +2,61 @@ PhysicalMemoryManagerInfoBlock* PMMInfoBlock; +const uint32_t KERNEL_OFFSET = 0xC0000000; +void SetupPhysicalMemoryManager( BootInfoBlock* Bootinfo) { -void initPMM( MemoryInfo* memory) { - - // NOTE: Lets for now puts the Physical memoryManagerBlock at a random address - // We'll think of a more proper solution a bit later - PMMInfoBlock = (PhysicalMemoryManagerInfoBlock*) 0xCC900000; - + PMMInfoBlock = (PhysicalMemoryManagerInfoBlock*) ((uint32_t)MemoryMapHeap_pptr + Bootinfo->map_size + 0xC0000000); + /* + Every byte contains 8 pages + A page is 4096 kib + Every block (1 bit) represent an page + */ // calculate the maximum number of blocks - PMMInfoBlock->max_blocks = KB_TO_BLOCKS(memory->TotalMemory); + PMMInfoBlock->max_blocks =Bootinfo->MemorySize / BLOCK_SIZE / 8; PMMInfoBlock->used_blocks = 0; - PMMInfoBlock->memoryBitMap = (uint32_t*) 0xCCA00000; - printf("Maximum Number of blocks: 0x%x, Number of bytes for memMap: 0x%x\n", PMMInfoBlock->max_blocks , (PMMInfoBlock->max_blocks/8)); + // put the map after the gdt + PMMInfoBlock->memoryBitMap = (uint32_t*) ( 0xC010b100) ; + + // // Page in the address space please + // uint32_t PDEI = 0xC020a000 >> 22; + // uint32_t PTEI = (0xC020a000 >> 12) & 0x1FFF; + // printf("PDEI: %d, PTEI: %d\n", PDEI, PTEI); - //Size of memory map - uint32_t memMap_size = (PMMInfoBlock->max_blocks / 8 ) ; - printf("Memory Map size: 0x%x\n", memMap_size ); - printf("size of int in bytes: 0x%x \n" , sizeof(int)); - + printf("Maximum num blocks: %d \n",PMMInfoBlock->max_blocks); + //Size of memory map + uint32_t memMap_size = PMMInfoBlock->max_blocks / 8; + printf("Memory map size: %d\n", memMap_size); + printf("Address of memory map 0x%x\n", PMMInfoBlock->memoryBitMap); // Set all places in memory as free - memset(PMMInfoBlock->memoryBitMap, 0xFF, memMap_size ); + memset(PMMInfoBlock->memoryBitMap, 0xFF, memMap_size ); + + // Loop over memory map and allocate physical locations + // that are already in use + MemoryInfoBlock* currentBlock = (MemoryInfoBlock*) ((uint32_t)Bootinfo->MemoryMap + KERNEL_OFFSET) ; + printf("Starting address: 0x%x\n", currentBlock); + while( (uint32_t) currentBlock->next != 0x0) + { + if(IS_AVAILABLE_MEM(currentBlock->type)){ + printf("skip!\n"); + } else { + printf("allocate region 0x%x of size 0x%x\n" , currentBlock->Base_addr, currentBlock->Memory_Size); + allocate_region((uint32_t) currentBlock->Base_addr, currentBlock->Memory_Size); + } + + currentBlock = (MemoryInfoBlock*) ((uint32_t)currentBlock->next + KERNEL_OFFSET ); + } + + uint32_t kernel_size = ((uint32_t)&kernel_end - (uint32_t)&kernel_begin ) - KERNEL_OFFSET; + + printf("kernel size in memory: 0x%x\n", kernel_size); + allocate_region((uint32_t)&kernel_begin, kernel_size); } -// NOTE: this can only give blocks of 4kb at a time! +// NOTE: This can only give blocks of 4kb at a time! +// We might at some point want to allocate multiple blocks at once. void* allocate_block() { uint8_t blocks_available = PMMInfoBlock->max_blocks - PMMInfoBlock->used_blocks; // Are there any blocks available? @@ -38,10 +67,8 @@ void* allocate_block() { } // Find 1 free block somewhere - int free_block_index = bitmap_first_unset(PMMInfoBlock->memoryBitMap, (PMMInfoBlock->max_blocks /8) /*memMap Size*/ ); + int free_block_index = bitmap_first_unset(PMMInfoBlock->memoryBitMap, PMMInfoBlock->max_blocks / 8 ); - - if(free_block_index == -1) { printf("Could not find a good block!\n"); @@ -83,20 +110,27 @@ void allocate_region(uint32_t startAddress, uint32_t size) { int NumberOfBlocksToAllocate = ( size / 1024) / 4 / 8 + 1; int startBlock = (startAddress / 1024) / 4 / 8 ; - // printf("NumberOfBlocksToAllocate: 0x%x\n", NumberOfBlocksToAllocate); - //printf( "start block: 0x%x\n" , startBlock); + for( int i = 0; i < NumberOfBlocksToAllocate; i++) { - - //printf("ALLOCATE BLOCK: 0x%x\n" , startBlock + i ); bitmap_unset(PMMInfoBlock->memoryBitMap, startBlock+ i); PMMInfoBlock->used_blocks++; } } + void deallocate_region(uint32_t StartAddress , uint32_t size ) { - // NOT IMPLEMENTED YET + // reverse of what happened in allocate_region + + int NumberOfBlocks = (size / 1024) / 4 / 8 + 1; + int startBlock = (StartAddress / 1024) / 4 / 8; + + for(int i = 0; i < NumberOfBlocks; i++) + { + bitmap_set(PMMInfoBlock->memoryBitMap, startBlock + i); + PMMInfoBlock->used_blocks --; + } } diff --git a/source/kernel/Memory/PhysicalMemoryManager.h b/source/kernel/Memory/PhysicalMemoryManager.h index 649c922..1122b25 100644 --- a/source/kernel/Memory/PhysicalMemoryManager.h +++ b/source/kernel/Memory/PhysicalMemoryManager.h @@ -1,17 +1,13 @@ #pragma once #include -#include "memoryinfo.h" - +#include "../PreKernel/bootstructure.h" #include "../Terminal/kterm.h" #include "../Lib/mem.h" #include "../bitmap.h" -// Asumming 32 bit x86 for now! -#define BLOCK_SIZE 4092 -#define WORD_SIZE 2 -#define BLOCKS_PER_WORD 32 +// Asumming i386 for now! +#define BLOCK_SIZE 4092 -#define KB_TO_BLOCKS(x) (x / BLOCK_SIZE) #define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) #define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) @@ -23,7 +19,7 @@ struct PhysicalMemoryManagerInfoBlock int used_blocks; }; -void initPMM(MemoryInfo* memory); +void SetupPhysicalMemoryManager(BootInfoBlock* memory); void free_block(void* ptr); void* allocate_block(); void allocate_region(uint32_t, uint32_t); diff --git a/source/kernel/PreKernel/bootstructure.h b/source/kernel/PreKernel/bootstructure.h index 70f9abf..78f4580 100644 --- a/source/kernel/PreKernel/bootstructure.h +++ b/source/kernel/PreKernel/bootstructure.h @@ -2,17 +2,12 @@ #include #include - extern "C" const uint32_t kernel_begin; extern "C" const uint32_t kernel_end; -// Put the BootInfoBlock 1MB above the kernel. -const uint32_t BootInfoBlock_pptr = (uint32_t)&kernel_end - 0xC0000000 + 0x1; -const uint32_t MemoryMapHeap_pptr = BootInfoBlock_pptr + 0x1; - #define IS_AVAILABLE_MEM(MEM_TYPE) MEM_TYPE & 0x1 #define IS_ACPI_MEM(MEM_TYPE) MEM_TYPE & 0x2 -#define IS_RESERVED_MEM(MEM_TYPE) MEM_TYPE & 0x3 +#define IS_RESERVED_MEM(MEM_TYPE) MEM_TYPE & 0x4 #define IS_NVS_MEMORY(MEM_TYPE) MEM_TYPE & 0x8 #define IS_BADRAM_MEMORY(MEM_TYPE) MEM_TYPE & 0x10 @@ -40,6 +35,11 @@ struct BootInfoBlock { bool PhysicalMemoryMapAvailable; MemoryInfoBlock* MemoryMap; + uint32_t map_size; + uint32_t MemorySize ; }; +// TODO Put the BootInfoBlock 1MB above the kernel. +const uint32_t BootInfoBlock_pptr = (uint32_t)&kernel_end - 0xC0000000 + 0x1; +const uint32_t MemoryMapHeap_pptr = BootInfoBlock_pptr + sizeof(BootInfoBlock); diff --git a/source/kernel/PreKernel/prekernel.cpp b/source/kernel/PreKernel/prekernel.cpp index 48ab238..479af04 100644 --- a/source/kernel/PreKernel/prekernel.cpp +++ b/source/kernel/PreKernel/prekernel.cpp @@ -5,7 +5,7 @@ #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) -extern "C" void testLauncher ( unsigned long magic, multiboot_info_t* mbi) { +extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) { // Create the bootInfoBlock at its location BootInfoBlock* BIB = (BootInfoBlock*) BootInfoBlock_pptr; @@ -74,23 +74,25 @@ if (CHECK_FLAG(mbi->flags, 6)) auto CurrentInfoBlock = BIB->MemoryMap; - - while((unsigned long) mmap < MemoryMapEnd){ + uint32_t RAM_size = 0; + while((unsigned long) mmap < MemoryMapEnd){ + BIB->map_size += sizeof(MemoryInfoBlock); CurrentInfoBlock->Base_addr = mmap->addr; CurrentInfoBlock->Memory_Size = mmap->len; if(mmap->type == MULTIBOOT_MEMORY_AVAILABLE) - CurrentInfoBlock->type &= 0x1; + CurrentInfoBlock->type |= 0x1; + RAM_size += mmap->len; if(mmap->type == MULTIBOOT_MEMORY_ACPI_RECLAIMABLE) - CurrentInfoBlock->type &= 0x2; + CurrentInfoBlock->type |= 0x2; if(mmap->type == MULTIBOOT_MEMORY_RESERVED) - CurrentInfoBlock->type &= 0x4; + CurrentInfoBlock->type |= 0x4; if(mmap->type == MULTIBOOT_MEMORY_NVS) - CurrentInfoBlock->type &= 0x8; + CurrentInfoBlock->type |= 0x8; if(mmap->type == MULTIBOOT_MEMORY_BADRAM) - CurrentInfoBlock->type &= 0x10; + CurrentInfoBlock->type |= 0x10; // continue to the next block @@ -102,7 +104,7 @@ if (CHECK_FLAG(mbi->flags, 6)) } CurrentInfoBlock->next = (MemoryInfoBlock*) 0x0; - + BIB->MemorySize = RAM_size; } else { BIB->PhysicalMemoryMapAvailable = false; diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index c9b8aff..d2f1018 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -4,9 +4,11 @@ extern "C" void early_main() /* * Initialize terminal interface */ - initGDT(); + kterm_init(); + initGDT(); + init_serial(); print_serial("Hello Higher half kernel!\n"); @@ -21,7 +23,7 @@ extern "C" void early_main() printf("|=== BarinkOS ===|\n"); printf("Kernel End Addr: 0x%x\n" , &kernel_end + KERNEL_BASE_ADDR); - uint32_t PageDirectoryEntryIndex = ((uint32_t)&kernel_end + KERNEL_BASE_ADDR ) >> 2 ; + uint32_t PageDirectoryEntryIndex = ((uint32_t)&kernel_end + KERNEL_BASE_ADDR ) >> 22 ; uint32_t PageTableEntryIndex = (((uint32_t)&kernel_end + KERNEL_BASE_ADDR) >> 12) & 0x1FFF; @@ -38,6 +40,8 @@ extern "C" void early_main() BootInfoBlock* BootInfo = (BootInfoBlock*) ( BootInfoBlock_pptr + 0xC0000000 ); + + printf("Size of BootInfoBlock: %d bytes\n", sizeof(BootInfoBlock)); printf("Bootloader information:\n"); if( BootInfo->ValidELFHeader ) { @@ -57,71 +61,58 @@ extern "C" void early_main() if(BootInfo->PhysicalMemoryMapAvailable) { printf("- Physical Memory Map available!\n"); - + printf("MemoryInfoheap size : %d bytes\n", BootInfo->map_size); // Print the memory regions MemoryInfoBlock* currentBlock = (MemoryInfoBlock*) ((uint32_t)BootInfo->MemoryMap + KERNEL_BASE_ADDR) ; - kterm_setcolor(VGA_COLOR_RED); - printf("size of MemoryInfoBlock: 0x%x\n", sizeof(MemoryInfoBlock)); - kterm_setcolor(VGA_COLOR_CYAN); - printf("Kernel End is at address: 0x%x\n", &kernel_end); - printf("BootInfo is at address: 0x%x\n", BootInfo); - printf("map is at address: 0x%x\n", currentBlock + KERNEL_BASE_ADDR); - kterm_setcolor(VGA_COLOR_WHITE); + printf( "Starting address: 0x%x\n", currentBlock); while( (uint32_t)currentBlock->next != 0x0 ) { - kterm_setcolor(VGA_COLOR_CYAN); - printf("map is at address: 0x%x\n", ( (uint32_t)currentBlock )); - kterm_setcolor(VGA_COLOR_WHITE); - - /* - uint32_t pageDirectoryIndex = ((uint32_t)¤tBlock ) >> 22; - printf("pageDirectoryIndex: %d\n", pageDirectoryIndex); - - uint32_t pageTableIndex = ((uint32_t)¤tBlock >> 12) & 0x1FFF; - printf("PagTableIndex: %d\n", pageTableIndex); - */ - - //printf("boot_page_directory addr: 0x%x\n", &boot_page_directory); - //printf("boot_page_table addr: 0x%x\n", &multiboot_page_table); - printf("Memory Region: \n"); - if(IS_AVAILABLE_MEM(currentBlock->type)){ //printf("AVAILABLE RAM\n"); } else if(IS_ACPI_MEM(currentBlock->type)){ - printf("ACPI MEMORY\n"); + //printf("ACPI MEMORY\n"); } else if(IS_RESERVED_MEM(currentBlock->type)){ - printf("RESERVED MEMORY\n"); + // printf("RESERVED MEMORY\n"); } else if(IS_NVS_MEMORY(currentBlock->type)){ - printf("NVS MEMORY \n"); + // printf("NVS MEMORY \n"); } else if(IS_BADRAM_MEMORY(currentBlock->type)){ - printf("BADRAM MEMORY \n"); + // printf("BADRAM MEMORY \n"); } else { // printf("(TYPE 0x%x )TYPE NOT SPECIFIED\n", currentBlock->type); } - - // printf("Base address: 0x%x, Memory size: 0x%x\n", currentBlock->Base_addr, currentBlock->Memory_Size); currentBlock = (MemoryInfoBlock*) ((uint32_t)currentBlock->next + KERNEL_BASE_ADDR ); } - + // Setup PhysicalMemoryManagement + SetupPhysicalMemoryManager(BootInfo); + // Small test! + void* block = allocate_block(); + void* block2 = allocate_block(); + printf("Allocated addresss 1: 0x%x 2: 0x%x\n", (uint32_t)block ,(uint32_t)block2); + free_block(block); + free_block(block2); + void* block3 = allocate_block(); + printf("Allocated addresss 3: 0x%x\n", (uint32_t)block3); + free_block(block3); } asm volatile("mov %cr0, %eax "); asm volatile("or $1, %eax"); - asm volatile("mov %eax, %cr0"); + asm volatile("mov %eax, %cr0"); // re-enable protected mode ? kernel_main(); } + void map_multiboot_info_structure(unsigned long addr){ // map the multiboot structure into virtual memory // so we can gather the necessary data from it. @@ -150,6 +141,7 @@ void map_multiboot_info_structure(unsigned long addr){ } void PhysicalMemoryAllocatorTest(){ + #ifdef UNIT_TESTS // test alloc_block uint8_t* memory = (uint8_t*) memAlloc.allocate_block(); -- 2.39.5 From c90e90bd8458b2e40e05b50699f50e4239973d20 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 1 Sep 2022 16:13:06 +0200 Subject: [PATCH 073/115] Moving the images from the repo into the disk folder --- images/BarinkOS.png | 3 --- images/BarinkOS_logo(standard).svg | 3 --- images/BarinkOS_logo.svg | 3 --- 3 files changed, 9 deletions(-) delete mode 100644 images/BarinkOS.png delete mode 100644 images/BarinkOS_logo(standard).svg delete mode 100644 images/BarinkOS_logo.svg diff --git a/images/BarinkOS.png b/images/BarinkOS.png deleted file mode 100644 index 3f6e913..0000000 --- a/images/BarinkOS.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:c3415fbc124e9a4f621f7aea377c782b56e42f6271bad434b4a3290437571acb -size 23402 diff --git a/images/BarinkOS_logo(standard).svg b/images/BarinkOS_logo(standard).svg deleted file mode 100644 index 700d71b..0000000 --- a/images/BarinkOS_logo(standard).svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:e9b64404160b415896faae7f3a2521a386162386f3c743cfed36633eb721ad75 -size 15322 diff --git a/images/BarinkOS_logo.svg b/images/BarinkOS_logo.svg deleted file mode 100644 index 7c38c24..0000000 --- a/images/BarinkOS_logo.svg +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fe3bc435da5cd4c8244caa71c57a7cfde01b0953be196e731f84d92942d5863f -size 18412 -- 2.39.5 From 15443601a6f9f907cb27327a8867b8dd8e7fd358 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 1 Sep 2022 16:13:58 +0200 Subject: [PATCH 074/115] Adding dev-scripts (Without much content) .. this can later help setting up the projects on other pc's. --- scripts/dev-setup/install.sh | 3 +++ scripts/hooks/pre-commit.hook.sh | 5 +++++ 2 files changed, 8 insertions(+) create mode 100644 scripts/dev-setup/install.sh create mode 100644 scripts/hooks/pre-commit.hook.sh diff --git a/scripts/dev-setup/install.sh b/scripts/dev-setup/install.sh new file mode 100644 index 0000000..9da7639 --- /dev/null +++ b/scripts/dev-setup/install.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +cmake -DLLVM_ENABLE_PROJECTS="clang-tools-extra" -DCMAKE_BUILD_TYPE=Release -G "Unix Makefiles" ../llvm \ No newline at end of file diff --git a/scripts/hooks/pre-commit.hook.sh b/scripts/hooks/pre-commit.hook.sh new file mode 100644 index 0000000..8a905bf --- /dev/null +++ b/scripts/hooks/pre-commit.hook.sh @@ -0,0 +1,5 @@ +#!/bin/bash + + +# Run clang-tidy + -- 2.39.5 From a70ae5ca314985a01b56f2a37550e0aab1b8e9a5 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 1 Sep 2022 16:42:56 +0200 Subject: [PATCH 075/115] KERNEL: Mapping the bios region ( below 1Mib) Keyboard.h: remove the incorrect use of typedef PhysicalMemoryManager.cpp: Map the Bios region as used. This prevents us from allocation the area used by the bios --- source/kernel/Drivers/PS-2/keyboard.h | 4 ++-- source/kernel/Memory/PhysicalMemoryManager.cpp | 3 +++ source/kernel/Memory/VirtualMemoryManager.h | 2 -- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/source/kernel/Drivers/PS-2/keyboard.h b/source/kernel/Drivers/PS-2/keyboard.h index f832178..f93b0fb 100644 --- a/source/kernel/Drivers/PS-2/keyboard.h +++ b/source/kernel/Drivers/PS-2/keyboard.h @@ -1,14 +1,14 @@ #pragma once #include #include "../../Terminal/kterm.h" -typedef enum ScanCodeSet{ +enum ScanCodeSet { None = 0, ScanCodeSet1 = 1, ScanCodeSet2 = 2, ScanCodeSet3 = 3, }; -typedef enum Modifiers{ +enum Modifiers { LSHIFT = 1, RSHIFT = 2, diff --git a/source/kernel/Memory/PhysicalMemoryManager.cpp b/source/kernel/Memory/PhysicalMemoryManager.cpp index 7551f91..bda801c 100644 --- a/source/kernel/Memory/PhysicalMemoryManager.cpp +++ b/source/kernel/Memory/PhysicalMemoryManager.cpp @@ -53,6 +53,9 @@ void SetupPhysicalMemoryManager( BootInfoBlock* Bootinfo) { printf("kernel size in memory: 0x%x\n", kernel_size); allocate_region((uint32_t)&kernel_begin, kernel_size); + + printf("allocate BIOS region"); + allocate_region (0x0000000, 0x00100000); } // NOTE: This can only give blocks of 4kb at a time! diff --git a/source/kernel/Memory/VirtualMemoryManager.h b/source/kernel/Memory/VirtualMemoryManager.h index 32abf0c..69e146e 100644 --- a/source/kernel/Memory/VirtualMemoryManager.h +++ b/source/kernel/Memory/VirtualMemoryManager.h @@ -8,5 +8,3 @@ void FreePage(uint32_t v_addr); void Map(uint32_t p_addr, uint32_t v_addr); void Unmap (uint32_t v_addr); - - -- 2.39.5 From 9893a0bd172fef2ae26ce92e2b0de3ad43aec517 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 1 Sep 2022 17:02:04 +0200 Subject: [PATCH 076/115] KERNEL: Cleanup Removing quite a few unnecessary parts. --- Makefile | 2 +- source/kernel/Interrupts/idt/idt.h | 4 +- source/kernel/Memory/MBIMMap/MBI_MMap.cpp | 44 ------------ source/kernel/Memory/MBIMMap/MBI_MMap.h | 18 ----- source/kernel/Memory/memoryinfo.h | 20 ------ source/kernel/Memory/paging.definitions.h | 56 --------------- source/kernel/Memory/paging.s | 44 ------------ .../SuperVisorTerminal/superVisorTerminal.cpp | 21 ++---- .../SuperVisorTerminal/superVisorTerminal.h | 3 +- source/kernel/{Boot => boot}/boot.s | 3 +- .../{Boot/Multiboot.S => boot/multiboot.s} | 0 source/kernel/bootinfo.h | 8 --- source/kernel/cpu.h | 3 +- source/kernel/kernel.cpp | 71 ++++--------------- source/kernel/kernel.h | 3 - 15 files changed, 26 insertions(+), 274 deletions(-) delete mode 100644 source/kernel/Memory/MBIMMap/MBI_MMap.cpp delete mode 100644 source/kernel/Memory/MBIMMap/MBI_MMap.h delete mode 100644 source/kernel/Memory/memoryinfo.h delete mode 100644 source/kernel/Memory/paging.definitions.h delete mode 100644 source/kernel/Memory/paging.s rename source/kernel/{Boot => boot}/boot.s (97%) rename source/kernel/{Boot/Multiboot.S => boot/multiboot.s} (100%) delete mode 100644 source/kernel/bootinfo.h diff --git a/Makefile b/Makefile index 2e1aff2..01da565 100644 --- a/Makefile +++ b/Makefile @@ -58,7 +58,7 @@ $(BUILD_DIR)/kterm.o: $(CPP) -c $(SRC_DIR)/kernel/Terminal/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/boot.o: - $(AS) $(SRC_DIR)/kernel/Boot/boot.s -o $(BUILD_DIR)/boot.o + $(AS) $(SRC_DIR)/kernel/boot/boot.s -o $(BUILD_DIR)/boot.o $(BUILD_DIR)/crti.o: $(AS) $(SRC_DIR)/kernel/crti.s -o $(BUILD_DIR)/crti.o diff --git a/source/kernel/Interrupts/idt/idt.h b/source/kernel/Interrupts/idt/idt.h index 8157fbe..6ca3399 100644 --- a/source/kernel/Interrupts/idt/idt.h +++ b/source/kernel/Interrupts/idt/idt.h @@ -1,7 +1,7 @@ #pragma once -#include "stdint.h" -#include "stddef.h" +#include +#include #include "../../Drivers/VGA/colors.h" #include "../../Drivers/PIC/pic.h" diff --git a/source/kernel/Memory/MBIMMap/MBI_MMap.cpp b/source/kernel/Memory/MBIMMap/MBI_MMap.cpp deleted file mode 100644 index 4dffba6..0000000 --- a/source/kernel/Memory/MBIMMap/MBI_MMap.cpp +++ /dev/null @@ -1,44 +0,0 @@ -#include "MBI_MMap.h" - -/* -void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt) { - - printf("mmap_addr = 0x%x, mmap_length = 0x%x\n", (unsigned) mbt->mmap_addr , (unsigned) mbt->mmap_length ); - - - multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) mbt->mmap_addr; - - for (; (unsigned long) mmap < mbt->mmap_addr + mbt->mmap_length; mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size))){ - - if ( mmap->type == MULTIBOOT_MEMORY_AVAILABLE){ - - memInfo->TotalMemory += mmap->len; - } else { - memInfo->ReservedMemory += mmap->len; - } - - print_Multiboot_memory_Map(mmap); - - } -} - - -*/ -/** - * @brief Debug Verbose functions - * - * @param mmap - */ -/* -void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap) { - printf( - "size = 0x%x, base_addr = 0x%x%08x, length = 0x%x%08x, type = 0x%x\n", - (unsigned) mmap->size, - (unsigned) (mmap->addr >> 32), - (unsigned) (mmap->addr & 0xffffffff), - (unsigned) (mmap->len >> 32), - (unsigned) (mmap->len & 0xffffffff), - (unsigned) mmap->type - ); -} -*/ \ No newline at end of file diff --git a/source/kernel/Memory/MBIMMap/MBI_MMap.h b/source/kernel/Memory/MBIMMap/MBI_MMap.h deleted file mode 100644 index 1bd1ad3..0000000 --- a/source/kernel/Memory/MBIMMap/MBI_MMap.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include -//#include "../../multiboot.h" -#include "../memoryinfo.h" - -void initialise_available_regions(uint32_t memoryMapAddr, uint32_t memoryMapLastAddr, uint32_t* memoryBitMap, int* used_blocks); - -/* -void mapMultibootMemoryMap( MemoryInfo* memInfo , multiboot_info_t *mbt); -*/ -/** - * @brief Debug Verbose Functions - * - * @param mmap - */ -/* -void print_Multiboot_memory_Map(multiboot_memory_map_t* mmap); -*/ diff --git a/source/kernel/Memory/memoryinfo.h b/source/kernel/Memory/memoryinfo.h deleted file mode 100644 index 9bbb626..0000000 --- a/source/kernel/Memory/memoryinfo.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include -#include - -struct MemoryArea{ - void* StartAddress; - size_t Size; - unsigned int type; - MemoryArea* Next; - -}__attribute__((packed)); - -struct MemoryInfo { - uint32_t TotalMemory; - uint32_t ReservedMemory; - MemoryArea* MemoryRegionList; -}__attribute__((packed)); - - - diff --git a/source/kernel/Memory/paging.definitions.h b/source/kernel/Memory/paging.definitions.h deleted file mode 100644 index 2f771f7..0000000 --- a/source/kernel/Memory/paging.definitions.h +++ /dev/null @@ -1,56 +0,0 @@ -#pragma once -#include -/* - This file contains some handy definitions for different types - that have to do with paging in atleast 32 bit and maybe sometime in the future - also 64 bit mode. -*/ - -#define MAX_DIRECTORY_ENTRIES 1024 -#define MAX_PAGE_TABLE_ENTRIES 1024 -#define MAX_PAGES 1024 - -#define PHYSICAL_ADDRESS uint32_t -#define VIRTUAL_ADDRESS uint32_t - -#define PageDirectoryEntry uint32_t -#define PageTableEntry uint32_t - - -#define KERNEL_VRT_MEMORY_BEGIN 0xC0000000 -#define KERNEL_VRT_MEMORY_END 0xCFFFFFFF -#define PAGE_SIZE 4096; - - -// NOTE: FIXME: I am fairly certain these masks are off by one! - -#define PD32_PRESENT_MASK (0x1 << 0) -#define PD32_READ_WRITE_MASK (0x1 << 1) -#define PD32_SUPERVISOR_MASK (0x1 << 2) -#define PD32_WRITE_THROUGH_MASK (0x1 << 3) -#define PD32_CACHE_DISABLE_MASK (0x1 << 4) -#define PD32_ACCESSED_MASK (0x1 << 5) -#define PD32_AVAILABLE_1_4KB_MASK (0x1 << 6) -#define PD32_DISABLE_4MB_MASK (0x1 << 6) -#define PD32_PAGE_SIZE_MASK (0x1 << 7) -#define PD32_GLOBAL_4MB_MASK (0x1 << 8) -#define PD32_AVAILABLE_2_4MB_MASK ( 14 << 9) -#define PD32_AVAILABLE_2_4KB_MASK ( 15 << 8) -#define PD32_ADDRESS_4KB_MASK (0x8FFFF << 12) -#define PD32_PAGE_ATTRIBUTE_TABLE_4MB_MASK (0x1 << 12) -#define PD32_HIGH_HALF_ADDRESS_4MB_MASK (0x7F<< 13) -#define PD32_RESERVED_4MB_MASK (0x1 << 21) -#define PD32_LOWER_HALF_ADDRESS_4MB_MASK (0x1FF << 22) - -#define PT32_PRESENT_MASK (0x1 << 0) -#define PT32_READ_WRITE_MASK (0x1 << 1) -#define PT32_SUPERVISOR_MASK (0x1 << 2) -#define PT32_WRITE_THROUGH_MASK (0x1 << 3) -#define PT32_CACHE_DISABLE_MASK (0x1 << 4) -#define PT32_ACCESSED_MASK (0x1 << 5) -#define PT32_DIRTY_MASK (0x1 << 6) -#define PT32_PAGE_ATTRIBUTE_TABLE_MASK (0x1 << 7) -#define PT32_GLOBAL_MASK (0x1 << 8) -#define PT32_AVAILABLE_MASK (0x7 << 9) -#define PT32_CACHE_DISABLE_MASK (0x7FFFF << 12) - diff --git a/source/kernel/Memory/paging.s b/source/kernel/Memory/paging.s deleted file mode 100644 index ca25a7d..0000000 --- a/source/kernel/Memory/paging.s +++ /dev/null @@ -1,44 +0,0 @@ -# NOTE: I wish this wasn't AT&T Syntax its horrible -# REMINDER: INSTRUCTION FROM_REGISTER, TO_REGISTER -.globl enablePaging -enablePaging: - # Create a new call frame - push %ebp - mov %esp, %ebp - - # Set the PG bit of CR0 - mov %cr0, %eax - or $0x80000000, %eax - mov %eax, %cr0 - - # Restore to the previous call frame - mov %ebp, %esp - pop %ebp - ret - -.globl loadPageDirectory -loadPageDirectory: - push %ebp - mov %esp, %ebp - - /* NOTE: We should probably check if paging is already enabled. - Changing the CR3 register whilst paging is enabled might - result in unwanted behaviour (in the worst case) or cause a - fault (in the best case). - */ - - mov 8(%esp), %eax # Move the first argument in the eax register - - mov %eax, %cr3 # Move the value of eax into the CR3 register - - /* - Moving the value of the argument passed to this function - into the CR3 register will allow the MMU to access the paging - structure we setup in memory once we enable paging - */ - - mov %ebp, %esp - pop %ebp - ret - - diff --git a/source/kernel/SuperVisorTerminal/superVisorTerminal.cpp b/source/kernel/SuperVisorTerminal/superVisorTerminal.cpp index 79dd349..74e5dcb 100644 --- a/source/kernel/SuperVisorTerminal/superVisorTerminal.cpp +++ b/source/kernel/SuperVisorTerminal/superVisorTerminal.cpp @@ -1,6 +1,6 @@ #include "superVisorTerminal.h" -void startSuperVisorTerminal(BootInfo* bootinfo){ +void startSuperVisorTerminal(){ while (true){ printf("SUPERVISOR:>$ " ); @@ -38,22 +38,11 @@ void startSuperVisorTerminal(BootInfo* bootinfo){ { // Show memory layout printf("========= Memory ==========\n"); + printf("Not Available!\n"); printf("Kernel MemoryMap:\n"); - //printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); - printf("Frames used: 0x%x blocks of 4 KiB\n", 0); - const int bytesInGiB = 1073741824; - int64_t bytesLeft = (bootinfo->memory->TotalMemory % bytesInGiB) / bytesInGiB; - int64_t effectiveNumberOfGib = bootinfo->memory->TotalMemory / bytesInGiB; - - int64_t GiBs = effectiveNumberOfGib + bytesLeft; - - printf("Available Memory: %d bytes, %d GiB\n", bootinfo->memory->TotalMemory, GiBs ); - printf("Reserved Memory: %d bytes\n", bootinfo->memory->ReservedMemory); - - //printf("\n\n"); - //PrintPhysicalMemoryAllocation( ); - - + printf("Frames used: -- \n"); + printf("Available Memory:-- \n"); + printf("Reserved Memory: -- bytes\n"); } else if(strncmp("TEST", command, characterCount) == 0) { diff --git a/source/kernel/SuperVisorTerminal/superVisorTerminal.h b/source/kernel/SuperVisorTerminal/superVisorTerminal.h index eeed1df..7821191 100644 --- a/source/kernel/SuperVisorTerminal/superVisorTerminal.h +++ b/source/kernel/SuperVisorTerminal/superVisorTerminal.h @@ -4,6 +4,5 @@ #include "../Drivers/PIT/pit.h" #include "../Drivers/PS-2/keyboard.h" #include "../Memory/PhysicalMemoryManager.h" -#include "../bootinfo.h" -void startSuperVisorTerminal(BootInfo * ); \ No newline at end of file +void startSuperVisorTerminal(); \ No newline at end of file diff --git a/source/kernel/Boot/boot.s b/source/kernel/boot/boot.s similarity index 97% rename from source/kernel/Boot/boot.s rename to source/kernel/boot/boot.s index f8eb7f6..6c1faf6 100644 --- a/source/kernel/Boot/boot.s +++ b/source/kernel/boot/boot.s @@ -1,4 +1,4 @@ -.include "./source/kernel/Boot/Multiboot.S" +.include "./source/kernel/boot/multiboot.s" /* * Allocate initial stack */ @@ -116,7 +116,6 @@ isPaging: .include "./source/kernel/irs_table.s" .include "./source/kernel/irq_table.s" .include "./source/kernel/Interrupts/idt/idt.s" -.include "./source/kernel/Memory/paging.s" .include "./source/kernel/cpu.s" diff --git a/source/kernel/Boot/Multiboot.S b/source/kernel/boot/multiboot.s similarity index 100% rename from source/kernel/Boot/Multiboot.S rename to source/kernel/boot/multiboot.s diff --git a/source/kernel/bootinfo.h b/source/kernel/bootinfo.h deleted file mode 100644 index 1daa198..0000000 --- a/source/kernel/bootinfo.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once -#include "Memory/memoryinfo.h" - -struct BootInfo{ - const char* BootStructureID = "BarinkOS"; - MemoryInfo* memory; - -}; \ No newline at end of file diff --git a/source/kernel/cpu.h b/source/kernel/cpu.h index 94d9485..0994c99 100644 --- a/source/kernel/cpu.h +++ b/source/kernel/cpu.h @@ -1,4 +1,5 @@ -#pragma once +#pragma once +#include /* Based on Intel specifications. diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index d2f1018..b66b1ed 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -21,7 +21,7 @@ extern "C" void early_main() * Show a little banner for cuteness */ printf("|=== BarinkOS ===|\n"); - printf("Kernel End Addr: 0x%x\n" , &kernel_end + KERNEL_BASE_ADDR); + printf("Kernel End Addr: 0x%x\n" , &kernel_end ); uint32_t PageDirectoryEntryIndex = ((uint32_t)&kernel_end + KERNEL_BASE_ADDR ) >> 22 ; @@ -93,16 +93,7 @@ extern "C" void early_main() // Setup PhysicalMemoryManagement SetupPhysicalMemoryManager(BootInfo); - // Small test! - - void* block = allocate_block(); - void* block2 = allocate_block(); - printf("Allocated addresss 1: 0x%x 2: 0x%x\n", (uint32_t)block ,(uint32_t)block2); - free_block(block); - free_block(block2); - void* block3 = allocate_block(); - printf("Allocated addresss 3: 0x%x\n", (uint32_t)block3); - free_block(block3); + } asm volatile("mov %cr0, %eax "); @@ -112,57 +103,23 @@ extern "C" void early_main() } - -void map_multiboot_info_structure(unsigned long addr){ - // map the multiboot structure into virtual memory - // so we can gather the necessary data from it. - - uint32_t pageDirectoryIndex = (addr ) >> 22; - printf("pageDirectoryIndex: %d\n", pageDirectoryIndex); - - uint32_t pageTableIndex = (addr >> 12) & 0x1FFF; - printf("PagTableIndex: %d\n", pageTableIndex); - - - printf("boot_page_directory addr: 0x%x\n", &boot_page_directory); - printf("boot_page_table addr: 0x%x\n", &multiboot_page_table); - - uint32_t* current_page_directory = &boot_page_directory; - uint32_t* needed_page_table = &multiboot_page_table - KERNEL_BASE_ADDR; - // set the page tabel reference; - current_page_directory[pageDirectoryIndex] = (uint32_t)&multiboot_page_table - KERNEL_BASE_ADDR + 0x003; - - // set the page reference; - needed_page_table[ pageTableIndex ] = addr | 0x003; - - - // Reload CR3 to force a flush - asm("movl %cr3, %ecx;" "movl %ecx, %cr3" ); -} - void PhysicalMemoryAllocatorTest(){ - -#ifdef UNIT_TESTS - // test alloc_block - uint8_t* memory = (uint8_t*) memAlloc.allocate_block(); - printf("Got a new pointer: 0x%x\n", memory); - - uint8_t* memory2 = (uint8_t*) memAlloc.allocate_block(); - printf("Got a new pointer: 0x%x\n", memory2); - - memAlloc.free_block((void*) memory); - uint8_t* newBlockPlse = (uint8_t*) memAlloc.allocate_block(); -#endif + #ifdef UNIT_TESTS + // Small test! + void* block = allocate_block(); + void* block2 = allocate_block(); + printf("Allocated addresss 1: 0x%x 2: 0x%x\n", (uint32_t)block ,(uint32_t)block2); + free_block(block); + free_block(block2); + void* block3 = allocate_block(); + printf("Allocated addresss 3: 0x%x\n", (uint32_t)block3); + free_block(block3); + #endif } extern "C" void kernel_main () { pit_initialise(); - // Create a dummy BootInfo object - // TODO: This should be done properly or the dependency should - // be removed from the SuperVisorTerminal. - BootInfo* bootinfo = {}; - - startSuperVisorTerminal(bootinfo); + startSuperVisorTerminal(); } \ No newline at end of file diff --git a/source/kernel/kernel.h b/source/kernel/kernel.h index 86bf667..c335c46 100644 --- a/source/kernel/kernel.h +++ b/source/kernel/kernel.h @@ -8,10 +8,7 @@ extern "C" #include "Drivers/VGA/VBE.h" #include "Terminal/kterm.h" -#include "bootinfo.h" - #include "Memory/PhysicalMemoryManager.h" -#include "Memory/memoryinfo.h" #include "Memory/VirtualMemoryManager.h" #include "Memory/GDT/gdtc.h" -- 2.39.5 From 13e9beea79d3284523017a2fb82c14c495b893db Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 1 Sep 2022 20:16:16 +0200 Subject: [PATCH 077/115] KERNEL: Implementing VMM & cleaning up Folders now are alll lower case Started working on the implementation of the Virtual memory manager. Implemented allocate and free page funtionality for as far as I can atm. Implemented the --- Makefile | 27 ++++--- source/kernel/Memory/VirtualMemoryManager.cpp | 24 ------ .../SuperVisorTerminal/superVisorTerminal.h | 8 -- source/kernel/boot/boot.s | 15 +--- source/kernel/cpu.cpp | 39 ++++++++++ source/kernel/cpu.h | 11 ++- source/kernel/cpu.s | 63 ---------------- .../kernel/{Drivers => drivers}/cmos/cmos.cpp | 0 .../{Drivers/PCI => drivers/pci}/pci.cpp | 0 .../kernel/{Drivers/PCI => drivers/pci}/pci.h | 0 .../{Drivers/PIC => drivers/pic}/pic.cpp | 0 .../kernel/{Drivers/PIC => drivers/pic}/pic.h | 0 .../{Drivers/PIT => drivers/pit}/pit.cpp | 2 +- .../kernel/{Drivers/PIT => drivers/pit}/pit.h | 1 + .../PS-2 => drivers/ps-2}/keyboard.cpp | 0 .../{Drivers/PS-2 => drivers/ps-2}/keyboard.h | 2 +- .../Serial => drivers/serial}/serial.cpp | 0 .../Serial => drivers/serial}/serial.h | 0 .../kernel/{Drivers/VGA => drivers/vga}/VBE.h | 0 .../{Drivers/VGA => drivers/vga}/colors.h | 0 .../{FileSystem => filesystem}/FAT/FAT16.cpp | 0 .../{FileSystem => filesystem}/FAT/FAT16.h | 0 .../{Interrupts => interrupts}/idt/idt.cpp | 4 +- .../{Interrupts => interrupts}/idt/idt.h | 6 +- .../{Interrupts => interrupts}/idt/idt.s | 0 .../idt/scancodes/set1.h | 0 source/kernel/kernel.cpp | 11 +-- source/kernel/kernel.h | 20 ++--- source/kernel/{Lib => lib}/mem.h | 0 source/kernel/{Lib => lib}/string.c | 0 source/kernel/{Lib => lib}/string.h | 0 .../kernel/{Memory => memory}/KernelHeap.cpp | 3 +- source/kernel/{Memory => memory}/KernelHeap.h | 0 .../PhysicalMemoryManager.cpp | 30 ++++---- .../PhysicalMemoryManager.h | 10 +-- source/kernel/memory/VirtualMemoryManager.cpp | 73 +++++++++++++++++++ .../{Memory => memory}/VirtualMemoryManager.h | 2 +- .../kernel/{Memory/GDT => memory/gdt}/gdt.s | 0 .../{Memory/GDT => memory/gdt}/gdtc.cpp | 2 +- .../kernel/{Memory/GDT => memory/gdt}/gdtc.h | 0 .../{PreKernel => prekernel}/bootstructure.h | 0 .../{PreKernel => prekernel}/multiboot.h | 0 .../{PreKernel => prekernel}/prekernel.cpp | 1 + source/kernel/serial.h | 2 +- .../superVisorTerminal.cpp | 0 .../supervisorterminal/superVisorTerminal.h | 8 ++ .../kernel/{Terminal => terminal}/kterm.cpp | 0 source/kernel/{Terminal => terminal}/kterm.h | 4 +- 48 files changed, 195 insertions(+), 173 deletions(-) delete mode 100644 source/kernel/Memory/VirtualMemoryManager.cpp delete mode 100644 source/kernel/SuperVisorTerminal/superVisorTerminal.h create mode 100644 source/kernel/cpu.cpp delete mode 100644 source/kernel/cpu.s rename source/kernel/{Drivers => drivers}/cmos/cmos.cpp (100%) rename source/kernel/{Drivers/PCI => drivers/pci}/pci.cpp (100%) rename source/kernel/{Drivers/PCI => drivers/pci}/pci.h (100%) rename source/kernel/{Drivers/PIC => drivers/pic}/pic.cpp (100%) rename source/kernel/{Drivers/PIC => drivers/pic}/pic.h (100%) rename source/kernel/{Drivers/PIT => drivers/pit}/pit.cpp (95%) rename source/kernel/{Drivers/PIT => drivers/pit}/pit.h (88%) rename source/kernel/{Drivers/PS-2 => drivers/ps-2}/keyboard.cpp (100%) rename source/kernel/{Drivers/PS-2 => drivers/ps-2}/keyboard.h (93%) rename source/kernel/{Drivers/Serial => drivers/serial}/serial.cpp (100%) rename source/kernel/{Drivers/Serial => drivers/serial}/serial.h (100%) rename source/kernel/{Drivers/VGA => drivers/vga}/VBE.h (100%) rename source/kernel/{Drivers/VGA => drivers/vga}/colors.h (100%) rename source/kernel/{FileSystem => filesystem}/FAT/FAT16.cpp (100%) rename source/kernel/{FileSystem => filesystem}/FAT/FAT16.h (100%) rename source/kernel/{Interrupts => interrupts}/idt/idt.cpp (99%) rename source/kernel/{Interrupts => interrupts}/idt/idt.h (94%) rename source/kernel/{Interrupts => interrupts}/idt/idt.s (100%) rename source/kernel/{Interrupts => interrupts}/idt/scancodes/set1.h (100%) rename source/kernel/{Lib => lib}/mem.h (100%) rename source/kernel/{Lib => lib}/string.c (100%) rename source/kernel/{Lib => lib}/string.h (100%) rename source/kernel/{Memory => memory}/KernelHeap.cpp (93%) rename source/kernel/{Memory => memory}/KernelHeap.h (100%) rename source/kernel/{Memory => memory}/PhysicalMemoryManager.cpp (84%) rename source/kernel/{Memory => memory}/PhysicalMemoryManager.h (78%) create mode 100644 source/kernel/memory/VirtualMemoryManager.cpp rename source/kernel/{Memory => memory}/VirtualMemoryManager.h (87%) rename source/kernel/{Memory/GDT => memory/gdt}/gdt.s (100%) rename source/kernel/{Memory/GDT => memory/gdt}/gdtc.cpp (97%) rename source/kernel/{Memory/GDT => memory/gdt}/gdtc.h (100%) rename source/kernel/{PreKernel => prekernel}/bootstructure.h (100%) rename source/kernel/{PreKernel => prekernel}/multiboot.h (100%) rename source/kernel/{PreKernel => prekernel}/prekernel.cpp (99%) rename source/kernel/{SuperVisorTerminal => supervisorterminal}/superVisorTerminal.cpp (100%) create mode 100644 source/kernel/supervisorterminal/superVisorTerminal.h rename source/kernel/{Terminal => terminal}/kterm.cpp (100%) rename source/kernel/{Terminal => terminal}/kterm.h (93%) diff --git a/Makefile b/Makefile index 01da565..3f64c5a 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o SRC_DIR = source BUILD_DIR = build @@ -55,7 +55,7 @@ $(BUILD_DIR)/kernel.o: $(CPP) -c $(SRC_DIR)/kernel/kernel.cpp -o $(BUILD_DIR)/kernel.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/kterm.o: - $(CPP) -c $(SRC_DIR)/kernel/Terminal/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/terminal/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/boot.o: $(AS) $(SRC_DIR)/kernel/boot/boot.s -o $(BUILD_DIR)/boot.o @@ -71,38 +71,41 @@ $(BUILD_DIR)/io.o: $(BUILD_DIR)/idt.o: - $(CPP) -c $(SRC_DIR)/kernel/Interrupts/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/interrupts/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/gdtc.o: - $(CPP) -c $(SRC_DIR)/kernel/Memory/GDT/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/memory/gdt/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pic.o: - $(CPP) -c $(SRC_DIR)/kernel/Drivers/PIC/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/string.o: - $(CC) -c $(SRC_DIR)/kernel/Lib/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 + $(CC) -c $(SRC_DIR)/kernel/lib/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 $(BUILD_DIR)/pit.o: - $(CPP) -c $(SRC_DIR)/kernel/Drivers/PIT/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/pit/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/keyboard.o: - $(CPP) -c $(SRC_DIR)/kernel/Drivers/PS-2/keyboard.cpp -o $(BUILD_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/ps-2/keyboard.cpp -o $(BUILD_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/time.o: $(CPP) -c $(SRC_DIR)/kernel/time.cpp -o $(BUILD_DIR)/time.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/sv-terminal.o: - $(CPP) -c $(SRC_DIR)/kernel/SuperVisorTerminal/superVisorTerminal.cpp -o $(BUILD_DIR)/sv-terminal.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/supervisorterminal/superVisorTerminal.cpp -o $(BUILD_DIR)/sv-terminal.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/memory.o: - $(CPP) -c $(SRC_DIR)/kernel/Memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/paging.o: - $(CPP) -c $(SRC_DIR)/kernel/Memory/VirtualMemoryManager.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/memory/VirtualMemoryManager.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/prekernel.o: - $(CPP) -c $(SRC_DIR)/kernel/PreKernel/prekernel.cpp -o $(BUILD_DIR)/prekernel.o $(CFLAGS) -fno-exceptions -fno-rtti \ No newline at end of file + $(CPP) -c $(SRC_DIR)/kernel/prekernel/prekernel.cpp -o $(BUILD_DIR)/prekernel.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(BUILD_DIR)/cpu.o: + $(CPP) -c $(SRC_DIR)/kernel/cpu.cpp -o $(BUILD_DIR)/cpu.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/source/kernel/Memory/VirtualMemoryManager.cpp b/source/kernel/Memory/VirtualMemoryManager.cpp deleted file mode 100644 index 2af5da6..0000000 --- a/source/kernel/Memory/VirtualMemoryManager.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include "VirtualMemoryManager.h" - -extern "C" void loadPageDirectory (uint32_t* addr ); -extern "C" void enablePaging(); - -void AllocatePage(uint32_t vaddr) -{ - -} - -void FreePage(uint32_t vaddr ) -{ - -} - -void Map ( uint32_t vaddr, uint32_t paddr) -{ - -} - -void Unmap(uint32_t vaddr) -{ - // NOTE: I will implement lazy unmapping for now -} diff --git a/source/kernel/SuperVisorTerminal/superVisorTerminal.h b/source/kernel/SuperVisorTerminal/superVisorTerminal.h deleted file mode 100644 index 7821191..0000000 --- a/source/kernel/SuperVisorTerminal/superVisorTerminal.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once -#include "../Terminal/kterm.h" -#include "../time.h" -#include "../Drivers/PIT/pit.h" -#include "../Drivers/PS-2/keyboard.h" -#include "../Memory/PhysicalMemoryManager.h" - -void startSuperVisorTerminal(); \ No newline at end of file diff --git a/source/kernel/boot/boot.s b/source/kernel/boot/boot.s index 6c1faf6..21a1bb8 100644 --- a/source/kernel/boot/boot.s +++ b/source/kernel/boot/boot.s @@ -17,6 +17,7 @@ stack_top: .globl boot_page_directory boot_page_directory: .skip 4096 +.globl boot_page_table boot_page_table: .skip 4096 .globl multiboot_page_table @@ -60,15 +61,6 @@ _start: 3: # Map VGA video memory to 0xC03FF00 as "present, writable" movl $(0x000B8000 | 0x003), boot_page_table - 0xC0000000 + 1023 * 4 - # IMPORTANT NOTE FROM WIKI.OSDEV.ORG/HIGHER_HALF_X86_BARE_BONES - - # The page table is used at both page directory entry 0 (virtually from 0x0 - # to 0x3FFFFF) (thus identity mapping the kernel) and page directory entry - # 768 (virtually from 0xC0000000 to 0xC03FFFFF) (thus mapping it in the - # higher half). The kernel is identity mapped because enabling paging does - # not change the next instruction, which continues to be physical. The CPU - # would instead page fault if there was no identity mapping.\ - # Map the page table to both virtual addresss 0x00000000 and 0xC0000000 movl $(boot_page_table - 0xC0000000 + 0x003), boot_page_directory - 0xC0000000 + 0 movl $(boot_page_table - 0xC0000000 + 0x003), boot_page_directory - 0xC0000000 + 768 * 4 @@ -112,10 +104,9 @@ isPaging: jmp 1b -.include "./source/kernel/Memory/GDT/gdt.s" +.include "./source/kernel/memory/gdt/gdt.s" .include "./source/kernel/irs_table.s" .include "./source/kernel/irq_table.s" -.include "./source/kernel/Interrupts/idt/idt.s" -.include "./source/kernel/cpu.s" +.include "./source/kernel/interrupts/idt/idt.s" diff --git a/source/kernel/cpu.cpp b/source/kernel/cpu.cpp new file mode 100644 index 0000000..897e92d --- /dev/null +++ b/source/kernel/cpu.cpp @@ -0,0 +1,39 @@ +#include "cpu.h" + + +uint32_t GetEFLAGS() +{ + uint32_t EFLAGS = 0; + asm volatile ("pushfl;" "movl 4(%%esp), %%edx" : "=d"(EFLAGS)); + return EFLAGS; +} + + +uint32_t GetCR0() +{ + uint32_t cr0_value; + asm volatile ("movl %%cr0, %%edx" : "=d"(cr0_value)); + return cr0_value; + +} + + +uint32_t GetCR2(){ + uint32_t cr2_value; + __asm__ volatile("movl %%cr2, %%edx": "=d"(cr2_value)); + return cr2_value; +} + + +uint32_t GetCR3(){ + uint32_t cr3_value; + __asm__ volatile("movl %%cr3, %%edx": "=d"(cr3_value)); + return cr3_value; +} + + +uint32_t GetCR4(){ + uint32_t cr4_value; + __asm__ volatile("movl %%cr4, %%edx": "=d"(cr4_value)); + return cr4_value; +} \ No newline at end of file diff --git a/source/kernel/cpu.h b/source/kernel/cpu.h index 0994c99..99cf6a8 100644 --- a/source/kernel/cpu.h +++ b/source/kernel/cpu.h @@ -9,19 +9,18 @@ C++ interface for the cpu.s assembly file. ©Nigel Barink - 2022 */ - /* * EFLAGS FUNCTIONS */ -extern "C" uint32_t GetEFLAGS(); +uint32_t GetEFLAGS(); /* * CONTROL_REGISTER_0 FUNCTIONS */ -extern "C" uint32_t GetCR0(); +uint32_t GetCR0(); /* struct CR0_Register { @@ -57,7 +56,7 @@ extern "C" uint32_t GetCR0(); * CONTROL_REGISTER_4 FUNCTIONS */ -extern "C" uint32_t GetCR4(); +uint32_t GetCR4(); #define GET_PSE_BIT(CONTROL_REGISTER_4) (CONTROL_REGISTER_4&0x4) #define GET_PAE_BIT(CONTROL_REGISTER_4) (CONTROL_REGISTER_4&0x5) @@ -66,10 +65,10 @@ extern "C" uint32_t GetCR4(); * CONTROL_REGISTER_2 FUNCTIONS */ -extern "C" uint32_t GetCR2(); +uint32_t GetCR2(); /* * CONTROL_REGISTER_3 FUNCTIONS */ -extern "C" uint32_t GetCR3(); \ No newline at end of file +uint32_t GetCR3(); \ No newline at end of file diff --git a/source/kernel/cpu.s b/source/kernel/cpu.s deleted file mode 100644 index 2df41db..0000000 --- a/source/kernel/cpu.s +++ /dev/null @@ -1,63 +0,0 @@ -# Basic cpu functions -.globl GetCR0 -GetCR0: - push %ebp # save the base pointer on the stack - mov %esp, %ebp # Set the base pointer to the current stack pointer - - xor %eax, %eax # Clear EAX to make sure no weird stuff is going on - mov %cr0, %eax # Copy the value of the CR0 register into EAX - - mov %ebp, %esp # restore the base pointer - pop %ebp - ret - -.globl GetCR4 -GetCR4: - push %ebp - mov %esp, %ebp - - xor %eax, %eax - mov %cr4, %eax - - mov %ebp, %esp - pop %ebp - ret - - - -.globl GetEFLAGS -GetEFLAGS: - push %ebp - mov %esp, %ebp - - xor %eax, %eax - pushfl # Push the EFLAGS register content onto the stack, should be pushfd but GAS apparently doesn't agree - mov 4(%esp) , %eax - - mov %ebp, %esp - pop %ebp - ret - -.globl GetCR2 -GetCR2: - push %ebp - mov %esp, %ebp - - xor %eax, %eax - mov %cr2, %eax - - mov %ebp, %esp - pop %ebp - ret - -.globl GetCR3 -GetCR3: - push %ebp - mov %esp, %ebp - - xor %eax, %eax - mov %cr3, %eax - - mov %ebp, %esp - pop %ebp - ret diff --git a/source/kernel/Drivers/cmos/cmos.cpp b/source/kernel/drivers/cmos/cmos.cpp similarity index 100% rename from source/kernel/Drivers/cmos/cmos.cpp rename to source/kernel/drivers/cmos/cmos.cpp diff --git a/source/kernel/Drivers/PCI/pci.cpp b/source/kernel/drivers/pci/pci.cpp similarity index 100% rename from source/kernel/Drivers/PCI/pci.cpp rename to source/kernel/drivers/pci/pci.cpp diff --git a/source/kernel/Drivers/PCI/pci.h b/source/kernel/drivers/pci/pci.h similarity index 100% rename from source/kernel/Drivers/PCI/pci.h rename to source/kernel/drivers/pci/pci.h diff --git a/source/kernel/Drivers/PIC/pic.cpp b/source/kernel/drivers/pic/pic.cpp similarity index 100% rename from source/kernel/Drivers/PIC/pic.cpp rename to source/kernel/drivers/pic/pic.cpp diff --git a/source/kernel/Drivers/PIC/pic.h b/source/kernel/drivers/pic/pic.h similarity index 100% rename from source/kernel/Drivers/PIC/pic.h rename to source/kernel/drivers/pic/pic.h diff --git a/source/kernel/Drivers/PIT/pit.cpp b/source/kernel/drivers/pit/pit.cpp similarity index 95% rename from source/kernel/Drivers/PIT/pit.cpp rename to source/kernel/drivers/pit/pit.cpp index afe8536..6b5eaa3 100644 --- a/source/kernel/Drivers/PIT/pit.cpp +++ b/source/kernel/drivers/pit/pit.cpp @@ -1,5 +1,5 @@ #include "pit.h" -#include "../../Terminal/kterm.h" + uint32_t pit_tick = 0; diff --git a/source/kernel/Drivers/PIT/pit.h b/source/kernel/drivers/pit/pit.h similarity index 88% rename from source/kernel/Drivers/PIT/pit.h rename to source/kernel/drivers/pit/pit.h index 7e4d0f1..72bb383 100644 --- a/source/kernel/Drivers/PIT/pit.h +++ b/source/kernel/drivers/pit/pit.h @@ -1,6 +1,7 @@ #pragma once #include #include "../../io.h" +#include "../../terminal/kterm.h" #define PIT_DATA_0 0x40 #define PIT_DATA_1 0x41 #define PIT_DATA_2 0x42 diff --git a/source/kernel/Drivers/PS-2/keyboard.cpp b/source/kernel/drivers/ps-2/keyboard.cpp similarity index 100% rename from source/kernel/Drivers/PS-2/keyboard.cpp rename to source/kernel/drivers/ps-2/keyboard.cpp diff --git a/source/kernel/Drivers/PS-2/keyboard.h b/source/kernel/drivers/ps-2/keyboard.h similarity index 93% rename from source/kernel/Drivers/PS-2/keyboard.h rename to source/kernel/drivers/ps-2/keyboard.h index f93b0fb..52c53ba 100644 --- a/source/kernel/Drivers/PS-2/keyboard.h +++ b/source/kernel/drivers/ps-2/keyboard.h @@ -1,6 +1,6 @@ #pragma once #include -#include "../../Terminal/kterm.h" +#include "../../terminal/kterm.h" enum ScanCodeSet { None = 0, ScanCodeSet1 = 1, diff --git a/source/kernel/Drivers/Serial/serial.cpp b/source/kernel/drivers/serial/serial.cpp similarity index 100% rename from source/kernel/Drivers/Serial/serial.cpp rename to source/kernel/drivers/serial/serial.cpp diff --git a/source/kernel/Drivers/Serial/serial.h b/source/kernel/drivers/serial/serial.h similarity index 100% rename from source/kernel/Drivers/Serial/serial.h rename to source/kernel/drivers/serial/serial.h diff --git a/source/kernel/Drivers/VGA/VBE.h b/source/kernel/drivers/vga/VBE.h similarity index 100% rename from source/kernel/Drivers/VGA/VBE.h rename to source/kernel/drivers/vga/VBE.h diff --git a/source/kernel/Drivers/VGA/colors.h b/source/kernel/drivers/vga/colors.h similarity index 100% rename from source/kernel/Drivers/VGA/colors.h rename to source/kernel/drivers/vga/colors.h diff --git a/source/kernel/FileSystem/FAT/FAT16.cpp b/source/kernel/filesystem/FAT/FAT16.cpp similarity index 100% rename from source/kernel/FileSystem/FAT/FAT16.cpp rename to source/kernel/filesystem/FAT/FAT16.cpp diff --git a/source/kernel/FileSystem/FAT/FAT16.h b/source/kernel/filesystem/FAT/FAT16.h similarity index 100% rename from source/kernel/FileSystem/FAT/FAT16.h rename to source/kernel/filesystem/FAT/FAT16.h diff --git a/source/kernel/Interrupts/idt/idt.cpp b/source/kernel/interrupts/idt/idt.cpp similarity index 99% rename from source/kernel/Interrupts/idt/idt.cpp rename to source/kernel/interrupts/idt/idt.cpp index 8b4fd83..7ee01da 100644 --- a/source/kernel/Interrupts/idt/idt.cpp +++ b/source/kernel/interrupts/idt/idt.cpp @@ -1,6 +1,6 @@ #include "idt.h" -#include "../../Drivers/PIT/pit.h" -#include "../../Drivers/PS-2/keyboard.h" +#include "../../drivers/pit/pit.h" +#include "../../drivers/ps-2/keyboard.h" #include "../../cpu.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; diff --git a/source/kernel/Interrupts/idt/idt.h b/source/kernel/interrupts/idt/idt.h similarity index 94% rename from source/kernel/Interrupts/idt/idt.h rename to source/kernel/interrupts/idt/idt.h index 6ca3399..94e409f 100644 --- a/source/kernel/Interrupts/idt/idt.h +++ b/source/kernel/interrupts/idt/idt.h @@ -2,10 +2,10 @@ #include #include -#include "../../Drivers/VGA/colors.h" -#include "../../Drivers/PIC/pic.h" +#include "../../drivers/vga/colors.h" +#include "../../drivers/pic/pic.h" -#include "../../Terminal/kterm.h" +#include "../../terminal/kterm.h" extern "C" { diff --git a/source/kernel/Interrupts/idt/idt.s b/source/kernel/interrupts/idt/idt.s similarity index 100% rename from source/kernel/Interrupts/idt/idt.s rename to source/kernel/interrupts/idt/idt.s diff --git a/source/kernel/Interrupts/idt/scancodes/set1.h b/source/kernel/interrupts/idt/scancodes/set1.h similarity index 100% rename from source/kernel/Interrupts/idt/scancodes/set1.h rename to source/kernel/interrupts/idt/scancodes/set1.h diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index b66b1ed..6cc3d68 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -1,11 +1,6 @@ #include "kernel.h" extern "C" void early_main() { - /* - * Initialize terminal interface - */ - - kterm_init(); initGDT(); @@ -64,10 +59,11 @@ extern "C" void early_main() printf("MemoryInfoheap size : %d bytes\n", BootInfo->map_size); // Print the memory regions MemoryInfoBlock* currentBlock = (MemoryInfoBlock*) ((uint32_t)BootInfo->MemoryMap + KERNEL_BASE_ADDR) ; - + printf( "Starting address: 0x%x\n", currentBlock); while( (uint32_t)currentBlock->next != 0x0 ) { + printf("CurrentBlock: 0x%x \n", (uint32_t ) currentBlock ); if(IS_AVAILABLE_MEM(currentBlock->type)){ //printf("AVAILABLE RAM\n"); } @@ -91,11 +87,12 @@ extern "C" void early_main() } + printf("Starting physical memory management setup\n"); // Setup PhysicalMemoryManagement SetupPhysicalMemoryManager(BootInfo); } - + printf("Enable Protected mode and jump to kernel main\n"); asm volatile("mov %cr0, %eax "); asm volatile("or $1, %eax"); asm volatile("mov %eax, %cr0"); // re-enable protected mode ? diff --git a/source/kernel/kernel.h b/source/kernel/kernel.h index c335c46..7a955d1 100644 --- a/source/kernel/kernel.h +++ b/source/kernel/kernel.h @@ -1,27 +1,27 @@ #pragma once extern "C" { - #include "Lib/string.h" + #include "lib/string.h" } #include "definitions.h" -#include "Drivers/VGA/VBE.h" -#include "Terminal/kterm.h" +#include "drivers/vga/VBE.h" +#include "terminal/kterm.h" -#include "Memory/PhysicalMemoryManager.h" -#include "Memory/VirtualMemoryManager.h" +#include "memory/PhysicalMemoryManager.h" +#include "memory/VirtualMemoryManager.h" -#include "Memory/GDT/gdtc.h" -#include "Interrupts/idt/idt.h" +#include "memory/gdt/gdtc.h" +#include "interrupts/idt/idt.h" -#include "Drivers/PIT/pit.h" +#include "drivers/pit/pit.h" #include "io.h" #include "cpu.h" #include "serial.h" #include "time.h" -#include "SuperVisorTerminal/superVisorTerminal.h" -#include "PreKernel/bootstructure.h" +#include "supervisorterminal/superVisorTerminal.h" +#include "prekernel/bootstructure.h" #define CHECK_FLAG(flag, bit) ( flag & (1 << bit )) #define PANIC(message) {return;} diff --git a/source/kernel/Lib/mem.h b/source/kernel/lib/mem.h similarity index 100% rename from source/kernel/Lib/mem.h rename to source/kernel/lib/mem.h diff --git a/source/kernel/Lib/string.c b/source/kernel/lib/string.c similarity index 100% rename from source/kernel/Lib/string.c rename to source/kernel/lib/string.c diff --git a/source/kernel/Lib/string.h b/source/kernel/lib/string.h similarity index 100% rename from source/kernel/Lib/string.h rename to source/kernel/lib/string.h diff --git a/source/kernel/Memory/KernelHeap.cpp b/source/kernel/memory/KernelHeap.cpp similarity index 93% rename from source/kernel/Memory/KernelHeap.cpp rename to source/kernel/memory/KernelHeap.cpp index bc5abce..4144947 100644 --- a/source/kernel/Memory/KernelHeap.cpp +++ b/source/kernel/memory/KernelHeap.cpp @@ -14,6 +14,7 @@ void* malloc(size_t size) printf("Received request for %d bytes of memory", size); heap_block* current = start; + // look for a free block while(current < start + heap_size) { if(current->size >= size && current->Used == false ) @@ -33,7 +34,7 @@ void* malloc(size_t size) // If we are here we need more memory so we should // probably ask the VMM for more - // TODO: ask for more memory + // TODO: ask for more memory | Extend kernel heap } diff --git a/source/kernel/Memory/KernelHeap.h b/source/kernel/memory/KernelHeap.h similarity index 100% rename from source/kernel/Memory/KernelHeap.h rename to source/kernel/memory/KernelHeap.h diff --git a/source/kernel/Memory/PhysicalMemoryManager.cpp b/source/kernel/memory/PhysicalMemoryManager.cpp similarity index 84% rename from source/kernel/Memory/PhysicalMemoryManager.cpp rename to source/kernel/memory/PhysicalMemoryManager.cpp index bda801c..90af1ac 100644 --- a/source/kernel/Memory/PhysicalMemoryManager.cpp +++ b/source/kernel/memory/PhysicalMemoryManager.cpp @@ -1,29 +1,33 @@ #include "./PhysicalMemoryManager.h" PhysicalMemoryManagerInfoBlock* PMMInfoBlock; +extern uint32_t* boot_page_directory; +extern uint32_t* boot_page_table; const uint32_t KERNEL_OFFSET = 0xC0000000; void SetupPhysicalMemoryManager( BootInfoBlock* Bootinfo) { - - PMMInfoBlock = (PhysicalMemoryManagerInfoBlock*) ((uint32_t)MemoryMapHeap_pptr + Bootinfo->map_size + 0xC0000000); - + // NOTE: Physical memory map will override the boot info for now! + PMMInfoBlock = (PhysicalMemoryManagerInfoBlock*) (&BootInfoBlock_pptr + KERNEL_OFFSET ); + printf("Setting up physical memory infoblock (0x%x) \n", (uint32_t)&PMMInfoBlock); /* Every byte contains 8 pages A page is 4096 kib Every block (1 bit) represent an page */ - // calculate the maximum number of blocks - PMMInfoBlock->max_blocks =Bootinfo->MemorySize / BLOCK_SIZE / 8; - PMMInfoBlock->used_blocks = 0; + // Calculate the maximum number of blocks + printf("Maxblocks at address(0x%x)\n" , (uint32_t)&(PMMInfoBlock->max_blocks)); + + int maximum_blocks = (uint32_t)Bootinfo->MemorySize / BLOCK_SIZE / 8; + printf("Set bitmap block maximum: %d\n", maximum_blocks); + PMMInfoBlock->max_blocks = maximum_blocks; + + printf("Set used blocks to zero\n"); + PMMInfoBlock->used_blocks = 0; + + printf("Determine memory bit map address"); // put the map after the gdt PMMInfoBlock->memoryBitMap = (uint32_t*) ( 0xC010b100) ; - - // // Page in the address space please - // uint32_t PDEI = 0xC020a000 >> 22; - // uint32_t PTEI = (0xC020a000 >> 12) & 0x1FFF; - // printf("PDEI: %d, PTEI: %d\n", PDEI, PTEI); - printf("Maximum num blocks: %d \n",PMMInfoBlock->max_blocks); //Size of memory map @@ -54,7 +58,7 @@ void SetupPhysicalMemoryManager( BootInfoBlock* Bootinfo) { printf("kernel size in memory: 0x%x\n", kernel_size); allocate_region((uint32_t)&kernel_begin, kernel_size); - printf("allocate BIOS region"); + printf("allocate BIOS region\n"); allocate_region (0x0000000, 0x00100000); } diff --git a/source/kernel/Memory/PhysicalMemoryManager.h b/source/kernel/memory/PhysicalMemoryManager.h similarity index 78% rename from source/kernel/Memory/PhysicalMemoryManager.h rename to source/kernel/memory/PhysicalMemoryManager.h index 1122b25..f51c329 100644 --- a/source/kernel/Memory/PhysicalMemoryManager.h +++ b/source/kernel/memory/PhysicalMemoryManager.h @@ -1,8 +1,8 @@ #pragma once #include -#include "../PreKernel/bootstructure.h" -#include "../Terminal/kterm.h" -#include "../Lib/mem.h" +#include "../prekernel/bootstructure.h" +#include "../terminal/kterm.h" +#include "../lib/mem.h" #include "../bitmap.h" // Asumming i386 for now! @@ -14,8 +14,8 @@ struct PhysicalMemoryManagerInfoBlock { uint32_t* memoryBitMap; - size_t pmmap_size; - size_t max_blocks; + uint32_t pmmap_size; + uint32_t max_blocks; int used_blocks; }; diff --git a/source/kernel/memory/VirtualMemoryManager.cpp b/source/kernel/memory/VirtualMemoryManager.cpp new file mode 100644 index 0000000..a01f8d0 --- /dev/null +++ b/source/kernel/memory/VirtualMemoryManager.cpp @@ -0,0 +1,73 @@ +#include "VirtualMemoryManager.h" +extern uint32_t boot_page_directory[1024] ; +extern uint32_t boot_page_table[1024]; +void AllocatePage(uint32_t vaddr) +{ + uint32_t page_aligned_address = ALIGN(vaddr, 4096); + + // allocate a page at virtual address + int PageDirectoryEntryIndex = vaddr >> 22; + int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; + + printf("Allocation happening at PDE: %d PTE: %d\n", PageDirectoryEntryIndex, PageTableEntryIndex); + + // check if the page directory entry is marked as present + if (boot_page_directory[PageDirectoryEntryIndex] & 0x1 ) { + + uint32_t* page_table = (uint32_t*)((boot_page_directory[PageDirectoryEntryIndex]) & 0xFFFFE000 + 0xC0000000); + + // check if the page table entry is marked as present + if ( page_table[PageTableEntryIndex] & 0x1 ) + { + // Map the entry to a physical page + page_table[PageTableEntryIndex] = (uint32_t)(allocate_block() + 0x3); + } else{ + // mark page as present + page_table[PageTableEntryIndex] = 0x3; + } + + } else { + // mark the page table as present and allocate a physical block for it + boot_page_directory[PageDirectoryEntryIndex] = (uint32_t)(allocate_block() + 0x3); + } + + +} + +void FreePage(uint32_t vaddr ) +{ + uint32_t page_aligned_address = ALIGN(vaddr, 4096); + + // allocate a page at virtual address + int PageDirectoryEntryIndex = vaddr >> 22; + int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; + + uint32_t* pageTable = (uint32_t*)(boot_page_directory[PageDirectoryEntryIndex] & 0xFFFFE000 + 0xC0000000); + + + void* physicalAddressToFree = (void*)(pageTable[PageTableEntryIndex] & 0xFFFFE000 + 0xC0000000); + free_block(physicalAddressToFree); + + pageTable[PageTableEntryIndex] = 0x0; + + +} + +void Map ( uint32_t vaddr, uint32_t paddr) +{ + uint32_t page_aligned_address = ALIGN(vaddr, 4096); + + // allocate a page at virtual address + int PageDirectoryEntryIndex = vaddr >> 22; + int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; +} + +void Unmap(uint32_t vaddr) +{ + // NOTE: I will implement lazy unmapping for now + uint32_t page_aligned_address = ALIGN(vaddr, 4096); + + // allocate a page at virtual address + int PageDirectoryEntryIndex = vaddr >> 22; + int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; +} diff --git a/source/kernel/Memory/VirtualMemoryManager.h b/source/kernel/memory/VirtualMemoryManager.h similarity index 87% rename from source/kernel/Memory/VirtualMemoryManager.h rename to source/kernel/memory/VirtualMemoryManager.h index 69e146e..e54e3ed 100644 --- a/source/kernel/Memory/VirtualMemoryManager.h +++ b/source/kernel/memory/VirtualMemoryManager.h @@ -1,6 +1,6 @@ #pragma once #include "PhysicalMemoryManager.h" -#include "../Terminal/kterm.h" +#include "../terminal/kterm.h" #include "../cpu.h" void AllocatePage(uint32_t v_addr ); diff --git a/source/kernel/Memory/GDT/gdt.s b/source/kernel/memory/gdt/gdt.s similarity index 100% rename from source/kernel/Memory/GDT/gdt.s rename to source/kernel/memory/gdt/gdt.s diff --git a/source/kernel/Memory/GDT/gdtc.cpp b/source/kernel/memory/gdt/gdtc.cpp similarity index 97% rename from source/kernel/Memory/GDT/gdtc.cpp rename to source/kernel/memory/gdt/gdtc.cpp index bd10a08..32b8ea3 100644 --- a/source/kernel/Memory/GDT/gdtc.cpp +++ b/source/kernel/memory/gdt/gdtc.cpp @@ -1,5 +1,5 @@ #include "gdtc.h" -#include "../../Terminal/kterm.h" +#include "../../terminal/kterm.h" #define NULL_SEGMENT 0 #define KERNEL_CODE_SEGMENT 1 diff --git a/source/kernel/Memory/GDT/gdtc.h b/source/kernel/memory/gdt/gdtc.h similarity index 100% rename from source/kernel/Memory/GDT/gdtc.h rename to source/kernel/memory/gdt/gdtc.h diff --git a/source/kernel/PreKernel/bootstructure.h b/source/kernel/prekernel/bootstructure.h similarity index 100% rename from source/kernel/PreKernel/bootstructure.h rename to source/kernel/prekernel/bootstructure.h diff --git a/source/kernel/PreKernel/multiboot.h b/source/kernel/prekernel/multiboot.h similarity index 100% rename from source/kernel/PreKernel/multiboot.h rename to source/kernel/prekernel/multiboot.h diff --git a/source/kernel/PreKernel/prekernel.cpp b/source/kernel/prekernel/prekernel.cpp similarity index 99% rename from source/kernel/PreKernel/prekernel.cpp rename to source/kernel/prekernel/prekernel.cpp index 479af04..5a28801 100644 --- a/source/kernel/PreKernel/prekernel.cpp +++ b/source/kernel/prekernel/prekernel.cpp @@ -16,6 +16,7 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) { if (magic != MULTIBOOT_BOOTLOADER_MAGIC) { BIB->MapIsInvalid = true; + // crash return; } else{ BIB->MapIsInvalid = false; diff --git a/source/kernel/serial.h b/source/kernel/serial.h index 343184b..b17afd8 100644 --- a/source/kernel/serial.h +++ b/source/kernel/serial.h @@ -1,6 +1,6 @@ #pragma once -#include "Terminal/kterm.h" +#include "terminal/kterm.h" #include "io.h" #define PORT 0x3f8 static int init_serial() { diff --git a/source/kernel/SuperVisorTerminal/superVisorTerminal.cpp b/source/kernel/supervisorterminal/superVisorTerminal.cpp similarity index 100% rename from source/kernel/SuperVisorTerminal/superVisorTerminal.cpp rename to source/kernel/supervisorterminal/superVisorTerminal.cpp diff --git a/source/kernel/supervisorterminal/superVisorTerminal.h b/source/kernel/supervisorterminal/superVisorTerminal.h new file mode 100644 index 0000000..f262ea3 --- /dev/null +++ b/source/kernel/supervisorterminal/superVisorTerminal.h @@ -0,0 +1,8 @@ +#pragma once +#include "../terminal/kterm.h" +#include "../time.h" +#include "../drivers/pit/pit.h" +#include "../drivers/ps-2/keyboard.h" +#include "../memory/PhysicalMemoryManager.h" + +void startSuperVisorTerminal(); \ No newline at end of file diff --git a/source/kernel/Terminal/kterm.cpp b/source/kernel/terminal/kterm.cpp similarity index 100% rename from source/kernel/Terminal/kterm.cpp rename to source/kernel/terminal/kterm.cpp diff --git a/source/kernel/Terminal/kterm.h b/source/kernel/terminal/kterm.h similarity index 93% rename from source/kernel/Terminal/kterm.h rename to source/kernel/terminal/kterm.h index 915c08a..c016549 100644 --- a/source/kernel/Terminal/kterm.h +++ b/source/kernel/terminal/kterm.h @@ -3,11 +3,11 @@ #include #include -#include "../Drivers/VGA/colors.h" +#include "../drivers/vga/colors.h" #include "../io.h" extern "C"{ - #include "../Lib/string.h" + #include "../lib/string.h" } void kterm_init(); -- 2.39.5 From 01fcb0aa15aa88e76743f9086656e9598cade992 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 2 Sep 2022 21:09:51 +0200 Subject: [PATCH 078/115] KERNEL: Improved Physical memory allocation code / Code refactor * Moved tests to a different folder * Adjusted the memory map address locations * Improved readability of `kernel.cpp` --- Makefile | 35 ++-- .../kernel-test/PhysicalMemoryManagerTest.cpp | 15 ++ source/kernel/boot/boot.s | 2 +- source/kernel/kernel.cpp | 185 ++++++++---------- source/kernel/kernel.h | 38 ---- source/kernel/lib/{string.c => string.cpp} | 0 source/kernel/memory/KernelHeap.cpp | 9 +- source/kernel/memory/KernelHeap.h | 3 +- .../kernel/memory/PhysicalMemoryManager.cpp | 45 ++--- source/kernel/memory/VirtualMemoryManager.cpp | 4 + source/kernel/prekernel/bootstructure.h | 7 +- source/kernel/prekernel/prekernel.cpp | 3 +- .../supervisorterminal/superVisorTerminal.h | 1 + source/kernel/terminal/kterm.h | 13 +- 14 files changed, 158 insertions(+), 202 deletions(-) create mode 100644 source/kernel-test/PhysicalMemoryManagerTest.cpp delete mode 100644 source/kernel/kernel.h rename source/kernel/lib/{string.c => string.cpp} (100%) diff --git a/Makefile b/Makefile index 3f64c5a..9d78640 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o SRC_DIR = source BUILD_DIR = build @@ -51,24 +51,15 @@ build_x86_64: clean: rm -f $(BUILD_DIR)/myos.bin $(INTERNAL_OBJS) +# C++ definition -> Object files $(BUILD_DIR)/kernel.o: $(CPP) -c $(SRC_DIR)/kernel/kernel.cpp -o $(BUILD_DIR)/kernel.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/kterm.o: $(CPP) -c $(SRC_DIR)/kernel/terminal/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti -$(BUILD_DIR)/boot.o: - $(AS) $(SRC_DIR)/kernel/boot/boot.s -o $(BUILD_DIR)/boot.o - -$(BUILD_DIR)/crti.o: - $(AS) $(SRC_DIR)/kernel/crti.s -o $(BUILD_DIR)/crti.o - -$(BUILD_DIR)/crtn.o: - $(AS) $(SRC_DIR)/kernel/crtn.s -o $(BUILD_DIR)/crtn.o - $(BUILD_DIR)/io.o: - $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti - + $(CPP) -c $(SRC_DIR)/kernel/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/idt.o: $(CPP) -c $(SRC_DIR)/kernel/interrupts/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -76,22 +67,18 @@ $(BUILD_DIR)/idt.o: $(BUILD_DIR)/gdtc.o: $(CPP) -c $(SRC_DIR)/kernel/memory/gdt/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti - $(BUILD_DIR)/pic.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/string.o: - $(CC) -c $(SRC_DIR)/kernel/lib/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 - + $(CPP) -c $(SRC_DIR)/kernel/lib/string.cpp -o $(BUILD_DIR)/string.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pit.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/pit/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti - $(BUILD_DIR)/keyboard.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/ps-2/keyboard.cpp -o $(BUILD_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti - $(BUILD_DIR)/time.o: $(CPP) -c $(SRC_DIR)/kernel/time.cpp -o $(BUILD_DIR)/time.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -104,8 +91,22 @@ $(BUILD_DIR)/memory.o: $(BUILD_DIR)/paging.o: $(CPP) -c $(SRC_DIR)/kernel/memory/VirtualMemoryManager.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti +$(BUILD_DIR)/KHeap.o: + $(CPP) -c $(SRC_DIR)/kernel/memory/KernelHeap.cpp -o $(BUILD_DIR)/KHeap.o $(CFLAGS) -fno-exceptions -fno-rtti + $(BUILD_DIR)/prekernel.o: $(CPP) -c $(SRC_DIR)/kernel/prekernel/prekernel.cpp -o $(BUILD_DIR)/prekernel.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/cpu.o: $(CPP) -c $(SRC_DIR)/kernel/cpu.cpp -o $(BUILD_DIR)/cpu.o $(CFLAGS) -fno-exceptions -fno-rtti + + +# Assembly -> Object files +$(BUILD_DIR)/boot.o: + $(AS) $(SRC_DIR)/kernel/boot/boot.s -o $(BUILD_DIR)/boot.o + +$(BUILD_DIR)/crti.o: + $(AS) $(SRC_DIR)/kernel/crti.s -o $(BUILD_DIR)/crti.o + +$(BUILD_DIR)/crtn.o: + $(AS) $(SRC_DIR)/kernel/crtn.s -o $(BUILD_DIR)/crtn.o diff --git a/source/kernel-test/PhysicalMemoryManagerTest.cpp b/source/kernel-test/PhysicalMemoryManagerTest.cpp new file mode 100644 index 0000000..30243df --- /dev/null +++ b/source/kernel-test/PhysicalMemoryManagerTest.cpp @@ -0,0 +1,15 @@ + +void PhysicalMemoryAllocatorTest() +{ + #ifdef UNIT_TESTS + // Small test! + void* block = allocate_block(); + void* block2 = allocate_block(); + printf("Allocated addresss 1: 0x%x 2: 0x%x\n", (uint32_t)block ,(uint32_t)block2); + free_block(block); + free_block(block2); + void* block3 = allocate_block(); + printf("Allocated addresss 3: 0x%x\n", (uint32_t)block3); + free_block(block3); + #endif +} \ No newline at end of file diff --git a/source/kernel/boot/boot.s b/source/kernel/boot/boot.s index 21a1bb8..5469538 100644 --- a/source/kernel/boot/boot.s +++ b/source/kernel/boot/boot.s @@ -83,7 +83,7 @@ _start: # At this point, paging is fully set up and enabled isPaging: # Unmap the identity mapping as it is now unnecessary - movl $0, boot_page_directory + 0 + //movl $0, boot_page_directory + 0 # Reload cr3 to force tlb flush movl %cr3, %ecx diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 6cc3d68..073223e 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -1,122 +1,107 @@ -#include "kernel.h" -extern "C" void early_main() +#include "lib/string.h" +#include "definitions.h" + +#include "prekernel/bootstructure.h" + +#include "drivers/vga/VBE.h" +#include "drivers/pit/pit.h" + +#include "memory/PhysicalMemoryManager.h" +#include "memory/VirtualMemoryManager.h" +#include "memory/KernelHeap.h" +#include "memory/gdt/gdtc.h" + +#include "interrupts/idt/idt.h" + +#include "io.h" +#include "cpu.h" +#include "serial.h" +#include "time.h" + +#include "terminal/kterm.h" + +#include "supervisorterminal/superVisorTerminal.h" + +extern "C" void kernel_main (); +void ProcessBootInfo(); + +extern "C" void kernel_main () { - kterm_init(); - initGDT(); - - - init_serial(); - print_serial("Hello Higher half kernel!\n"); - - init_idt(); - // Enable interrupts - asm volatile("STI"); - /* * Show a little banner for cuteness */ printf("|=== BarinkOS ===|\n"); - printf("Kernel End Addr: 0x%x\n" , &kernel_end ); - - uint32_t PageDirectoryEntryIndex = ((uint32_t)&kernel_end + KERNEL_BASE_ADDR ) >> 22 ; - - uint32_t PageTableEntryIndex = (((uint32_t)&kernel_end + KERNEL_BASE_ADDR) >> 12) & 0x1FFF; - - printf("Kernel End PDE: %d, PTE: %d\n" , PageDirectoryEntryIndex, PageTableEntryIndex); - - uint32_t BootInfoStruct = BootInfoBlock_pptr + 0xC0000000; - printf("Addr BootInfostruct: 0x%x\n", BootInfoStruct); - - uint32_t PageDirectoryEntryIndex2 = (BootInfoStruct ) >> 2 ; - - uint32_t PageTableEntryIndex2 = (BootInfoStruct >> 12) & 0x1FFF; - - printf("PDE: 0x%x, PTE: 0x%x\n", PageDirectoryEntryIndex2 , PageTableEntryIndex2 ); - - BootInfoBlock* BootInfo = (BootInfoBlock*) ( BootInfoBlock_pptr + 0xC0000000 ); + startSuperVisorTerminal(); +} - printf("Size of BootInfoBlock: %d bytes\n", sizeof(BootInfoBlock)); - printf("Bootloader information:\n"); - if( BootInfo->ValidELFHeader ) - { - printf("- Valid ELF Header is available!\n"); - } +extern "C" void early_main() +{ + init_serial(); + print_serial("Hello Higher half kernel!\n"); + kterm_init(); + initGDT(); + init_idt(); + // Enable interrupts + asm volatile("STI"); + + ProcessBootInfo(); - if(BootInfo->EnabledVBE) - { - printf("- VBE graphics mode is available!\n"); - } + initHeap(); - if(BootInfo->ValidSymbolTable) - { - printf("- Valid Symbol Table available at 0x%x.\n Tab Size: %d, str Size: %d\n", BootInfo->SymbolTableAddr, BootInfo->SymbolTabSize, BootInfo->SymbolStrSize); - } + // test heap allocation + /* + struct KernelInfo { + int bar; + bool foo; + }; - if(BootInfo->PhysicalMemoryMapAvailable) - { - printf("- Physical Memory Map available!\n"); - printf("MemoryInfoheap size : %d bytes\n", BootInfo->map_size); - // Print the memory regions - MemoryInfoBlock* currentBlock = (MemoryInfoBlock*) ((uint32_t)BootInfo->MemoryMap + KERNEL_BASE_ADDR) ; + KernelInfo* MyInfo = (KernelInfo*) malloc(sizeof(KernelInfo)); - printf( "Starting address: 0x%x\n", currentBlock); - while( (uint32_t)currentBlock->next != 0x0 ) - { - printf("CurrentBlock: 0x%x \n", (uint32_t ) currentBlock ); - if(IS_AVAILABLE_MEM(currentBlock->type)){ - //printf("AVAILABLE RAM\n"); - } - else if(IS_ACPI_MEM(currentBlock->type)){ - //printf("ACPI MEMORY\n"); - } - else if(IS_RESERVED_MEM(currentBlock->type)){ - // printf("RESERVED MEMORY\n"); - } - else if(IS_NVS_MEMORY(currentBlock->type)){ - // printf("NVS MEMORY \n"); - } - else if(IS_BADRAM_MEMORY(currentBlock->type)){ - // printf("BADRAM MEMORY \n"); - } - else { - // printf("(TYPE 0x%x )TYPE NOT SPECIFIED\n", currentBlock->type); - } + MyInfo->bar = 6; + MyInfo->foo = false; - currentBlock = (MemoryInfoBlock*) ((uint32_t)currentBlock->next + KERNEL_BASE_ADDR ); - - } + free(MyInfo); + */ - printf("Starting physical memory management setup\n"); - // Setup PhysicalMemoryManagement - SetupPhysicalMemoryManager(BootInfo); - - } printf("Enable Protected mode and jump to kernel main\n"); + asm volatile("mov %cr0, %eax "); asm volatile("or $1, %eax"); asm volatile("mov %eax, %cr0"); // re-enable protected mode ? + + pit_initialise(); + + kernel_main(); } -void PhysicalMemoryAllocatorTest(){ - #ifdef UNIT_TESTS - // Small test! - void* block = allocate_block(); - void* block2 = allocate_block(); - printf("Allocated addresss 1: 0x%x 2: 0x%x\n", (uint32_t)block ,(uint32_t)block2); - free_block(block); - free_block(block2); - void* block3 = allocate_block(); - printf("Allocated addresss 3: 0x%x\n", (uint32_t)block3); - free_block(block3); - #endif +void ProcessBootInfo(){ + uint32_t BootInfoStruct = BootInfoBlock_pptr + 0xC0000000; + BootInfoBlock* BootInfo = (BootInfoBlock*) ( BootInfoBlock_pptr + 0xC0000000 ); + + if( BootInfo->ValidELFHeader ) + { + // NOTE: Do something with it.. (Store it , process it etc...) + } + + if(BootInfo->EnabledVBE) + { + // NOTE: Do something with it.. (Store it , process it etc...) + } + + if(BootInfo->ValidSymbolTable) + { + // NOTE: Do something with it.. (Store it , process it etc...) + // printf("- Valid Symbol Table available at 0x%x.\n Tab Size: %d, str Size: %d\n", BootInfo->SymbolTableAddr, BootInfo->SymbolTabSize, BootInfo->SymbolStrSize); + } + + if(BootInfo->PhysicalMemoryMapAvailable) + { + + + SetupPhysicalMemoryManager(BootInfo); + } + } - - -extern "C" void kernel_main () { - pit_initialise(); - - startSuperVisorTerminal(); -} \ No newline at end of file diff --git a/source/kernel/kernel.h b/source/kernel/kernel.h deleted file mode 100644 index 7a955d1..0000000 --- a/source/kernel/kernel.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once -extern "C" -{ - #include "lib/string.h" -} -#include "definitions.h" - -#include "drivers/vga/VBE.h" -#include "terminal/kterm.h" - -#include "memory/PhysicalMemoryManager.h" -#include "memory/VirtualMemoryManager.h" - -#include "memory/gdt/gdtc.h" -#include "interrupts/idt/idt.h" - -#include "drivers/pit/pit.h" -#include "io.h" -#include "cpu.h" -#include "serial.h" - -#include "time.h" -#include "supervisorterminal/superVisorTerminal.h" -#include "prekernel/bootstructure.h" - -#define CHECK_FLAG(flag, bit) ( flag & (1 << bit )) -#define PANIC(message) {return;} - -void map_multiboot_info_structure(unsigned long addr); - -extern "C" void kernel_main (); - - -extern "C" uint32_t boot_page_directory; -extern "C" uint32_t multiboot_page_table; - - -const uint32_t KERNEL_BASE_ADDR = 0xC0000000; \ No newline at end of file diff --git a/source/kernel/lib/string.c b/source/kernel/lib/string.cpp similarity index 100% rename from source/kernel/lib/string.c rename to source/kernel/lib/string.cpp diff --git a/source/kernel/memory/KernelHeap.cpp b/source/kernel/memory/KernelHeap.cpp index 4144947..0aff6d3 100644 --- a/source/kernel/memory/KernelHeap.cpp +++ b/source/kernel/memory/KernelHeap.cpp @@ -4,7 +4,7 @@ struct heap_block{ uint8_t Used; uint32_t Size; -} +}; uint32_t heap_size; heap_block* start ; @@ -17,7 +17,7 @@ void* malloc(size_t size) // look for a free block while(current < start + heap_size) { - if(current->size >= size && current->Used == false ) + if(current->Size >= size && current->Used == false ) { // We found a spot // Set the spot to in-use @@ -42,11 +42,12 @@ void free(void* addr) { // clear the free boolean that corresponds to this adddress // This should be fairly simple - heap_block* allocatedBlock = addr - sizeof(heap_block); - allocate_block->Used = false; + heap_block* allocatedBlock = (heap_block*)(addr - sizeof(heap_block)); + allocatedBlock->Used = false; } void initHeap() { + // NOTE: What to do now?? } \ No newline at end of file diff --git a/source/kernel/memory/KernelHeap.h b/source/kernel/memory/KernelHeap.h index e38110b..c6f87af 100644 --- a/source/kernel/memory/KernelHeap.h +++ b/source/kernel/memory/KernelHeap.h @@ -1,6 +1,7 @@ #pragma once +#include #include - +#include "../terminal/kterm.h" void initHeap(); diff --git a/source/kernel/memory/PhysicalMemoryManager.cpp b/source/kernel/memory/PhysicalMemoryManager.cpp index 90af1ac..c16d33e 100644 --- a/source/kernel/memory/PhysicalMemoryManager.cpp +++ b/source/kernel/memory/PhysicalMemoryManager.cpp @@ -1,14 +1,17 @@ #include "./PhysicalMemoryManager.h" -PhysicalMemoryManagerInfoBlock* PMMInfoBlock; +const uint32_t KERNEL_OFFSET = 0xC0000000; extern uint32_t* boot_page_directory; extern uint32_t* boot_page_table; +extern uint32_t* multiboot_page_table; -const uint32_t KERNEL_OFFSET = 0xC0000000; -void SetupPhysicalMemoryManager( BootInfoBlock* Bootinfo) { - // NOTE: Physical memory map will override the boot info for now! - PMMInfoBlock = (PhysicalMemoryManagerInfoBlock*) (&BootInfoBlock_pptr + KERNEL_OFFSET ); - printf("Setting up physical memory infoblock (0x%x) \n", (uint32_t)&PMMInfoBlock); +PhysicalMemoryManagerInfoBlock* PMMInfoBlock; + +void SetupPhysicalMemoryManager( BootInfoBlock* Bootinfo) +{ + + // NOTE: We should move our bitmap to just after the end of our kernel instead + PMMInfoBlock = (PhysicalMemoryManagerInfoBlock*) ( ((uint32_t)MemoryMapHeap_pptr + 80 ) + KERNEL_OFFSET ); /* Every byte contains 8 pages A page is 4096 kib @@ -16,41 +19,33 @@ void SetupPhysicalMemoryManager( BootInfoBlock* Bootinfo) { */ // Calculate the maximum number of blocks - printf("Maxblocks at address(0x%x)\n" , (uint32_t)&(PMMInfoBlock->max_blocks)); - int maximum_blocks = (uint32_t)Bootinfo->MemorySize / BLOCK_SIZE / 8; - printf("Set bitmap block maximum: %d\n", maximum_blocks); PMMInfoBlock->max_blocks = maximum_blocks; - - printf("Set used blocks to zero\n"); PMMInfoBlock->used_blocks = 0; - printf("Determine memory bit map address"); // put the map after the gdt PMMInfoBlock->memoryBitMap = (uint32_t*) ( 0xC010b100) ; - printf("Maximum num blocks: %d \n",PMMInfoBlock->max_blocks); //Size of memory map uint32_t memMap_size = PMMInfoBlock->max_blocks / 8; - printf("Memory map size: %d\n", memMap_size); - printf("Address of memory map 0x%x\n", PMMInfoBlock->memoryBitMap); // Set all places in memory as free memset(PMMInfoBlock->memoryBitMap, 0xFF, memMap_size ); + MemoryInfoBlock* currentBlock = (MemoryInfoBlock*) ((uint32_t)Bootinfo->MemoryMap + 0xC0000000) ; - // Loop over memory map and allocate physical locations - // that are already in use - MemoryInfoBlock* currentBlock = (MemoryInfoBlock*) ((uint32_t)Bootinfo->MemoryMap + KERNEL_OFFSET) ; - printf("Starting address: 0x%x\n", currentBlock); - while( (uint32_t) currentBlock->next != 0x0) + printf( "Starting address: 0x%x\n", currentBlock); + while( (uint32_t)currentBlock->next != 0x0 ) { + if(IS_AVAILABLE_MEM(currentBlock->type)){ - printf("skip!\n"); - } else { - printf("allocate region 0x%x of size 0x%x\n" , currentBlock->Base_addr, currentBlock->Memory_Size); - allocate_region((uint32_t) currentBlock->Base_addr, currentBlock->Memory_Size); + printf("skip!\n"); + } + else{ + printf("allocate region 0x%x of size %d bytes\n", currentBlock->Base_addr, currentBlock->Memory_Size); + // allocate_region( currentBlock->Base_addr, currentBlock->Memory_Size); // allocate region causes #PF Exception } - currentBlock = (MemoryInfoBlock*) ((uint32_t)currentBlock->next + KERNEL_OFFSET ); + currentBlock = (MemoryInfoBlock*) ((uint32_t)currentBlock->next + 0xC0000000 ); + } uint32_t kernel_size = ((uint32_t)&kernel_end - (uint32_t)&kernel_begin ) - KERNEL_OFFSET; diff --git a/source/kernel/memory/VirtualMemoryManager.cpp b/source/kernel/memory/VirtualMemoryManager.cpp index a01f8d0..813d52b 100644 --- a/source/kernel/memory/VirtualMemoryManager.cpp +++ b/source/kernel/memory/VirtualMemoryManager.cpp @@ -1,6 +1,9 @@ #include "VirtualMemoryManager.h" + extern uint32_t boot_page_directory[1024] ; extern uint32_t boot_page_table[1024]; + + void AllocatePage(uint32_t vaddr) { uint32_t page_aligned_address = ALIGN(vaddr, 4096); @@ -60,6 +63,7 @@ void Map ( uint32_t vaddr, uint32_t paddr) // allocate a page at virtual address int PageDirectoryEntryIndex = vaddr >> 22; int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; + } void Unmap(uint32_t vaddr) diff --git a/source/kernel/prekernel/bootstructure.h b/source/kernel/prekernel/bootstructure.h index 78f4580..51f8ce0 100644 --- a/source/kernel/prekernel/bootstructure.h +++ b/source/kernel/prekernel/bootstructure.h @@ -40,6 +40,7 @@ struct BootInfoBlock { }; -// TODO Put the BootInfoBlock 1MB above the kernel. -const uint32_t BootInfoBlock_pptr = (uint32_t)&kernel_end - 0xC0000000 + 0x1; -const uint32_t MemoryMapHeap_pptr = BootInfoBlock_pptr + sizeof(BootInfoBlock); + +const uint32_t pke = ((uint32_t)&kernel_end) - 0xC0000000; +const uint32_t BootInfoBlock_pptr = pke + 1000 - sizeof(BootInfoBlock); +const uint32_t MemoryMapHeap_pptr = pke + 0x1; diff --git a/source/kernel/prekernel/prekernel.cpp b/source/kernel/prekernel/prekernel.cpp index 5a28801..156201c 100644 --- a/source/kernel/prekernel/prekernel.cpp +++ b/source/kernel/prekernel/prekernel.cpp @@ -99,9 +99,8 @@ if (CHECK_FLAG(mbi->flags, 6)) // continue to the next block mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size)); - CurrentInfoBlock->next = (MemoryInfoBlock*) ((uint32_t)CurrentInfoBlock) + sizeof(MemoryInfoBlock); + CurrentInfoBlock->next = (MemoryInfoBlock*) CurrentInfoBlock + 16; CurrentInfoBlock = CurrentInfoBlock->next; - } CurrentInfoBlock->next = (MemoryInfoBlock*) 0x0; diff --git a/source/kernel/supervisorterminal/superVisorTerminal.h b/source/kernel/supervisorterminal/superVisorTerminal.h index f262ea3..796f6ac 100644 --- a/source/kernel/supervisorterminal/superVisorTerminal.h +++ b/source/kernel/supervisorterminal/superVisorTerminal.h @@ -4,5 +4,6 @@ #include "../drivers/pit/pit.h" #include "../drivers/ps-2/keyboard.h" #include "../memory/PhysicalMemoryManager.h" +#include "../lib/string.h" void startSuperVisorTerminal(); \ No newline at end of file diff --git a/source/kernel/terminal/kterm.h b/source/kernel/terminal/kterm.h index c016549..1d63389 100644 --- a/source/kernel/terminal/kterm.h +++ b/source/kernel/terminal/kterm.h @@ -6,9 +6,8 @@ #include "../drivers/vga/colors.h" #include "../io.h" -extern "C"{ - #include "../lib/string.h" -} +#include "../lib/string.h" + void kterm_init(); @@ -35,11 +34,3 @@ int get_cursor_y (uint16_t cursor_pos); void printf ( const char *format, ...); -//static void itoa (char *buf, int base, int d); - -#define KernelTag "[Kernel]: " -#define AS_KERNEL() ( kterm_setcolor(VGA_COLOR_LIGHT_BLUE),\ - kterm_write(KernelTag, 10 ), \ - kterm_resetcolor()) - - -- 2.39.5 From 656ca0baa82c7be3e0d16d136fe53caa88273050 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 3 Sep 2022 01:00:17 +0200 Subject: [PATCH 079/115] KERNEL: Pre-kernel sets up the physical memory manager. * BUG: allocated blocks is possibly incorrect! * prekernel no longer gets compiled as being in physical memory --- source/kernel/bitmap.h | 2 - source/kernel/boot/boot.s | 19 +- source/kernel/kernel.cpp | 37 +-- source/kernel/linker.ld | 6 +- .../kernel/memory/PhysicalMemoryManager.cpp | 98 +++---- source/kernel/memory/PhysicalMemoryManager.h | 22 +- source/kernel/memory/VirtualMemoryManager.cpp | 2 +- source/kernel/prekernel/bootstructure.h | 5 - source/kernel/prekernel/prekernel.cpp | 239 ++++++++++-------- 9 files changed, 193 insertions(+), 237 deletions(-) diff --git a/source/kernel/bitmap.h b/source/kernel/bitmap.h index 165266c..fd80075 100644 --- a/source/kernel/bitmap.h +++ b/source/kernel/bitmap.h @@ -2,7 +2,6 @@ #include #include - inline void bitmap_set( uint32_t* map , int index ) { map[index/32] |= (1 << (index % 32)); @@ -24,7 +23,6 @@ inline uint32_t bitmap_first_unset( uint32_t* map , int map_size) for(int j = 0 ; j < 32 ; j++){ if ( (map[i] & (0x00000001 << j)) > 0) { - printf("Found bit: byte 0x%x , bit 0x%x\n", i , j); return (i*32)+j; } } diff --git a/source/kernel/boot/boot.s b/source/kernel/boot/boot.s index 5469538..cbfb2ce 100644 --- a/source/kernel/boot/boot.s +++ b/source/kernel/boot/boot.s @@ -27,17 +27,10 @@ multiboot_page_table: # Entry point .section .multiboot.text, "a" -.global _start +.globl _start .type _start, @function _start: - /* push the pointer to the Multiboot information structure*/ - pushl %ebx - - /* push the magic value */ - pushl %eax - call prekernelSetup - # Get physical address of the boot_page_table movl $(boot_page_table - 0xC0000000), %edi # Map address 0 @@ -82,8 +75,15 @@ _start: 4: # At this point, paging is fully set up and enabled isPaging: + /* push the pointer to the Multiboot information structure*/ + pushl %ebx + + /* push the magic value */ + pushl %eax + call prekernelSetup + # Unmap the identity mapping as it is now unnecessary - //movl $0, boot_page_directory + 0 + movl $0, boot_page_directory + 0 # Reload cr3 to force tlb flush movl %cr3, %ecx @@ -97,6 +97,7 @@ isPaging: pushl $0 popf + call early_main cli diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 073223e..6f932a1 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -39,13 +39,17 @@ extern "C" void early_main() { init_serial(); print_serial("Hello Higher half kernel!\n"); + kterm_init(); + + printf("Allocated blocks: %d \n", GetUsedBlocks()); + initGDT(); init_idt(); + // Enable interrupts asm volatile("STI"); - ProcessBootInfo(); initHeap(); @@ -75,33 +79,4 @@ extern "C" void early_main() kernel_main(); -} - -void ProcessBootInfo(){ - uint32_t BootInfoStruct = BootInfoBlock_pptr + 0xC0000000; - BootInfoBlock* BootInfo = (BootInfoBlock*) ( BootInfoBlock_pptr + 0xC0000000 ); - - if( BootInfo->ValidELFHeader ) - { - // NOTE: Do something with it.. (Store it , process it etc...) - } - - if(BootInfo->EnabledVBE) - { - // NOTE: Do something with it.. (Store it , process it etc...) - } - - if(BootInfo->ValidSymbolTable) - { - // NOTE: Do something with it.. (Store it , process it etc...) - // printf("- Valid Symbol Table available at 0x%x.\n Tab Size: %d, str Size: %d\n", BootInfo->SymbolTableAddr, BootInfo->SymbolTabSize, BootInfo->SymbolStrSize); - } - - if(BootInfo->PhysicalMemoryMapAvailable) - { - - - SetupPhysicalMemoryManager(BootInfo); - } - -} +} \ No newline at end of file diff --git a/source/kernel/linker.ld b/source/kernel/linker.ld index ef2b6a1..f15ca57 100644 --- a/source/kernel/linker.ld +++ b/source/kernel/linker.ld @@ -8,20 +8,16 @@ SECTIONS _kernel_start = .; kernel_begin = .; /* For legacy reasons */ - - + .multiboot.data : { *(.multiboot.data) } .multiboot.text : { *(multiboot.text) - *prekernel.o(.text) } . += 0xC0000000; /* Addresses in the following code need to be above the 3Gb mark */ - - .text ALIGN (4K) : AT (ADDR (.text) - 0xC0000000) { *(.text) diff --git a/source/kernel/memory/PhysicalMemoryManager.cpp b/source/kernel/memory/PhysicalMemoryManager.cpp index c16d33e..33dde1e 100644 --- a/source/kernel/memory/PhysicalMemoryManager.cpp +++ b/source/kernel/memory/PhysicalMemoryManager.cpp @@ -1,66 +1,46 @@ #include "./PhysicalMemoryManager.h" +#define BLOCK_SIZE 4092 +#define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) +#define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) const uint32_t KERNEL_OFFSET = 0xC0000000; -extern uint32_t* boot_page_directory; -extern uint32_t* boot_page_table; -extern uint32_t* multiboot_page_table; -PhysicalMemoryManagerInfoBlock* PMMInfoBlock; +uint32_t* memoryBitMap; +uint32_t pmmap_size; +uint32_t max_blocks; +int used_blocks; -void SetupPhysicalMemoryManager( BootInfoBlock* Bootinfo) + +void SetupPhysicalMemoryManager(uint32_t mapAddress, uint32_t memorySize ) { - - // NOTE: We should move our bitmap to just after the end of our kernel instead - PMMInfoBlock = (PhysicalMemoryManagerInfoBlock*) ( ((uint32_t)MemoryMapHeap_pptr + 80 ) + KERNEL_OFFSET ); - /* + /* Every byte contains 8 pages A page is 4096 kib Every block (1 bit) represent an page */ - // Calculate the maximum number of blocks - int maximum_blocks = (uint32_t)Bootinfo->MemorySize / BLOCK_SIZE / 8; - PMMInfoBlock->max_blocks = maximum_blocks; - PMMInfoBlock->used_blocks = 0; + // Set the maximum number of blocks + max_blocks = (uint32_t)memorySize / BLOCK_SIZE ; + printf("Max Blocks: %d\n", max_blocks); - // put the map after the gdt - PMMInfoBlock->memoryBitMap = (uint32_t*) ( 0xC010b100) ; + // Set size of the bitmap + uint32_t bitmap_size = max_blocks / 32; + printf("Bitmap size: %d bytes\n",bitmap_size); + + // Set blocks used to zero + used_blocks = 0; - //Size of memory map - uint32_t memMap_size = PMMInfoBlock->max_blocks / 8; + // set the address of the memory bitmap + memoryBitMap = (uint32_t*) mapAddress; + // Set all places in memory as free - memset(PMMInfoBlock->memoryBitMap, 0xFF, memMap_size ); - MemoryInfoBlock* currentBlock = (MemoryInfoBlock*) ((uint32_t)Bootinfo->MemoryMap + 0xC0000000) ; - - printf( "Starting address: 0x%x\n", currentBlock); - while( (uint32_t)currentBlock->next != 0x0 ) - { - - if(IS_AVAILABLE_MEM(currentBlock->type)){ - printf("skip!\n"); - } - else{ - printf("allocate region 0x%x of size %d bytes\n", currentBlock->Base_addr, currentBlock->Memory_Size); - // allocate_region( currentBlock->Base_addr, currentBlock->Memory_Size); // allocate region causes #PF Exception - } - - currentBlock = (MemoryInfoBlock*) ((uint32_t)currentBlock->next + 0xC0000000 ); - - } - - uint32_t kernel_size = ((uint32_t)&kernel_end - (uint32_t)&kernel_begin ) - KERNEL_OFFSET; - - printf("kernel size in memory: 0x%x\n", kernel_size); - allocate_region((uint32_t)&kernel_begin, kernel_size); - - printf("allocate BIOS region\n"); - allocate_region (0x0000000, 0x00100000); + memset(memoryBitMap, 0xFFFFFFFF, max_blocks / 32 ); } // NOTE: This can only give blocks of 4kb at a time! // We might at some point want to allocate multiple blocks at once. void* allocate_block() { - uint8_t blocks_available = PMMInfoBlock->max_blocks - PMMInfoBlock->used_blocks; + uint8_t blocks_available = max_blocks - used_blocks; // Are there any blocks available? if( blocks_available <= 0) { @@ -69,7 +49,7 @@ void* allocate_block() { } // Find 1 free block somewhere - int free_block_index = bitmap_first_unset(PMMInfoBlock->memoryBitMap, PMMInfoBlock->max_blocks / 8 ); + int free_block_index = bitmap_first_unset(memoryBitMap, max_blocks / 8 ); if(free_block_index == -1) { @@ -82,10 +62,10 @@ void* allocate_block() { printf("Somethings wrong!!!\n"); // Set the block to be used! - bitmap_unset(PMMInfoBlock->memoryBitMap, free_block_index); + bitmap_unset(memoryBitMap, free_block_index); // Increase the used_block count! - PMMInfoBlock->used_blocks++; - printf("used blocks: 0x%x\n", PMMInfoBlock->used_blocks); + used_blocks++; + printf("used blocks: 0x%x\n", used_blocks); // return the pointer to the physical address return (void*) (BLOCK_SIZE * free_block_index); } @@ -99,9 +79,9 @@ void free_block(void* p) { int index = ((uint32_t) p) / BLOCK_SIZE; // set the block to be free - bitmap_set(PMMInfoBlock->memoryBitMap, index); - PMMInfoBlock->used_blocks--; - printf("used blocks: 0x%x, after free\n", PMMInfoBlock->used_blocks); + bitmap_set(memoryBitMap, index); + used_blocks--; + printf("used blocks: 0x%x, after free\n", used_blocks); } @@ -111,28 +91,26 @@ void allocate_region(uint32_t startAddress, uint32_t size) { int NumberOfBlocksToAllocate = ( size / 1024) / 4 / 8 + 1; int startBlock = (startAddress / 1024) / 4 / 8 ; - for( int i = 0; i < NumberOfBlocksToAllocate; i++) { - bitmap_unset(PMMInfoBlock->memoryBitMap, startBlock+ i); - PMMInfoBlock->used_blocks++; + bitmap_unset(memoryBitMap, startBlock + i);// allocate region causes #PF Exception + used_blocks++; } - - } void deallocate_region(uint32_t StartAddress , uint32_t size ) { // reverse of what happened in allocate_region - int NumberOfBlocks = (size / 1024) / 4 / 8 + 1; int startBlock = (StartAddress / 1024) / 4 / 8; for(int i = 0; i < NumberOfBlocks; i++) { - bitmap_set(PMMInfoBlock->memoryBitMap, startBlock + i); - PMMInfoBlock->used_blocks --; + bitmap_set(memoryBitMap, startBlock + i); + used_blocks --; } } - +int GetUsedBlocks (){ + return used_blocks; +} diff --git a/source/kernel/memory/PhysicalMemoryManager.h b/source/kernel/memory/PhysicalMemoryManager.h index f51c329..87d3a8c 100644 --- a/source/kernel/memory/PhysicalMemoryManager.h +++ b/source/kernel/memory/PhysicalMemoryManager.h @@ -5,22 +5,14 @@ #include "../lib/mem.h" #include "../bitmap.h" -// Asumming i386 for now! -#define BLOCK_SIZE 4092 -#define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) -#define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) -struct PhysicalMemoryManagerInfoBlock -{ - uint32_t* memoryBitMap; - uint32_t pmmap_size; - uint32_t max_blocks; - int used_blocks; -}; +void SetupPhysicalMemoryManager(uint32_t mapAddress, uint32_t memorySize); -void SetupPhysicalMemoryManager(BootInfoBlock* memory); -void free_block(void* ptr); void* allocate_block(); -void allocate_region(uint32_t, uint32_t); -void deallocate_region(uint32_t , uint32_t ); +void free_block(void* ptr); + +void allocate_region(uint32_t address, uint32_t size); +void deallocate_region(uint32_t address, uint32_t size); + +int GetUsedBlocks(); \ No newline at end of file diff --git a/source/kernel/memory/VirtualMemoryManager.cpp b/source/kernel/memory/VirtualMemoryManager.cpp index 813d52b..bc535ee 100644 --- a/source/kernel/memory/VirtualMemoryManager.cpp +++ b/source/kernel/memory/VirtualMemoryManager.cpp @@ -1,5 +1,5 @@ #include "VirtualMemoryManager.h" - +#define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) extern uint32_t boot_page_directory[1024] ; extern uint32_t boot_page_table[1024]; diff --git a/source/kernel/prekernel/bootstructure.h b/source/kernel/prekernel/bootstructure.h index 51f8ce0..63e95f6 100644 --- a/source/kernel/prekernel/bootstructure.h +++ b/source/kernel/prekernel/bootstructure.h @@ -39,8 +39,3 @@ struct BootInfoBlock { uint32_t MemorySize ; }; - - -const uint32_t pke = ((uint32_t)&kernel_end) - 0xC0000000; -const uint32_t BootInfoBlock_pptr = pke + 1000 - sizeof(BootInfoBlock); -const uint32_t MemoryMapHeap_pptr = pke + 0x1; diff --git a/source/kernel/prekernel/prekernel.cpp b/source/kernel/prekernel/prekernel.cpp index 156201c..53c34d3 100644 --- a/source/kernel/prekernel/prekernel.cpp +++ b/source/kernel/prekernel/prekernel.cpp @@ -1,119 +1,140 @@ #include #include #include "multiboot.h" -#include "bootstructure.h" +#include "../memory/PhysicalMemoryManager.h" + #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) +#define VADDR_TO_PADDR(vaddr) (vaddr - 0xC0000000) +#define PADDR_TO_VADDR(paddr) (paddr + 0xC0000000) -extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) { - - // Create the bootInfoBlock at its location - BootInfoBlock* BIB = (BootInfoBlock*) BootInfoBlock_pptr; +extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) +{ - /* - * Check Multiboot magic number - */ - if (magic != MULTIBOOT_BOOTLOADER_MAGIC) - { - BIB->MapIsInvalid = true; - // crash - return; - } else{ - BIB->MapIsInvalid = false; - } - - /* is boot device valid ? */ - if (CHECK_FLAG (mbi->flags, 1)) - { - BIB->bootDeviceID = mbi->boot_device; - } else{ - BIB->bootDeviceID = 0x11111111; - } - - /* Are mods_* valid? */ - if(CHECK_FLAG ( mbi->flags, 3)){ - multiboot_module_t *mod; - uint32_t i; - - BIB->GrubModuleCount = mbi->mods_count; - - - for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ - - } - } - - /* Is the symbol table of a.out valid? */ - if (CHECK_FLAG(mbi->flags, 4)) - { - BIB->ValidSymbolTable = true; - multiboot_aout_symbol_table_t *multiboot_aout_sym = &(mbi->u.aout_sym); - - } else{ - BIB->ValidSymbolTable = false; - } - - /* Is the section header table of ELF valid? */ - if (CHECK_FLAG(mbi->flags, 5)) - { - BIB->ValidELFHeader = true; - multiboot_elf_section_header_table_t *multiboot_elf_sec = &(mbi->u.elf_sec); - - }else{ - BIB->ValidELFHeader = false; - } -/* -If we got a memory map from our bootloader we -should be parsing it to find out the memory regions available. -*/ -if (CHECK_FLAG(mbi->flags, 6)) -{ - BIB->PhysicalMemoryMapAvailable = true; - BIB->MemoryMap = (MemoryInfoBlock*) MemoryMapHeap_pptr; - multiboot_memory_map_t *mmap = (multiboot_memory_map_t*) (mbi->mmap_addr) ; - auto MemoryMapEnd = mbi->mmap_addr + mbi->mmap_length; - - auto CurrentInfoBlock = BIB->MemoryMap; - - uint32_t RAM_size = 0; - - while((unsigned long) mmap < MemoryMapEnd){ - BIB->map_size += sizeof(MemoryInfoBlock); - CurrentInfoBlock->Base_addr = mmap->addr; - CurrentInfoBlock->Memory_Size = mmap->len; - - - if(mmap->type == MULTIBOOT_MEMORY_AVAILABLE) - CurrentInfoBlock->type |= 0x1; - RAM_size += mmap->len; - if(mmap->type == MULTIBOOT_MEMORY_ACPI_RECLAIMABLE) - CurrentInfoBlock->type |= 0x2; - if(mmap->type == MULTIBOOT_MEMORY_RESERVED) - CurrentInfoBlock->type |= 0x4; - if(mmap->type == MULTIBOOT_MEMORY_NVS) - CurrentInfoBlock->type |= 0x8; - if(mmap->type == MULTIBOOT_MEMORY_BADRAM) - CurrentInfoBlock->type |= 0x10; - - - // continue to the next block - mmap = (multiboot_memory_map_t *) ((unsigned long) mmap + mmap->size + sizeof(mmap->size)); - - CurrentInfoBlock->next = (MemoryInfoBlock*) CurrentInfoBlock + 16; - CurrentInfoBlock = CurrentInfoBlock->next; + /* + * Check Multiboot magic number + */ + if (magic != MULTIBOOT_BOOTLOADER_MAGIC) + { + // PANIC!! + return; } - CurrentInfoBlock->next = (MemoryInfoBlock*) 0x0; - BIB->MemorySize = RAM_size; -} else -{ - BIB->PhysicalMemoryMapAvailable = false; -} - - /* Draw diagonal blue line */ - if (CHECK_FLAG (mbi->flags, 12)){ - BIB->EnabledVBE = true; - } else{ - BIB->EnabledVBE; - } + mbi = PADDR_TO_VADDR(mbi); + + + // Setup the physical memory manager immmediatly + // Doing so saves the complications of doing it later when + // paging is enabled + + /* + If we got a memory map from our bootloader we + should be parsing it to find out the memory regions available. + */ + if (CHECK_FLAG(mbi->flags, 6)) + { + + // Calculate total memory size + uint32_t RAM_size = 0; + for( + multiboot_memory_map_t* mmap = (multiboot_memory_map_t*) mbi->mmap_addr; + (unsigned long)mmap < mbi->mmap_addr + mbi->mmap_length; + mmap += mmap->size +sizeof(mmap->size) + ){ + RAM_size += mmap->len; + } + + // Call SetupPhysicalMemoryManager at its physical address + SetupPhysicalMemoryManager ( (uint32_t)VADDR_TO_PADDR(&kernel_end), RAM_size); + + for( + multiboot_memory_map_t* mmap = (multiboot_memory_map_t*) mbi->mmap_addr; + (unsigned long)mmap < mbi->mmap_addr + mbi->mmap_length; + mmap += mmap->size +sizeof(mmap->size) + ){ + + if(mmap->type == MULTIBOOT_MEMORY_AVAILABLE) + deallocate_region(mmap->addr, mmap->len); + if(mmap->type == MULTIBOOT_MEMORY_ACPI_RECLAIMABLE) + allocate_region(mmap->addr, mmap->len); + if(mmap->type == MULTIBOOT_MEMORY_RESERVED) + allocate_region(mmap->addr, mmap->len); + if(mmap->type == MULTIBOOT_MEMORY_NVS) + allocate_region(mmap->addr, mmap->len); + if(mmap->type == MULTIBOOT_MEMORY_BADRAM) + allocate_region(mmap->addr, mmap->len); + + } + + + // Allocate the kernel + allocate_region( (uint32_t)&kernel_begin, ( (uint32_t)&kernel_end - (uint32_t)&kernel_begin)- 0xC0000000 ); + + // Allocate the memory region below 1MB + allocate_region(0x0000000, 0x00100000); + + } + else + { + // We didn't get a memory map from our bootloader. + // PANIC!!!! + return; + } + + // allocate a full block for the other boot info! + BootInfoBlock* BIB = (BootInfoBlock*) allocate_block(); + + + /* is boot device valid ? */ + if (CHECK_FLAG (mbi->flags, 1)) + { + BIB->bootDeviceID = mbi->boot_device; + } else{ + BIB->bootDeviceID = 0x11111111; + } + + /* Are mods_* valid? */ + if(CHECK_FLAG ( mbi->flags, 3)){ + multiboot_module_t *mod; + uint32_t i; + + BIB->GrubModuleCount = mbi->mods_count; + + + for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ + + } + } + + /* Is the symbol table of a.out valid? */ + if (CHECK_FLAG(mbi->flags, 4)) + { + // NOTE: Do something with it.. (Store it , process it etc...) + // printf("- Valid Symbol Table available at 0x%x.\n Tab Size: %d, str Size: %d\n", BootInfo->SymbolTableAddr, BootInfo->SymbolTabSize, BootInfo->SymbolStrSize); + BIB->ValidSymbolTable = true; + multiboot_aout_symbol_table_t *multiboot_aout_sym = &(mbi->u.aout_sym); + + } else{ + BIB->ValidSymbolTable = false; + } + + /* Is the section header table of ELF valid? */ + if (CHECK_FLAG(mbi->flags, 5)) + { + // NOTE: Do something with it.. (Store it , process it etc...) + BIB->ValidELFHeader = true; + multiboot_elf_section_header_table_t *multiboot_elf_sec = &(mbi->u.elf_sec); + + }else{ + BIB->ValidELFHeader = false; + } + + /* Draw diagonal blue line */ + if (CHECK_FLAG (mbi->flags, 12)){ + BIB->EnabledVBE = true; + + // NOTE: Do something with it.. (Store it , process it etc...) + } else{ + BIB->EnabledVBE; + } } -- 2.39.5 From a47879f404e5d7ea268247a56cc535f86014869c Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 3 Sep 2022 17:27:29 +0200 Subject: [PATCH 080/115] KERNEL: First Kernel heap implementation --- source/kernel/kernel.cpp | 15 ++++--- source/kernel/memory/KernelHeap.cpp | 43 +++++++++++++++++-- .../kernel/memory/PhysicalMemoryManager.cpp | 3 +- source/kernel/memory/PhysicalMemoryManager.h | 1 + source/kernel/memory/VirtualMemoryManager.cpp | 32 ++++++++++---- source/kernel/memory/VirtualMemoryManager.h | 12 ++++-- source/kernel/prekernel/bootstructure.h | 11 ----- source/kernel/serial.h | 17 -------- 8 files changed, 83 insertions(+), 51 deletions(-) diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 6f932a1..8049eb5 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -38,11 +38,9 @@ extern "C" void kernel_main () extern "C" void early_main() { init_serial(); - print_serial("Hello Higher half kernel!\n"); kterm_init(); - - printf("Allocated blocks: %d \n", GetUsedBlocks()); + printf("Allocated blocks: 0x%x \n", GetUsedBlocks()); initGDT(); init_idt(); @@ -53,8 +51,12 @@ extern "C" void early_main() initHeap(); + printf("TRY ALLOCATING 4 BYTES\n"); + uint32_t* MyVariable = (uint32_t*) malloc(4); // allocate 4 bytes using my heap + free(MyVariable); + // test heap allocation - /* + struct KernelInfo { int bar; bool foo; @@ -64,9 +66,10 @@ extern "C" void early_main() MyInfo->bar = 6; MyInfo->foo = false; - + printf("bar contains %d\n", MyInfo->bar); free(MyInfo); - */ + + printf("Enable Protected mode and jump to kernel main\n"); diff --git a/source/kernel/memory/KernelHeap.cpp b/source/kernel/memory/KernelHeap.cpp index 0aff6d3..a17ccf6 100644 --- a/source/kernel/memory/KernelHeap.cpp +++ b/source/kernel/memory/KernelHeap.cpp @@ -1,4 +1,5 @@ #include "KernelHeap.h" +#include "VirtualMemoryManager.h" // Size of heap meta data is 5 bytes struct heap_block{ @@ -11,7 +12,7 @@ heap_block* start ; void* malloc(size_t size) { - printf("Received request for %d bytes of memory", size); + printf("Received request for %d bytes of memory\n", size); heap_block* current = start; // look for a free block @@ -20,8 +21,21 @@ void* malloc(size_t size) if(current->Size >= size && current->Used == false ) { // We found a spot + printf("Block found!\n"); + // Set the spot to in-use - current->Used = false; + current->Used = true; + + + // split the block + printf("Split block.\n"); + uint32_t oldSize = current->Size; + current->Size = size; + + heap_block* new_block = current + sizeof(heap_block) + current->Size; + new_block->Size = oldSize - ( sizeof(heap_block) + size); + new_block->Used = false; + // return the free address // NOTE: added an offset from the initial address to accomodate for // meta-data. @@ -36,6 +50,7 @@ void* malloc(size_t size) // probably ask the VMM for more // TODO: ask for more memory | Extend kernel heap + printf("ERROR: OUT OF HEAP MEMORY CONDITION IS NOT IMPLEMENTED. HEAP NEEDS TO BE EXTENDED!\n"); } void free(void* addr) @@ -48,6 +63,26 @@ void free(void* addr) void initHeap() { - // NOTE: What to do now?? - + // put the start of our kernel heap 1 page after the kernel_end address + // Lets calculate the address + printf("FIND SUITABLE HEAP_ADDRESS\n"); + uint32_t alligned_k_end = (uint32_t) &kernel_end + ((uint32_t)&kernel_end % BLOCK_SIZE == 0 ? 4096 : 0); + uint32_t HEAP_ADDRESS = (uint32_t) alligned_k_end + 4096; + printf("HEAP_ADDRESS: 0x%x\n", HEAP_ADDRESS); + + // NOTE: we can't check if the mapping has failed or not here! + AllocatePage(HEAP_ADDRESS); + start = (heap_block*) HEAP_ADDRESS; + heap_size = 4096; + + printf("Clear heap\n"); + // Clear the heap + printf("set at 0x%x %d bytes to zero\n", start , heap_size); + memset((void*)start, 0x00, heap_size /4); + + printf("Init first heap block\n"); + // initialzie + start->Size = heap_size - sizeof(heap_block); + start->Used = false; + } \ No newline at end of file diff --git a/source/kernel/memory/PhysicalMemoryManager.cpp b/source/kernel/memory/PhysicalMemoryManager.cpp index 33dde1e..3d78798 100644 --- a/source/kernel/memory/PhysicalMemoryManager.cpp +++ b/source/kernel/memory/PhysicalMemoryManager.cpp @@ -1,5 +1,4 @@ #include "./PhysicalMemoryManager.h" -#define BLOCK_SIZE 4092 #define IS_ALIGNED(addr, align) !((addr) & ~((align) - 1)) #define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) @@ -28,7 +27,7 @@ void SetupPhysicalMemoryManager(uint32_t mapAddress, uint32_t memorySize ) printf("Bitmap size: %d bytes\n",bitmap_size); // Set blocks used to zero - used_blocks = 0; + used_blocks = max_blocks; // set the address of the memory bitmap memoryBitMap = (uint32_t*) mapAddress; diff --git a/source/kernel/memory/PhysicalMemoryManager.h b/source/kernel/memory/PhysicalMemoryManager.h index 87d3a8c..e68b33d 100644 --- a/source/kernel/memory/PhysicalMemoryManager.h +++ b/source/kernel/memory/PhysicalMemoryManager.h @@ -5,6 +5,7 @@ #include "../lib/mem.h" #include "../bitmap.h" +#define BLOCK_SIZE 4092 void SetupPhysicalMemoryManager(uint32_t mapAddress, uint32_t memorySize); diff --git a/source/kernel/memory/VirtualMemoryManager.cpp b/source/kernel/memory/VirtualMemoryManager.cpp index bc535ee..3ce9260 100644 --- a/source/kernel/memory/VirtualMemoryManager.cpp +++ b/source/kernel/memory/VirtualMemoryManager.cpp @@ -1,9 +1,16 @@ #include "VirtualMemoryManager.h" #define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) + extern uint32_t boot_page_directory[1024] ; extern uint32_t boot_page_table[1024]; +void flush_cr3(){ + asm volatile("movl %cr3, %ecx;" + "movl %ecx, %cr3"); +} + + void AllocatePage(uint32_t vaddr) { uint32_t page_aligned_address = ALIGN(vaddr, 4096); @@ -15,23 +22,31 @@ void AllocatePage(uint32_t vaddr) printf("Allocation happening at PDE: %d PTE: %d\n", PageDirectoryEntryIndex, PageTableEntryIndex); // check if the page directory entry is marked as present - if (boot_page_directory[PageDirectoryEntryIndex] & 0x1 ) { - - uint32_t* page_table = (uint32_t*)((boot_page_directory[PageDirectoryEntryIndex]) & 0xFFFFE000 + 0xC0000000); + if (boot_page_directory[PageDirectoryEntryIndex] & 0x1 ) + { + printf("Directory entry is marked as present\n"); + uint32_t* page_table = (uint32_t*)((boot_page_directory[PageDirectoryEntryIndex]) & 0xFFFFE000) ; + page_table = (uint32_t*) ((uint32_t)page_table + 0xC0000000); // Add kernel offset + printf("Page table address: 0x%x\n", (uint32_t)page_table); // check if the page table entry is marked as present if ( page_table[PageTableEntryIndex] & 0x1 ) { + printf("page already present!\n"); + return; + } else{ + printf("Mapping a physical page.\n"); // Map the entry to a physical page page_table[PageTableEntryIndex] = (uint32_t)(allocate_block() + 0x3); - } else{ - // mark page as present - page_table[PageTableEntryIndex] = 0x3; + flush_cr3(); } } else { + printf("Mapping a new page directory entry with a page table\n"); // mark the page table as present and allocate a physical block for it boot_page_directory[PageDirectoryEntryIndex] = (uint32_t)(allocate_block() + 0x3); + flush_cr3(); + } @@ -56,7 +71,8 @@ void FreePage(uint32_t vaddr ) } -void Map ( uint32_t vaddr, uint32_t paddr) + +void Immediate_Map ( uint32_t vaddr, uint32_t paddr) { uint32_t page_aligned_address = ALIGN(vaddr, 4096); @@ -66,7 +82,7 @@ void Map ( uint32_t vaddr, uint32_t paddr) } -void Unmap(uint32_t vaddr) +void Immediate_Unmap(uint32_t vaddr) { // NOTE: I will implement lazy unmapping for now uint32_t page_aligned_address = ALIGN(vaddr, 4096); diff --git a/source/kernel/memory/VirtualMemoryManager.h b/source/kernel/memory/VirtualMemoryManager.h index e54e3ed..ef80ffe 100644 --- a/source/kernel/memory/VirtualMemoryManager.h +++ b/source/kernel/memory/VirtualMemoryManager.h @@ -1,10 +1,16 @@ #pragma once -#include "PhysicalMemoryManager.h" #include "../terminal/kterm.h" #include "../cpu.h" +#include "PhysicalMemoryManager.h" + + +void SetupVMM(); void AllocatePage(uint32_t v_addr ); void FreePage(uint32_t v_addr); -void Map(uint32_t p_addr, uint32_t v_addr); -void Unmap (uint32_t v_addr); +void Immediate_Map(uint32_t p_addr, uint32_t v_addr); +void Immediate_Unmap (uint32_t v_addr); + +// void Demand_map(uint32_t p_addr, uint32_t v_addr); +// void Demand_Unmap (uint32_t v_addr); diff --git a/source/kernel/prekernel/bootstructure.h b/source/kernel/prekernel/bootstructure.h index 63e95f6..48fd40d 100644 --- a/source/kernel/prekernel/bootstructure.h +++ b/source/kernel/prekernel/bootstructure.h @@ -11,13 +11,7 @@ extern "C" const uint32_t kernel_end; #define IS_NVS_MEMORY(MEM_TYPE) MEM_TYPE & 0x8 #define IS_BADRAM_MEMORY(MEM_TYPE) MEM_TYPE & 0x10 -struct MemoryInfoBlock { - uint32_t Base_addr ; - uint32_t Memory_Size; - MemoryInfoBlock* next; - uint8_t type; -}; struct BootInfoBlock { bool MapIsInvalid; uint32_t bootDeviceID ; @@ -33,9 +27,4 @@ struct BootInfoBlock { bool EnabledVBE; - bool PhysicalMemoryMapAvailable; - MemoryInfoBlock* MemoryMap; - uint32_t map_size; - uint32_t MemorySize ; - }; diff --git a/source/kernel/serial.h b/source/kernel/serial.h index b17afd8..6494a36 100644 --- a/source/kernel/serial.h +++ b/source/kernel/serial.h @@ -56,20 +56,3 @@ void print_serial(const char* string ){ } } -void test_serial(){ - /** Serial test **/ - kterm_writestring("Writing to COM1 serial port:"); - init_serial(); - write_serial('A'); - write_serial('B'); - write_serial('C'); - write_serial('D'); - write_serial('E'); - - char Character_received = read_serial(); - kterm_writestring("\n"); - kterm_writestring("received from COM 1: \n"); - kterm_put(Character_received); - - kterm_writestring("\n"); -} -- 2.39.5 From 16e23540192baa82f4b59b69677e6e1f69c53b8c Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 3 Sep 2022 17:27:41 +0200 Subject: [PATCH 081/115] KERNEL: Moved serials test function into the test folder --- source/kernel-test/SerialTest.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 source/kernel-test/SerialTest.cpp diff --git a/source/kernel-test/SerialTest.cpp b/source/kernel-test/SerialTest.cpp new file mode 100644 index 0000000..cffdfc0 --- /dev/null +++ b/source/kernel-test/SerialTest.cpp @@ -0,0 +1,18 @@ + +void test_serial(){ + /** Serial test **/ + kterm_writestring("Writing to COM1 serial port:"); + init_serial(); + write_serial('A'); + write_serial('B'); + write_serial('C'); + write_serial('D'); + write_serial('E'); + + char Character_received = read_serial(); + kterm_writestring("\n"); + kterm_writestring("received from COM 1: \n"); + kterm_put(Character_received); + + kterm_writestring("\n"); +} \ No newline at end of file -- 2.39.5 From 68371475d96b914a3f20591eaf49792a3a7f8103 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 3 Sep 2022 17:38:22 +0200 Subject: [PATCH 082/115] Marking memory management features as done. Work still needs to be done but the bare minimum for memory management is there. --- features.md | 6 +++--- todo.md | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/features.md b/features.md index b704af2..c953c7f 100644 --- a/features.md +++ b/features.md @@ -18,9 +18,9 @@ Virtual filesystem \ Keyboard support ( P/S2 Keyboard) \ Physical memory management \ - Paging \ - Virtual memory management \ - The heap: allocating memory at runtime (malloc and free) is almost impossible to go without. \ + Paging \ + Virtual memory management \ + The heap: allocating memory at runtime (malloc and free) is almost impossible to go without. \ Enable SIMD Extensions (SSE) Hardware Management system diff --git a/todo.md b/todo.md index d927cb1..a47a9f3 100644 --- a/todo.md +++ b/todo.md @@ -8,11 +8,11 @@ needs to be done. It is a expansion on the features markdown file which describe to do on a more in depth level. ## -- -[ ] Setup paging \ +[x] Setup paging \ [ ] HELP command -[ ] Setup a proper HEAP \ +[x] Setup a proper HEAP \ [ ] Setup a proper Stack \ -[ ] Setup KMalloc and KFree \ +[x] Setup KMalloc and KFree \ [ ] Merge Functioning Feature branches into sandboxKernelDev \ [ ] Remove merged feature branches \ [ ] Merge sandboxKernelDev with dev \ -- 2.39.5 From 364d10d02e3220289e399c5debad5d9ea344a68c Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 10 Sep 2022 20:06:49 +0200 Subject: [PATCH 083/115] src folder -> source folder; makes merging with dev a bit easier. --- Makefile | 6 +++--- {src => source}/grub.cfg | 0 .../kernel/PartitionTable/MBR/MasterBootRecord.h | 0 .../kernel/PartitionTable/MBR/PartitionTableEntry.h | 0 {src => source}/kernel/boot.s | 10 +++++----- {src => source}/kernel/bootcheck.h | 0 {src => source}/kernel/bootinfo.h | 0 {src => source}/kernel/bootloader/multiboot.h | 0 {src => source}/kernel/cpu.h | 0 {src => source}/kernel/crti.s | 0 {src => source}/kernel/crtn.s | 0 {src => source}/kernel/definitions.h | 0 {src => source}/kernel/drivers/ACPI/rsdp.cpp | 0 {src => source}/kernel/drivers/ACPI/rsdp.h | 0 {src => source}/kernel/drivers/IO/PCI/pci.cpp | 0 {src => source}/kernel/drivers/IO/PCI/pci.h | 0 {src => source}/kernel/drivers/IO/ata/ataDevice.cpp | 0 {src => source}/kernel/drivers/IO/ata/ataDevice.h | 0 .../kernel/drivers/IO/atapi/atapiDevice.cpp | 0 {src => source}/kernel/drivers/IO/atapi/atapiDevice.h | 0 {src => source}/kernel/drivers/IO/io.cpp | 0 {src => source}/kernel/drivers/IO/io.h | 0 {src => source}/kernel/drivers/VGA/VBE.h | 0 {src => source}/kernel/drivers/VGA/colors.h | 0 {src => source}/kernel/drivers/cmos/cmos.cpp | 0 {src => source}/kernel/filesystems/EXT2/SuperBlock.h | 0 .../kernel/filesystems/FAT/BiosParameterBlock.h | 0 .../kernel/filesystems/FAT/DirectoryEntry.h | 0 .../kernel/filesystems/FAT/ExtendBootRecord.h | 0 {src => source}/kernel/gdt/gdt.s | 0 {src => source}/kernel/gdt/gdtc.cpp | 0 {src => source}/kernel/gdt/gdtc.h | 0 {src => source}/kernel/ide/ide.h | 0 {src => source}/kernel/ide/ideCommands.h | 0 {src => source}/kernel/ide/sampleIDE.definitions.h | 0 {src => source}/kernel/ide/sampleIDE.h | 0 {src => source}/kernel/idt/idt.cpp | 0 {src => source}/kernel/idt/idt.h | 0 {src => source}/kernel/idt/idt.s | 0 {src => source}/kernel/idt/scancodes/set1.h | 0 {src => source}/kernel/irq_table.s | 0 {src => source}/kernel/irs_table.s | 0 {src => source}/kernel/kernel.cpp | 0 {src => source}/kernel/kernel.h | 0 {src => source}/kernel/keyboard/keyboard.cpp | 0 {src => source}/kernel/keyboard/keyboard.h | 0 {src => source}/kernel/kstructures/bitmap.h | 0 {src => source}/kernel/linker.ld | 0 {src => source}/kernel/memory/PageDirectory.cpp | 0 {src => source}/kernel/memory/PageDirectory.h | 0 {src => source}/kernel/memory/memory.cpp | 0 {src => source}/kernel/memory/memory.h | 0 {src => source}/kernel/memory/memoryinfo.h | 0 {src => source}/kernel/memory/paging.s | 0 {src => source}/kernel/pci/pciDevice.cpp | 0 {src => source}/kernel/pci/pciDevice.h | 0 {src => source}/kernel/pic/pic.cpp | 0 {src => source}/kernel/pic/pic.h | 0 {src => source}/kernel/pit.cpp | 0 {src => source}/kernel/pit.h | 0 {src => source}/kernel/serial.h | 0 {src => source}/kernel/serial/serial.cpp | 0 {src => source}/kernel/serial/serial.h | 0 .../kernel/sv-terminal/superVisorTerminal.cpp | 0 .../kernel/sv-terminal/superVisorTerminal.h | 0 {src => source}/kernel/time.cpp | 0 {src => source}/kernel/time.h | 0 {src => source}/kernel/timer.cpp | 0 {src => source}/kernel/timer.h | 0 {src => source}/kernel/tty/kterm.cpp | 0 {src => source}/kernel/tty/kterm.h | 0 {src => source}/kernel/vfs/File.h | 0 {src => source}/kernel/vfs/VFS.cpp | 0 {src => source}/kernel/vfs/VFS.h | 0 {src => source}/libc/include/mem.h | 0 {src => source}/libc/include/string.c | 0 {src => source}/libc/include/string.h | 0 77 files changed, 8 insertions(+), 8 deletions(-) rename {src => source}/grub.cfg (100%) rename {src => source}/kernel/PartitionTable/MBR/MasterBootRecord.h (100%) rename {src => source}/kernel/PartitionTable/MBR/PartitionTableEntry.h (100%) rename {src => source}/kernel/boot.s (84%) rename {src => source}/kernel/bootcheck.h (100%) rename {src => source}/kernel/bootinfo.h (100%) rename {src => source}/kernel/bootloader/multiboot.h (100%) rename {src => source}/kernel/cpu.h (100%) rename {src => source}/kernel/crti.s (100%) rename {src => source}/kernel/crtn.s (100%) rename {src => source}/kernel/definitions.h (100%) rename {src => source}/kernel/drivers/ACPI/rsdp.cpp (100%) rename {src => source}/kernel/drivers/ACPI/rsdp.h (100%) rename {src => source}/kernel/drivers/IO/PCI/pci.cpp (100%) rename {src => source}/kernel/drivers/IO/PCI/pci.h (100%) rename {src => source}/kernel/drivers/IO/ata/ataDevice.cpp (100%) rename {src => source}/kernel/drivers/IO/ata/ataDevice.h (100%) rename {src => source}/kernel/drivers/IO/atapi/atapiDevice.cpp (100%) rename {src => source}/kernel/drivers/IO/atapi/atapiDevice.h (100%) rename {src => source}/kernel/drivers/IO/io.cpp (100%) rename {src => source}/kernel/drivers/IO/io.h (100%) rename {src => source}/kernel/drivers/VGA/VBE.h (100%) rename {src => source}/kernel/drivers/VGA/colors.h (100%) rename {src => source}/kernel/drivers/cmos/cmos.cpp (100%) rename {src => source}/kernel/filesystems/EXT2/SuperBlock.h (100%) rename {src => source}/kernel/filesystems/FAT/BiosParameterBlock.h (100%) rename {src => source}/kernel/filesystems/FAT/DirectoryEntry.h (100%) rename {src => source}/kernel/filesystems/FAT/ExtendBootRecord.h (100%) rename {src => source}/kernel/gdt/gdt.s (100%) rename {src => source}/kernel/gdt/gdtc.cpp (100%) rename {src => source}/kernel/gdt/gdtc.h (100%) rename {src => source}/kernel/ide/ide.h (100%) rename {src => source}/kernel/ide/ideCommands.h (100%) rename {src => source}/kernel/ide/sampleIDE.definitions.h (100%) rename {src => source}/kernel/ide/sampleIDE.h (100%) rename {src => source}/kernel/idt/idt.cpp (100%) rename {src => source}/kernel/idt/idt.h (100%) rename {src => source}/kernel/idt/idt.s (100%) rename {src => source}/kernel/idt/scancodes/set1.h (100%) rename {src => source}/kernel/irq_table.s (100%) rename {src => source}/kernel/irs_table.s (100%) rename {src => source}/kernel/kernel.cpp (100%) rename {src => source}/kernel/kernel.h (100%) rename {src => source}/kernel/keyboard/keyboard.cpp (100%) rename {src => source}/kernel/keyboard/keyboard.h (100%) rename {src => source}/kernel/kstructures/bitmap.h (100%) rename {src => source}/kernel/linker.ld (100%) rename {src => source}/kernel/memory/PageDirectory.cpp (100%) rename {src => source}/kernel/memory/PageDirectory.h (100%) rename {src => source}/kernel/memory/memory.cpp (100%) rename {src => source}/kernel/memory/memory.h (100%) rename {src => source}/kernel/memory/memoryinfo.h (100%) rename {src => source}/kernel/memory/paging.s (100%) rename {src => source}/kernel/pci/pciDevice.cpp (100%) rename {src => source}/kernel/pci/pciDevice.h (100%) rename {src => source}/kernel/pic/pic.cpp (100%) rename {src => source}/kernel/pic/pic.h (100%) rename {src => source}/kernel/pit.cpp (100%) rename {src => source}/kernel/pit.h (100%) rename {src => source}/kernel/serial.h (100%) rename {src => source}/kernel/serial/serial.cpp (100%) rename {src => source}/kernel/serial/serial.h (100%) rename {src => source}/kernel/sv-terminal/superVisorTerminal.cpp (100%) rename {src => source}/kernel/sv-terminal/superVisorTerminal.h (100%) rename {src => source}/kernel/time.cpp (100%) rename {src => source}/kernel/time.h (100%) rename {src => source}/kernel/timer.cpp (100%) rename {src => source}/kernel/timer.h (100%) rename {src => source}/kernel/tty/kterm.cpp (100%) rename {src => source}/kernel/tty/kterm.h (100%) rename {src => source}/kernel/vfs/File.h (100%) rename {src => source}/kernel/vfs/VFS.cpp (100%) rename {src => source}/kernel/vfs/VFS.h (100%) rename {src => source}/libc/include/mem.h (100%) rename {src => source}/libc/include/string.c (100%) rename {src => source}/libc/include/string.h (100%) diff --git a/Makefile b/Makefile index 6b85a09..31eb6d9 100644 --- a/Makefile +++ b/Makefile @@ -27,7 +27,7 @@ $(BUILD_DIR)/sv-terminal.o \ -SRC_DIR = src +SRC_DIR = source BUILD_DIR = build CRTBEGIN_OBJ = $(shell $(CC) $(CFLAGS) -print-file-name=crtbegin.o) @@ -50,7 +50,7 @@ clean_iso: iso: clean_iso clean build mkdir -p root/boot/grub cp build/myos.bin root/boot/myos.bin - cp src/grub.cfg root/boot/grub/grub.cfg + cp source/grub.cfg root/boot/grub/grub.cfg grub-mkrescue -o build/barinkOS.iso root run: all virtualboxvm --startvm "BarinkOS_test" @@ -62,7 +62,7 @@ test_iso: $(EMULATOR) -boot d -cdrom $(BUILD_DIR)/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo build_kernel: $(OBJ_LINK_LIST) - $(CC) -T $(SRC_DIR)/kernel//linker.ld -o $(BUILD_DIR)/myos.bin \ + $(CC) -T $(SRC_DIR)/kernel/linker.ld -o $(BUILD_DIR)/myos.bin \ -ffreestanding -O2 -nostdlib $(OBJ_LINK_LIST) -lgcc build_x86_64: diff --git a/src/grub.cfg b/source/grub.cfg similarity index 100% rename from src/grub.cfg rename to source/grub.cfg diff --git a/src/kernel/PartitionTable/MBR/MasterBootRecord.h b/source/kernel/PartitionTable/MBR/MasterBootRecord.h similarity index 100% rename from src/kernel/PartitionTable/MBR/MasterBootRecord.h rename to source/kernel/PartitionTable/MBR/MasterBootRecord.h diff --git a/src/kernel/PartitionTable/MBR/PartitionTableEntry.h b/source/kernel/PartitionTable/MBR/PartitionTableEntry.h similarity index 100% rename from src/kernel/PartitionTable/MBR/PartitionTableEntry.h rename to source/kernel/PartitionTable/MBR/PartitionTableEntry.h diff --git a/src/kernel/boot.s b/source/kernel/boot.s similarity index 84% rename from src/kernel/boot.s rename to source/kernel/boot.s index 78f5912..3015e8d 100644 --- a/src/kernel/boot.s +++ b/source/kernel/boot.s @@ -21,11 +21,11 @@ stack_bottom: stack_top: .section .text -.include "./src/kernel/gdt/gdt.s" -.include "./src/kernel/irs_table.s" -.include "./src/kernel/irq_table.s" -.include "./src/kernel/idt/idt.s" -.include "./src/kernel/memory/paging.s" +.include "./source/kernel/gdt/gdt.s" +.include "./source/kernel/irs_table.s" +.include "./source/kernel/irq_table.s" +.include "./source/kernel/idt/idt.s" +.include "./source/kernel/memory/paging.s" .global _start diff --git a/src/kernel/bootcheck.h b/source/kernel/bootcheck.h similarity index 100% rename from src/kernel/bootcheck.h rename to source/kernel/bootcheck.h diff --git a/src/kernel/bootinfo.h b/source/kernel/bootinfo.h similarity index 100% rename from src/kernel/bootinfo.h rename to source/kernel/bootinfo.h diff --git a/src/kernel/bootloader/multiboot.h b/source/kernel/bootloader/multiboot.h similarity index 100% rename from src/kernel/bootloader/multiboot.h rename to source/kernel/bootloader/multiboot.h diff --git a/src/kernel/cpu.h b/source/kernel/cpu.h similarity index 100% rename from src/kernel/cpu.h rename to source/kernel/cpu.h diff --git a/src/kernel/crti.s b/source/kernel/crti.s similarity index 100% rename from src/kernel/crti.s rename to source/kernel/crti.s diff --git a/src/kernel/crtn.s b/source/kernel/crtn.s similarity index 100% rename from src/kernel/crtn.s rename to source/kernel/crtn.s diff --git a/src/kernel/definitions.h b/source/kernel/definitions.h similarity index 100% rename from src/kernel/definitions.h rename to source/kernel/definitions.h diff --git a/src/kernel/drivers/ACPI/rsdp.cpp b/source/kernel/drivers/ACPI/rsdp.cpp similarity index 100% rename from src/kernel/drivers/ACPI/rsdp.cpp rename to source/kernel/drivers/ACPI/rsdp.cpp diff --git a/src/kernel/drivers/ACPI/rsdp.h b/source/kernel/drivers/ACPI/rsdp.h similarity index 100% rename from src/kernel/drivers/ACPI/rsdp.h rename to source/kernel/drivers/ACPI/rsdp.h diff --git a/src/kernel/drivers/IO/PCI/pci.cpp b/source/kernel/drivers/IO/PCI/pci.cpp similarity index 100% rename from src/kernel/drivers/IO/PCI/pci.cpp rename to source/kernel/drivers/IO/PCI/pci.cpp diff --git a/src/kernel/drivers/IO/PCI/pci.h b/source/kernel/drivers/IO/PCI/pci.h similarity index 100% rename from src/kernel/drivers/IO/PCI/pci.h rename to source/kernel/drivers/IO/PCI/pci.h diff --git a/src/kernel/drivers/IO/ata/ataDevice.cpp b/source/kernel/drivers/IO/ata/ataDevice.cpp similarity index 100% rename from src/kernel/drivers/IO/ata/ataDevice.cpp rename to source/kernel/drivers/IO/ata/ataDevice.cpp diff --git a/src/kernel/drivers/IO/ata/ataDevice.h b/source/kernel/drivers/IO/ata/ataDevice.h similarity index 100% rename from src/kernel/drivers/IO/ata/ataDevice.h rename to source/kernel/drivers/IO/ata/ataDevice.h diff --git a/src/kernel/drivers/IO/atapi/atapiDevice.cpp b/source/kernel/drivers/IO/atapi/atapiDevice.cpp similarity index 100% rename from src/kernel/drivers/IO/atapi/atapiDevice.cpp rename to source/kernel/drivers/IO/atapi/atapiDevice.cpp diff --git a/src/kernel/drivers/IO/atapi/atapiDevice.h b/source/kernel/drivers/IO/atapi/atapiDevice.h similarity index 100% rename from src/kernel/drivers/IO/atapi/atapiDevice.h rename to source/kernel/drivers/IO/atapi/atapiDevice.h diff --git a/src/kernel/drivers/IO/io.cpp b/source/kernel/drivers/IO/io.cpp similarity index 100% rename from src/kernel/drivers/IO/io.cpp rename to source/kernel/drivers/IO/io.cpp diff --git a/src/kernel/drivers/IO/io.h b/source/kernel/drivers/IO/io.h similarity index 100% rename from src/kernel/drivers/IO/io.h rename to source/kernel/drivers/IO/io.h diff --git a/src/kernel/drivers/VGA/VBE.h b/source/kernel/drivers/VGA/VBE.h similarity index 100% rename from src/kernel/drivers/VGA/VBE.h rename to source/kernel/drivers/VGA/VBE.h diff --git a/src/kernel/drivers/VGA/colors.h b/source/kernel/drivers/VGA/colors.h similarity index 100% rename from src/kernel/drivers/VGA/colors.h rename to source/kernel/drivers/VGA/colors.h diff --git a/src/kernel/drivers/cmos/cmos.cpp b/source/kernel/drivers/cmos/cmos.cpp similarity index 100% rename from src/kernel/drivers/cmos/cmos.cpp rename to source/kernel/drivers/cmos/cmos.cpp diff --git a/src/kernel/filesystems/EXT2/SuperBlock.h b/source/kernel/filesystems/EXT2/SuperBlock.h similarity index 100% rename from src/kernel/filesystems/EXT2/SuperBlock.h rename to source/kernel/filesystems/EXT2/SuperBlock.h diff --git a/src/kernel/filesystems/FAT/BiosParameterBlock.h b/source/kernel/filesystems/FAT/BiosParameterBlock.h similarity index 100% rename from src/kernel/filesystems/FAT/BiosParameterBlock.h rename to source/kernel/filesystems/FAT/BiosParameterBlock.h diff --git a/src/kernel/filesystems/FAT/DirectoryEntry.h b/source/kernel/filesystems/FAT/DirectoryEntry.h similarity index 100% rename from src/kernel/filesystems/FAT/DirectoryEntry.h rename to source/kernel/filesystems/FAT/DirectoryEntry.h diff --git a/src/kernel/filesystems/FAT/ExtendBootRecord.h b/source/kernel/filesystems/FAT/ExtendBootRecord.h similarity index 100% rename from src/kernel/filesystems/FAT/ExtendBootRecord.h rename to source/kernel/filesystems/FAT/ExtendBootRecord.h diff --git a/src/kernel/gdt/gdt.s b/source/kernel/gdt/gdt.s similarity index 100% rename from src/kernel/gdt/gdt.s rename to source/kernel/gdt/gdt.s diff --git a/src/kernel/gdt/gdtc.cpp b/source/kernel/gdt/gdtc.cpp similarity index 100% rename from src/kernel/gdt/gdtc.cpp rename to source/kernel/gdt/gdtc.cpp diff --git a/src/kernel/gdt/gdtc.h b/source/kernel/gdt/gdtc.h similarity index 100% rename from src/kernel/gdt/gdtc.h rename to source/kernel/gdt/gdtc.h diff --git a/src/kernel/ide/ide.h b/source/kernel/ide/ide.h similarity index 100% rename from src/kernel/ide/ide.h rename to source/kernel/ide/ide.h diff --git a/src/kernel/ide/ideCommands.h b/source/kernel/ide/ideCommands.h similarity index 100% rename from src/kernel/ide/ideCommands.h rename to source/kernel/ide/ideCommands.h diff --git a/src/kernel/ide/sampleIDE.definitions.h b/source/kernel/ide/sampleIDE.definitions.h similarity index 100% rename from src/kernel/ide/sampleIDE.definitions.h rename to source/kernel/ide/sampleIDE.definitions.h diff --git a/src/kernel/ide/sampleIDE.h b/source/kernel/ide/sampleIDE.h similarity index 100% rename from src/kernel/ide/sampleIDE.h rename to source/kernel/ide/sampleIDE.h diff --git a/src/kernel/idt/idt.cpp b/source/kernel/idt/idt.cpp similarity index 100% rename from src/kernel/idt/idt.cpp rename to source/kernel/idt/idt.cpp diff --git a/src/kernel/idt/idt.h b/source/kernel/idt/idt.h similarity index 100% rename from src/kernel/idt/idt.h rename to source/kernel/idt/idt.h diff --git a/src/kernel/idt/idt.s b/source/kernel/idt/idt.s similarity index 100% rename from src/kernel/idt/idt.s rename to source/kernel/idt/idt.s diff --git a/src/kernel/idt/scancodes/set1.h b/source/kernel/idt/scancodes/set1.h similarity index 100% rename from src/kernel/idt/scancodes/set1.h rename to source/kernel/idt/scancodes/set1.h diff --git a/src/kernel/irq_table.s b/source/kernel/irq_table.s similarity index 100% rename from src/kernel/irq_table.s rename to source/kernel/irq_table.s diff --git a/src/kernel/irs_table.s b/source/kernel/irs_table.s similarity index 100% rename from src/kernel/irs_table.s rename to source/kernel/irs_table.s diff --git a/src/kernel/kernel.cpp b/source/kernel/kernel.cpp similarity index 100% rename from src/kernel/kernel.cpp rename to source/kernel/kernel.cpp diff --git a/src/kernel/kernel.h b/source/kernel/kernel.h similarity index 100% rename from src/kernel/kernel.h rename to source/kernel/kernel.h diff --git a/src/kernel/keyboard/keyboard.cpp b/source/kernel/keyboard/keyboard.cpp similarity index 100% rename from src/kernel/keyboard/keyboard.cpp rename to source/kernel/keyboard/keyboard.cpp diff --git a/src/kernel/keyboard/keyboard.h b/source/kernel/keyboard/keyboard.h similarity index 100% rename from src/kernel/keyboard/keyboard.h rename to source/kernel/keyboard/keyboard.h diff --git a/src/kernel/kstructures/bitmap.h b/source/kernel/kstructures/bitmap.h similarity index 100% rename from src/kernel/kstructures/bitmap.h rename to source/kernel/kstructures/bitmap.h diff --git a/src/kernel/linker.ld b/source/kernel/linker.ld similarity index 100% rename from src/kernel/linker.ld rename to source/kernel/linker.ld diff --git a/src/kernel/memory/PageDirectory.cpp b/source/kernel/memory/PageDirectory.cpp similarity index 100% rename from src/kernel/memory/PageDirectory.cpp rename to source/kernel/memory/PageDirectory.cpp diff --git a/src/kernel/memory/PageDirectory.h b/source/kernel/memory/PageDirectory.h similarity index 100% rename from src/kernel/memory/PageDirectory.h rename to source/kernel/memory/PageDirectory.h diff --git a/src/kernel/memory/memory.cpp b/source/kernel/memory/memory.cpp similarity index 100% rename from src/kernel/memory/memory.cpp rename to source/kernel/memory/memory.cpp diff --git a/src/kernel/memory/memory.h b/source/kernel/memory/memory.h similarity index 100% rename from src/kernel/memory/memory.h rename to source/kernel/memory/memory.h diff --git a/src/kernel/memory/memoryinfo.h b/source/kernel/memory/memoryinfo.h similarity index 100% rename from src/kernel/memory/memoryinfo.h rename to source/kernel/memory/memoryinfo.h diff --git a/src/kernel/memory/paging.s b/source/kernel/memory/paging.s similarity index 100% rename from src/kernel/memory/paging.s rename to source/kernel/memory/paging.s diff --git a/src/kernel/pci/pciDevice.cpp b/source/kernel/pci/pciDevice.cpp similarity index 100% rename from src/kernel/pci/pciDevice.cpp rename to source/kernel/pci/pciDevice.cpp diff --git a/src/kernel/pci/pciDevice.h b/source/kernel/pci/pciDevice.h similarity index 100% rename from src/kernel/pci/pciDevice.h rename to source/kernel/pci/pciDevice.h diff --git a/src/kernel/pic/pic.cpp b/source/kernel/pic/pic.cpp similarity index 100% rename from src/kernel/pic/pic.cpp rename to source/kernel/pic/pic.cpp diff --git a/src/kernel/pic/pic.h b/source/kernel/pic/pic.h similarity index 100% rename from src/kernel/pic/pic.h rename to source/kernel/pic/pic.h diff --git a/src/kernel/pit.cpp b/source/kernel/pit.cpp similarity index 100% rename from src/kernel/pit.cpp rename to source/kernel/pit.cpp diff --git a/src/kernel/pit.h b/source/kernel/pit.h similarity index 100% rename from src/kernel/pit.h rename to source/kernel/pit.h diff --git a/src/kernel/serial.h b/source/kernel/serial.h similarity index 100% rename from src/kernel/serial.h rename to source/kernel/serial.h diff --git a/src/kernel/serial/serial.cpp b/source/kernel/serial/serial.cpp similarity index 100% rename from src/kernel/serial/serial.cpp rename to source/kernel/serial/serial.cpp diff --git a/src/kernel/serial/serial.h b/source/kernel/serial/serial.h similarity index 100% rename from src/kernel/serial/serial.h rename to source/kernel/serial/serial.h diff --git a/src/kernel/sv-terminal/superVisorTerminal.cpp b/source/kernel/sv-terminal/superVisorTerminal.cpp similarity index 100% rename from src/kernel/sv-terminal/superVisorTerminal.cpp rename to source/kernel/sv-terminal/superVisorTerminal.cpp diff --git a/src/kernel/sv-terminal/superVisorTerminal.h b/source/kernel/sv-terminal/superVisorTerminal.h similarity index 100% rename from src/kernel/sv-terminal/superVisorTerminal.h rename to source/kernel/sv-terminal/superVisorTerminal.h diff --git a/src/kernel/time.cpp b/source/kernel/time.cpp similarity index 100% rename from src/kernel/time.cpp rename to source/kernel/time.cpp diff --git a/src/kernel/time.h b/source/kernel/time.h similarity index 100% rename from src/kernel/time.h rename to source/kernel/time.h diff --git a/src/kernel/timer.cpp b/source/kernel/timer.cpp similarity index 100% rename from src/kernel/timer.cpp rename to source/kernel/timer.cpp diff --git a/src/kernel/timer.h b/source/kernel/timer.h similarity index 100% rename from src/kernel/timer.h rename to source/kernel/timer.h diff --git a/src/kernel/tty/kterm.cpp b/source/kernel/tty/kterm.cpp similarity index 100% rename from src/kernel/tty/kterm.cpp rename to source/kernel/tty/kterm.cpp diff --git a/src/kernel/tty/kterm.h b/source/kernel/tty/kterm.h similarity index 100% rename from src/kernel/tty/kterm.h rename to source/kernel/tty/kterm.h diff --git a/src/kernel/vfs/File.h b/source/kernel/vfs/File.h similarity index 100% rename from src/kernel/vfs/File.h rename to source/kernel/vfs/File.h diff --git a/src/kernel/vfs/VFS.cpp b/source/kernel/vfs/VFS.cpp similarity index 100% rename from src/kernel/vfs/VFS.cpp rename to source/kernel/vfs/VFS.cpp diff --git a/src/kernel/vfs/VFS.h b/source/kernel/vfs/VFS.h similarity index 100% rename from src/kernel/vfs/VFS.h rename to source/kernel/vfs/VFS.h diff --git a/src/libc/include/mem.h b/source/libc/include/mem.h similarity index 100% rename from src/libc/include/mem.h rename to source/libc/include/mem.h diff --git a/src/libc/include/string.c b/source/libc/include/string.c similarity index 100% rename from src/libc/include/string.c rename to source/libc/include/string.c diff --git a/src/libc/include/string.h b/source/libc/include/string.h similarity index 100% rename from src/libc/include/string.h rename to source/libc/include/string.h -- 2.39.5 From 891085e151966f1b21363e80139501137622eb88 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 2 Feb 2023 14:59:42 +0100 Subject: [PATCH 084/115] Successfully able to create a disk-image file - Created a scripts folder - Written instructions on how to create the disk image - Working on a python build script that executes all other scripts The scripts folder should contain scripts to build a full installation of our operating system. Scripts like creating a filesystem should be found here --- Makefile | 3 ++ scripts/build.py | 25 ++++++++++++++ scripts/create-filesystem.sh | 64 ++++++++++++++++++++++++++++++++++++ scripts/test.sh | 5 +++ 4 files changed, 97 insertions(+) create mode 100755 scripts/build.py create mode 100644 scripts/create-filesystem.sh create mode 100755 scripts/test.sh diff --git a/Makefile b/Makefile index 31eb6d9..fbdbff8 100644 --- a/Makefile +++ b/Makefile @@ -60,6 +60,9 @@ test: test_iso: $(EMULATOR) -boot d -cdrom $(BUILD_DIR)/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo +test_disk: + $(EMULATOR) -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo + build_kernel: $(OBJ_LINK_LIST) $(CC) -T $(SRC_DIR)/kernel/linker.ld -o $(BUILD_DIR)/myos.bin \ diff --git a/scripts/build.py b/scripts/build.py new file mode 100755 index 0000000..cd06dc4 --- /dev/null +++ b/scripts/build.py @@ -0,0 +1,25 @@ +#!/usr/bin/python3 +import os +import subprocess + + +print("Building BarinkOS") + + +# list and run build scripts +print("Running build-scripts") +os.chdir("scripts") + +scripts=os.listdir() +currentScript=os.path.basename(__file__) + +if currentScript in scripts: + scripts.remove(currentScript) + + +for script in scripts: + print(os.getcwd()) + print("Running:" + script) + subprocess.call(script, cwd=os.getcwd()) + +os.chdir("..") \ No newline at end of file diff --git a/scripts/create-filesystem.sh b/scripts/create-filesystem.sh new file mode 100644 index 0000000..45dc117 --- /dev/null +++ b/scripts/create-filesystem.sh @@ -0,0 +1,64 @@ +#!/bin/bash +# +# How to build a boot image +# NOTE: This script cant run properly yet +# Things described here should be done manually for now +# +# COPYRIGHT © Nigel Barink 2023 +# + +echo "Building a FAT16 filesystem" + + +su + +# dd if=/dev/zero of=diks.img bs=512 count=131072 +# fdisk disk.img +# Use the following options in fdisk (Format Disk Tool) +# We want to create a MBR (NOT GPT) Partition table containing 1 logical disk +# with a primary FAT16 partition marked bootable + +#OPTIONs + +# Create new DOS disklabel +# o +# Create new partition +# n +# Choose Primary as partition type +# p +# hit enter to choose default for the other options + +# Mark partition 1 as bootable +# a + +# Change partition type to FAT16 +# t +# Choose Partition 1 +# 1 +# Choose HEX 6 for FAT16 +# 6 + +# Sync and write changes to disk +# w + +# Create a "block" device from the disk.img +# losetup /dev/loop9 disk.img + +# Format the partition on the disk as FAT16 +# mkdosfs -F16 /dev/loop9 + +# Mount the disk to a folder on our dev machine +# mount /dev/loop9 /mnt + +# Install the grub bootloader onto the disk +# grub-install --no-floppy --modules="normal multiboot" /dev/loop9 --target=i386-pc --boot-directory=/mnt/boot --force + +# copy the necessary OS files +# cp root/boot/myos.bin /mnt/boot/myos.bin +# cp root/boot/grub/grub.cfg /mnt/boot/grub/grub.cfg + +# Unmount the device +# umount /mnt + +# Destroy the loop device +# losetup -d /dev/loop9 diff --git a/scripts/test.sh b/scripts/test.sh new file mode 100755 index 0000000..cb84bbe --- /dev/null +++ b/scripts/test.sh @@ -0,0 +1,5 @@ +#!/bin/bash +start=`date +%s` +end=`date +%s` +echo That took $((end-start)) seconds +date +"%c" -d195440409 -- 2.39.5 From 749f2aa492219fd5c00ac6ed5da0af39f7e10ba9 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 3 Feb 2023 20:01:31 +0100 Subject: [PATCH 085/115] Updating folders name's (1) This should help merging into dev branch --- Makefile | 10 +++++----- source/kernel/boot.s | 2 +- source/kernel/{bootloader => boot}/multiboot.h | 0 source/kernel/bootcheck.h | 2 +- source/kernel/drivers/ACPI/rsdp.h | 2 +- source/kernel/drivers/IO/PCI/pci.h | 2 +- source/kernel/drivers/IO/ata/ataDevice.h | 4 ++-- source/kernel/drivers/IO/atapi/atapiDevice.h | 4 ++-- source/kernel/{ => drivers}/ide/ide.h | 2 +- source/kernel/{ => drivers}/ide/ideCommands.h | 0 .../{ => drivers}/ide/sampleIDE.definitions.h | 0 source/kernel/{ => drivers}/ide/sampleIDE.h | 2 +- source/kernel/{ => drivers}/pci/pciDevice.cpp | 0 source/kernel/{ => drivers}/pci/pciDevice.h | 0 source/kernel/{ => drivers}/pic/pic.cpp | 0 source/kernel/{ => drivers}/pic/pic.h | 2 +- source/kernel/{ => drivers/pit}/pit.cpp | 2 +- source/kernel/{ => drivers/pit}/pit.h | 2 +- .../EXT2/SuperBlock.h | 0 .../FAT/BiosParameterBlock.h | 0 .../FAT/DirectoryEntry.h | 0 .../FAT/ExtendBootRecord.h | 0 source/kernel/{ => interrupts}/idt/idt.cpp | 4 ++-- source/kernel/{ => interrupts}/idt/idt.h | 6 +++--- source/kernel/{ => interrupts}/idt/idt.s | 0 .../kernel/{ => interrupts}/idt/scancodes/set1.h | 0 source/kernel/kernel.h | 16 ++++++++-------- source/kernel/memory/memory.h | 4 ++-- source/kernel/sv-terminal/superVisorTerminal.h | 2 +- source/kernel/tty/kterm.h | 2 +- source/{libc => lib}/include/mem.h | 0 source/{libc => lib}/include/string.c | 0 source/{libc => lib}/include/string.h | 0 33 files changed, 35 insertions(+), 35 deletions(-) rename source/kernel/{bootloader => boot}/multiboot.h (100%) rename source/kernel/{ => drivers}/ide/ide.h (98%) rename source/kernel/{ => drivers}/ide/ideCommands.h (100%) rename source/kernel/{ => drivers}/ide/sampleIDE.definitions.h (100%) rename source/kernel/{ => drivers}/ide/sampleIDE.h (99%) rename source/kernel/{ => drivers}/pci/pciDevice.cpp (100%) rename source/kernel/{ => drivers}/pci/pciDevice.h (100%) rename source/kernel/{ => drivers}/pic/pic.cpp (100%) rename source/kernel/{ => drivers}/pic/pic.h (95%) rename source/kernel/{ => drivers/pit}/pit.cpp (96%) rename source/kernel/{ => drivers/pit}/pit.h (89%) rename source/kernel/{filesystems => filesystem}/EXT2/SuperBlock.h (100%) rename source/kernel/{filesystems => filesystem}/FAT/BiosParameterBlock.h (100%) rename source/kernel/{filesystems => filesystem}/FAT/DirectoryEntry.h (100%) rename source/kernel/{filesystems => filesystem}/FAT/ExtendBootRecord.h (100%) rename source/kernel/{ => interrupts}/idt/idt.cpp (99%) rename source/kernel/{ => interrupts}/idt/idt.h (94%) rename source/kernel/{ => interrupts}/idt/idt.s (100%) rename source/kernel/{ => interrupts}/idt/scancodes/set1.h (100%) rename source/{libc => lib}/include/mem.h (100%) rename source/{libc => lib}/include/string.c (100%) rename source/{libc => lib}/include/string.h (100%) diff --git a/Makefile b/Makefile index fbdbff8..22df814 100644 --- a/Makefile +++ b/Makefile @@ -95,17 +95,17 @@ $(BUILD_DIR)/io.o: $(BUILD_DIR)/idt.o: - $(CPP) -c $(SRC_DIR)/kernel/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/interrupts/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/gdtc.o: $(CPP) -c $(SRC_DIR)/kernel/gdt/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pic.o: - $(CPP) -c $(SRC_DIR)/kernel/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/string.o: - $(CC) -c $(SRC_DIR)/libc/include/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 + $(CC) -c $(SRC_DIR)/lib/include/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 $(BUILD_DIR)/PhysicalMemoryManager.o: $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -114,7 +114,7 @@ $(BUILD_DIR)/pci.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/IO/PCI/pci.cpp -o $(BUILD_DIR)/pci.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pcidevice.o: - $(CPP) -c $(SRC_DIR)/kernel/pci/pciDevice.cpp -o $(BUILD_DIR)/pcidevice.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/pci/pciDevice.cpp -o $(BUILD_DIR)/pcidevice.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/atapiDevice.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/IO/atapi/atapiDevice.cpp -o $(BUILD_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -127,7 +127,7 @@ $(BUILD_DIR)/rsdp.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/ACPI/rsdp.cpp -o $(BUILD_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/pit.o: - $(CPP) -c $(SRC_DIR)/kernel/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/pit/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/keyboard.o: diff --git a/source/kernel/boot.s b/source/kernel/boot.s index 3015e8d..7cccd17 100644 --- a/source/kernel/boot.s +++ b/source/kernel/boot.s @@ -24,7 +24,7 @@ stack_top: .include "./source/kernel/gdt/gdt.s" .include "./source/kernel/irs_table.s" .include "./source/kernel/irq_table.s" -.include "./source/kernel/idt/idt.s" +.include "./source/kernel/interrupts/idt/idt.s" .include "./source/kernel/memory/paging.s" diff --git a/source/kernel/bootloader/multiboot.h b/source/kernel/boot/multiboot.h similarity index 100% rename from source/kernel/bootloader/multiboot.h rename to source/kernel/boot/multiboot.h diff --git a/source/kernel/bootcheck.h b/source/kernel/bootcheck.h index 62765a5..70c0354 100644 --- a/source/kernel/bootcheck.h +++ b/source/kernel/bootcheck.h @@ -1,5 +1,5 @@ #pragma once -#include "bootloader/multiboot.h" +#include "boot/multiboot.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) #include "tty/kterm.h" diff --git a/source/kernel/drivers/ACPI/rsdp.h b/source/kernel/drivers/ACPI/rsdp.h index 1bac440..cb3ac24 100644 --- a/source/kernel/drivers/ACPI/rsdp.h +++ b/source/kernel/drivers/ACPI/rsdp.h @@ -1,7 +1,7 @@ #pragma once #include #include "./../../tty/kterm.h" -#include "../../../libc/include/mem.h" +#include "../../../lib/include/mem.h" struct RSDPTR { char signature[8]; uint8_t Checksum ; diff --git a/source/kernel/drivers/IO/PCI/pci.h b/source/kernel/drivers/IO/PCI/pci.h index 9f2bba2..d9a86f4 100644 --- a/source/kernel/drivers/IO/PCI/pci.h +++ b/source/kernel/drivers/IO/PCI/pci.h @@ -2,7 +2,7 @@ #include #include "../io.h" #include "../../../tty/kterm.h" -#include "../../../pci/pciDevice.h" +#include "../../pci/pciDevice.h" // Configuration Space Access Mechanism #1 #define CONFIG_ADDRESS 0xCF8 // Configuration adress that is to be accessed diff --git a/source/kernel/drivers/IO/ata/ataDevice.h b/source/kernel/drivers/IO/ata/ataDevice.h index 89bfe7d..ab8822b 100644 --- a/source/kernel/drivers/IO/ata/ataDevice.h +++ b/source/kernel/drivers/IO/ata/ataDevice.h @@ -1,8 +1,8 @@ #pragma once #include #include "../io.h" -#include "../../../ide/ideCommands.h" -#include "../../../ide/sampleIDE.definitions.h" +#include "../../ide/ideCommands.h" +#include "../../ide/sampleIDE.definitions.h" #include "../../../tty/kterm.h" diff --git a/source/kernel/drivers/IO/atapi/atapiDevice.h b/source/kernel/drivers/IO/atapi/atapiDevice.h index 37d516e..ba06167 100644 --- a/source/kernel/drivers/IO/atapi/atapiDevice.h +++ b/source/kernel/drivers/IO/atapi/atapiDevice.h @@ -1,8 +1,8 @@ #pragma once #include #include "../io.h" -#include "../../../ide/ideCommands.h" -#include "../../../ide/sampleIDE.definitions.h" +#include "../../ide/ideCommands.h" +#include "../../ide/sampleIDE.definitions.h" #include "../../../tty/kterm.h" diff --git a/source/kernel/ide/ide.h b/source/kernel/drivers/ide/ide.h similarity index 98% rename from source/kernel/ide/ide.h rename to source/kernel/drivers/ide/ide.h index ce2ebc1..516f7c7 100644 --- a/source/kernel/ide/ide.h +++ b/source/kernel/drivers/ide/ide.h @@ -1,7 +1,7 @@ #pragma once #include #include "../pci/pciDevice.h" -#include "../tty/kterm.h" +#include "../../tty/kterm.h" #include "ideCommands.h" #include "sampleIDE.h" diff --git a/source/kernel/ide/ideCommands.h b/source/kernel/drivers/ide/ideCommands.h similarity index 100% rename from source/kernel/ide/ideCommands.h rename to source/kernel/drivers/ide/ideCommands.h diff --git a/source/kernel/ide/sampleIDE.definitions.h b/source/kernel/drivers/ide/sampleIDE.definitions.h similarity index 100% rename from source/kernel/ide/sampleIDE.definitions.h rename to source/kernel/drivers/ide/sampleIDE.definitions.h diff --git a/source/kernel/ide/sampleIDE.h b/source/kernel/drivers/ide/sampleIDE.h similarity index 99% rename from source/kernel/ide/sampleIDE.h rename to source/kernel/drivers/ide/sampleIDE.h index 5e805e3..ad978b5 100644 --- a/source/kernel/ide/sampleIDE.h +++ b/source/kernel/drivers/ide/sampleIDE.h @@ -1,6 +1,6 @@ #pragma once #include -#include "../tty/kterm.h" +#include "../../tty/kterm.h" #include "sampleIDE.definitions.h" #include "ideCommands.h" diff --git a/source/kernel/pci/pciDevice.cpp b/source/kernel/drivers/pci/pciDevice.cpp similarity index 100% rename from source/kernel/pci/pciDevice.cpp rename to source/kernel/drivers/pci/pciDevice.cpp diff --git a/source/kernel/pci/pciDevice.h b/source/kernel/drivers/pci/pciDevice.h similarity index 100% rename from source/kernel/pci/pciDevice.h rename to source/kernel/drivers/pci/pciDevice.h diff --git a/source/kernel/pic/pic.cpp b/source/kernel/drivers/pic/pic.cpp similarity index 100% rename from source/kernel/pic/pic.cpp rename to source/kernel/drivers/pic/pic.cpp diff --git a/source/kernel/pic/pic.h b/source/kernel/drivers/pic/pic.h similarity index 95% rename from source/kernel/pic/pic.h rename to source/kernel/drivers/pic/pic.h index fa06d3d..9f05d73 100644 --- a/source/kernel/pic/pic.h +++ b/source/kernel/drivers/pic/pic.h @@ -1,5 +1,5 @@ #pragma once -#include "../drivers/IO/io.h" +#include "../IO/io.h" #define PIC1 0x20 /* IO base address for master PIC */ #define PIC2 0xA0 /* IO base address for slave PIC */ diff --git a/source/kernel/pit.cpp b/source/kernel/drivers/pit/pit.cpp similarity index 96% rename from source/kernel/pit.cpp rename to source/kernel/drivers/pit/pit.cpp index d2b6527..d345517 100644 --- a/source/kernel/pit.cpp +++ b/source/kernel/drivers/pit/pit.cpp @@ -1,5 +1,5 @@ #include "pit.h" -#include "tty/kterm.h" +#include "../../tty/kterm.h" uint32_t pit_tick = 0; diff --git a/source/kernel/pit.h b/source/kernel/drivers/pit/pit.h similarity index 89% rename from source/kernel/pit.h rename to source/kernel/drivers/pit/pit.h index 0bc988f..268937a 100644 --- a/source/kernel/pit.h +++ b/source/kernel/drivers/pit/pit.h @@ -1,6 +1,6 @@ #pragma once #include -#include "drivers/IO/io.h" +#include "../IO/io.h" #define PIT_DATA_0 0x40 #define PIT_DATA_1 0x41 #define PIT_DATA_2 0x42 diff --git a/source/kernel/filesystems/EXT2/SuperBlock.h b/source/kernel/filesystem/EXT2/SuperBlock.h similarity index 100% rename from source/kernel/filesystems/EXT2/SuperBlock.h rename to source/kernel/filesystem/EXT2/SuperBlock.h diff --git a/source/kernel/filesystems/FAT/BiosParameterBlock.h b/source/kernel/filesystem/FAT/BiosParameterBlock.h similarity index 100% rename from source/kernel/filesystems/FAT/BiosParameterBlock.h rename to source/kernel/filesystem/FAT/BiosParameterBlock.h diff --git a/source/kernel/filesystems/FAT/DirectoryEntry.h b/source/kernel/filesystem/FAT/DirectoryEntry.h similarity index 100% rename from source/kernel/filesystems/FAT/DirectoryEntry.h rename to source/kernel/filesystem/FAT/DirectoryEntry.h diff --git a/source/kernel/filesystems/FAT/ExtendBootRecord.h b/source/kernel/filesystem/FAT/ExtendBootRecord.h similarity index 100% rename from source/kernel/filesystems/FAT/ExtendBootRecord.h rename to source/kernel/filesystem/FAT/ExtendBootRecord.h diff --git a/source/kernel/idt/idt.cpp b/source/kernel/interrupts/idt/idt.cpp similarity index 99% rename from source/kernel/idt/idt.cpp rename to source/kernel/interrupts/idt/idt.cpp index 393902b..6184dd8 100644 --- a/source/kernel/idt/idt.cpp +++ b/source/kernel/interrupts/idt/idt.cpp @@ -1,6 +1,6 @@ #include "idt.h" -#include "../pit.h" -#include "../keyboard/keyboard.h" +#include "../../drivers/pit/pit.h" +#include "../../keyboard/keyboard.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; diff --git a/source/kernel/idt/idt.h b/source/kernel/interrupts/idt/idt.h similarity index 94% rename from source/kernel/idt/idt.h rename to source/kernel/interrupts/idt/idt.h index 48c026c..b09d7c6 100644 --- a/source/kernel/idt/idt.h +++ b/source/kernel/interrupts/idt/idt.h @@ -2,10 +2,10 @@ #include "stdint.h" #include "stddef.h" -#include "../drivers/VGA/colors.h" -#include "../pic/pic.h" +#include "../../drivers/VGA/colors.h" +#include "../../drivers/pic/pic.h" -#include "../tty/kterm.h" +#include "../../tty/kterm.h" extern "C" { diff --git a/source/kernel/idt/idt.s b/source/kernel/interrupts/idt/idt.s similarity index 100% rename from source/kernel/idt/idt.s rename to source/kernel/interrupts/idt/idt.s diff --git a/source/kernel/idt/scancodes/set1.h b/source/kernel/interrupts/idt/scancodes/set1.h similarity index 100% rename from source/kernel/idt/scancodes/set1.h rename to source/kernel/interrupts/idt/scancodes/set1.h diff --git a/source/kernel/kernel.h b/source/kernel/kernel.h index ac164a3..30285b9 100644 --- a/source/kernel/kernel.h +++ b/source/kernel/kernel.h @@ -1,14 +1,14 @@ #pragma once extern "C" { - #include "../libc/include/string.h" + #include "../lib/include/string.h" } #include "drivers/VGA/VBE.h" #include "tty/kterm.h" -#include "./bootloader/multiboot.h" +#include "./boot/multiboot.h" #include "bootinfo.h" #include "memory/memory.h" @@ -16,21 +16,21 @@ extern "C" #include "bootcheck.h" #include "gdt/gdtc.h" -#include "idt/idt.h" +#include "interrupts/idt/idt.h" #include "drivers/IO/io.h" #include "time.h" -#include "pit.h" +#include "drivers/pit/pit.h" #include "cpu.h" #include "serial.h" #include "drivers/IO/PCI/pci.h" -#include "ide/ide.h" +#include "drivers/ide/ide.h" #include "./drivers/IO/ata/ataDevice.h" #include "./PartitionTable/MBR/MasterBootRecord.h" -#include "./filesystems/FAT/BiosParameterBlock.h" -#include "./filesystems/FAT/ExtendBootRecord.h" -#include "./filesystems/FAT/DirectoryEntry.h" +#include "./filesystem/FAT/BiosParameterBlock.h" +#include "./filesystem/FAT/ExtendBootRecord.h" +#include "./filesystem/FAT/DirectoryEntry.h" #include "drivers/ACPI/rsdp.h" diff --git a/source/kernel/memory/memory.h b/source/kernel/memory/memory.h index 2d0d309..9f344b1 100644 --- a/source/kernel/memory/memory.h +++ b/source/kernel/memory/memory.h @@ -3,9 +3,9 @@ #include #include "memoryinfo.h" -#include "../bootloader/multiboot.h" +#include "../boot/multiboot.h" #include "../tty/kterm.h" -#include "../../libc/include/mem.h" +#include "../../lib/include/mem.h" #include "../kstructures/bitmap.h" #define BLOCK_SIZE 4092 diff --git a/source/kernel/sv-terminal/superVisorTerminal.h b/source/kernel/sv-terminal/superVisorTerminal.h index 5d4519d..752f289 100644 --- a/source/kernel/sv-terminal/superVisorTerminal.h +++ b/source/kernel/sv-terminal/superVisorTerminal.h @@ -1,7 +1,7 @@ #pragma once #include "../tty/kterm.h" #include "../time.h" -#include "../pit.h" +#include "../drivers/pit/pit.h" #include "../keyboard/keyboard.h" #include "../memory/memory.h" #include "../bootinfo.h" diff --git a/source/kernel/tty/kterm.h b/source/kernel/tty/kterm.h index 0753294..71e45c4 100644 --- a/source/kernel/tty/kterm.h +++ b/source/kernel/tty/kterm.h @@ -8,7 +8,7 @@ #include "../drivers/IO/io.h" extern "C"{ - #include "./../../libc/include/string.h" + #include "./../../lib/include/string.h" } void kterm_init(); diff --git a/source/libc/include/mem.h b/source/lib/include/mem.h similarity index 100% rename from source/libc/include/mem.h rename to source/lib/include/mem.h diff --git a/source/libc/include/string.c b/source/lib/include/string.c similarity index 100% rename from source/libc/include/string.c rename to source/lib/include/string.c diff --git a/source/libc/include/string.h b/source/lib/include/string.h similarity index 100% rename from source/libc/include/string.h rename to source/lib/include/string.h -- 2.39.5 From 520104a43a6a621507755c55208b809df926cad3 Mon Sep 17 00:00:00 2001 From: Nigel Date: Wed, 8 Feb 2023 14:07:44 +0100 Subject: [PATCH 086/115] Moved reading file from disk to its own super visor terminal command - Updated gdt assembly - Updated Interrupt service request handlers - Improved virtual memory manager - NOTE: we're dependent on identity mappings for the heap to work --- Makefile | 12 +- features.md | 2 +- source/kernel/boot/boot.s | 2 +- source/kernel/drivers/acpi/acpi.cpp | 14 + source/kernel/drivers/acpi/acpi.h | 13 + source/kernel/drivers/acpi/rsdp.h | 2 - source/kernel/drivers/ide/sampleIDE.h | 4 +- source/kernel/drivers/pci/pci.cpp | 6 +- source/kernel/drivers/pci/pci.h | 2 - source/kernel/gdt/gdt.s | 19 -- source/kernel/gdt/gdtc.cpp | 58 ---- source/kernel/gdt/gdtc.h | 27 -- source/kernel/interrupts/idt/idt.cpp | 179 +++++------ source/kernel/interrupts/idt/idt.h | 2 +- source/kernel/irs_table.s | 286 ++++-------------- source/kernel/kernel.cpp | 229 +++----------- source/kernel/kernel.h | 39 +-- source/kernel/memory/KernelHeap.cpp | 18 +- source/kernel/memory/VirtualMemoryManager.cpp | 53 +++- source/kernel/memory/VirtualMemoryManager.h | 2 +- source/kernel/memory/gdt/gdtc.cpp | 21 +- source/kernel/memory/gdt/gdtc.h | 11 +- .../supervisorterminal/superVisorTerminal.cpp | 174 ++++++++++- 23 files changed, 474 insertions(+), 701 deletions(-) create mode 100644 source/kernel/drivers/acpi/acpi.cpp create mode 100644 source/kernel/drivers/acpi/acpi.h delete mode 100644 source/kernel/gdt/gdt.s delete mode 100644 source/kernel/gdt/gdtc.cpp delete mode 100644 source/kernel/gdt/gdtc.h diff --git a/Makefile b/Makefile index 24dba1d..e4bb2ff 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o SRC_DIR = source BUILD_DIR = build @@ -36,12 +36,12 @@ run: all virtualboxvm --startvm "BarinkOS_test" debug: all objcopy --only-keep-debug build/myos.bin kernel.sym - $(EMULATOR) -cdrom build/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -s -d int + $(EMULATOR) -cdrom build/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -s -d int -no-shutdown -no-reboot test: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo + $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-shutdown -no-reboot test_iso: - $(EMULATOR) -boot d -cdrom $(BUILD_DIR)/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo + $(EMULATOR) -boot d -cdrom $(BUILD_DIR)/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-reboot -no-shutdown test_disk: $(EMULATOR) -boot d -drive format=raw,file=build/disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo @@ -97,6 +97,9 @@ $(BUILD_DIR)/ataDevice.o: $(BUILD_DIR)/rsdp.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/acpi/rsdp.cpp -o $(BUILD_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti +$(BUILD_DIR)/acpi.o: + $(CPP) -c $(SRC_DIR)/kernel/drivers/acpi/acpi.cpp -o $(BUILD_DIR)/acpi.o $(CFLAGS) -fno-exceptions -fno-rtti + $(BUILD_DIR)/pit.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/pit/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -126,6 +129,7 @@ $(BUILD_DIR)/cpu.o: $(CPP) -c $(SRC_DIR)/kernel/cpu.cpp -o $(BUILD_DIR)/cpu.o $(CFLAGS) -fno-exceptions -fno-rtti + # Assembly -> Object files $(BUILD_DIR)/boot.o: $(AS) $(SRC_DIR)/kernel/boot/boot.s -o $(BUILD_DIR)/boot.o diff --git a/features.md b/features.md index 1d33930..577e666 100644 --- a/features.md +++ b/features.md @@ -29,7 +29,6 @@ USTAR Filesystem ( For its simplicity this is very likely the first filesystem the OS is going to support) \ ACPI support ( Or some other basic way to support shutdown, reboot and possibly hibernation ) \ ATAPI support \ - Keyboard support ( P/S2 Keyboard) \ Memory Management (MMU) Hardware Management system @@ -49,3 +48,4 @@ Basic Window server/client \ EXT2 Filesystem USTAR Filesystem \ + FAT16 Filesystem \ diff --git a/source/kernel/boot/boot.s b/source/kernel/boot/boot.s index 18e50ca..6013482 100644 --- a/source/kernel/boot/boot.s +++ b/source/kernel/boot/boot.s @@ -83,7 +83,7 @@ isPaging: call prekernelSetup # Unmap the identity mapping as it is now unnecessary - movl $0, boot_page_directory + 0 + # movl $0, boot_page_directory + 0 # Reload cr3 to force tlb flush movl %cr3, %ecx diff --git a/source/kernel/drivers/acpi/acpi.cpp b/source/kernel/drivers/acpi/acpi.cpp new file mode 100644 index 0000000..6366d6f --- /dev/null +++ b/source/kernel/drivers/acpi/acpi.cpp @@ -0,0 +1,14 @@ +#include "acpi.h" +RSDPTR* ACPI::rsd_ptr; +RSDT* ACPI::rsd_table; + + + +void ACPI::initialize(){ + + // Find the Root System Description Pointer + ACPI::rsd_ptr = FindRSD(); + printRSD(rsd_ptr); + // Get the Root System Description Table + ACPI::rsd_table = getRSDT(rsd_ptr); +} \ No newline at end of file diff --git a/source/kernel/drivers/acpi/acpi.h b/source/kernel/drivers/acpi/acpi.h new file mode 100644 index 0000000..66fe8d9 --- /dev/null +++ b/source/kernel/drivers/acpi/acpi.h @@ -0,0 +1,13 @@ +#pragma once +#include "rsdp.h" +class ACPI { + public: + static void initialize(); + + // In the future ACPI might start + // doing more systems initialization + + private: + static RSDPTR* rsd_ptr; + static RSDT* rsd_table; +}; \ No newline at end of file diff --git a/source/kernel/drivers/acpi/rsdp.h b/source/kernel/drivers/acpi/rsdp.h index 925b50d..eb5a87a 100644 --- a/source/kernel/drivers/acpi/rsdp.h +++ b/source/kernel/drivers/acpi/rsdp.h @@ -27,8 +27,6 @@ struct RSDT{ uint32_t PointerToSDT[]; // Length of array : (header.Length - sizeof(header))/ 4 }__attribute__((packed)); - -//NOTE: only scans EBDA enough to find RSD PTR in QEMU RSDPTR* FindRSD(); void printRSD(RSDPTR* rsd); diff --git a/source/kernel/drivers/ide/sampleIDE.h b/source/kernel/drivers/ide/sampleIDE.h index 3976ac3..5be1cf9 100644 --- a/source/kernel/drivers/ide/sampleIDE.h +++ b/source/kernel/drivers/ide/sampleIDE.h @@ -155,7 +155,7 @@ inline void init_IDE( uint32_t BAR0, uint32_t BAR1,uint32_t BAR2, uint32_t BAR3, // 3- Detect ATA-ATAPI Devices: -void DetectDevices(){ +inline void DetectDevices(){ int i, j, k, count = 0; for (i = 0; i < 2; i++) @@ -228,7 +228,7 @@ void DetectDevices(){ } -void Detect_IO_Ports(uint32_t BAR0, uint32_t BAR1,uint32_t BAR2, uint32_t BAR3, uint32_t BAR4){ +inline void Detect_IO_Ports(uint32_t BAR0, uint32_t BAR1,uint32_t BAR2, uint32_t BAR3, uint32_t BAR4){ // 1 Detect I/O Ports which interface an IDE Controller // Based on the implementation within serenity diff --git a/source/kernel/drivers/pci/pci.cpp b/source/kernel/drivers/pci/pci.cpp index c7ba0ac..e45314c 100644 --- a/source/kernel/drivers/pci/pci.cpp +++ b/source/kernel/drivers/pci/pci.cpp @@ -185,7 +185,11 @@ void PrintPCIDeviceInfo (PCIBusAddress& PCIDeviceAddress) } void PCI_Enumerate(){ - int devicesFound = 0; + + + int devicesFound = 0; + + printf("Start finding devices, Found: %d devices"); // loop through all possible busses, devices and their functions; for( int bus = 0 ; bus < 256 ; bus++) { diff --git a/source/kernel/drivers/pci/pci.h b/source/kernel/drivers/pci/pci.h index 272e0f4..7e60de4 100644 --- a/source/kernel/drivers/pci/pci.h +++ b/source/kernel/drivers/pci/pci.h @@ -10,8 +10,6 @@ extern const char* ClassCodeTable [0x13]; - - // Note: this could be used to make the api for receiving PCI class codes a bit // nicer. struct ClassCodes { diff --git a/source/kernel/gdt/gdt.s b/source/kernel/gdt/gdt.s deleted file mode 100644 index 95859c2..0000000 --- a/source/kernel/gdt/gdt.s +++ /dev/null @@ -1,19 +0,0 @@ -.global LoadGlobalDescriptorTable - - LoadGlobalDescriptorTable: - lgdt gdtDescriptor - - movw $16, %ax - movw %ax, %ds - movw %ax, %es - movw %ax, %fs - movw %ax, %gs - movw %ax, %ss - - jmp $8,$flush - - flush: - ret - - - diff --git a/source/kernel/gdt/gdtc.cpp b/source/kernel/gdt/gdtc.cpp deleted file mode 100644 index 5547dee..0000000 --- a/source/kernel/gdt/gdtc.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "gdtc.h" -#include "../terminal/kterm.h" - -#define NULL_SEGMENT 0 -#define KERNEL_CODE_SEGMENT 1 -#define KERNEL_DATA_SEGMENT 2 -#define USER_CODE_SEGMENT 3 -#define USER_DATA_SEGMENT 4 - -SegmentDescriptor GlobalDescriptorTable[5]; -GlobalDescriptorTableDescriptor gdtDescriptor; - -void add_descriptor(int which , unsigned long base, unsigned long limit, unsigned char access, unsigned char granularity ){ - GlobalDescriptorTable[which].base_low = (base & 0xFFFF ); - GlobalDescriptorTable[which].base_middle = (base >> 6) & 0xFF; - GlobalDescriptorTable[which].base_high = (base >> 24) & 0xFF; - - GlobalDescriptorTable[which].limit_low = (limit & 0xFFFF); - GlobalDescriptorTable[which].granularity = ((limit >> 16) & 0x0F); - - GlobalDescriptorTable[which].granularity |= (granularity & 0xF0); - GlobalDescriptorTable[which].access = access; - - -} - - - - -void initGDT(){ - -#ifdef __VERBOSE__ - printf("Init GDT!\n"); -#endif - // NULL segment - add_descriptor(NULL_SEGMENT, 0,0,0,0); - - // Kernel Code Segment - add_descriptor(KERNEL_CODE_SEGMENT, 0, 0xFFFFFFFF, 0x9A, 0xCF); - - // Kernel Data Segment - add_descriptor(KERNEL_DATA_SEGMENT, 0, 0xFFFFFFFF, 0x92, 0xCF); - - // User Code Segment - // TODO: - - // User Data Segement - // TODO: - - // init Gdt Descriptor - gdtDescriptor.limit = ((sizeof(SegmentDescriptor ) * 5 ) - 1); - gdtDescriptor.base = (unsigned int) &GlobalDescriptorTable; - - - - LoadGlobalDescriptorTable(); - -} diff --git a/source/kernel/gdt/gdtc.h b/source/kernel/gdt/gdtc.h deleted file mode 100644 index 548bc5e..0000000 --- a/source/kernel/gdt/gdtc.h +++ /dev/null @@ -1,27 +0,0 @@ -#include - - -struct SegmentDescriptor { - unsigned short limit_low; - unsigned short base_low; - unsigned char base_middle; - unsigned char access; - unsigned char granularity; - unsigned char base_high; -}__attribute__((packed)); - - -struct GlobalDescriptorTableDescriptor{ - unsigned short limit; - unsigned int base; -}__attribute__((packed)); - -extern SegmentDescriptor GlobalDescriptorTable[]; -extern GlobalDescriptorTableDescriptor gdtDescriptor; - - -void add_descriptor(int which , unsigned long base, unsigned long limit, unsigned char access, unsigned char granularity ); - - -extern "C" void LoadGlobalDescriptorTable(); -void initGDT(); diff --git a/source/kernel/interrupts/idt/idt.cpp b/source/kernel/interrupts/idt/idt.cpp index abb9940..3000fae 100644 --- a/source/kernel/interrupts/idt/idt.cpp +++ b/source/kernel/interrupts/idt/idt.cpp @@ -2,8 +2,7 @@ #include "../../drivers/pit/pit.h" #include "../../drivers/ps-2/keyboard.h" #include "../../cpu.h" -#include "../../drivers/ps-2/keyboard.h" - +#include "../../memory/VirtualMemoryManager.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; @@ -17,25 +16,25 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ }; -void irs_handler (registers regs) { +void irs_handler (registers* regs) { uint32_t FaultingAddress; //printf("(IRS) Interrupt number: %d \r", regs.int_no); - switch (regs.int_no) + switch (regs->int_no) { case 0: // Divide Error #DE printf("#DE\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 1: // Debug Exception #DB printf("#DB\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 2: @@ -46,49 +45,50 @@ void irs_handler (registers regs) { case 3: // Breakpoint Exception #BP printf("#BP\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 4: // Overflow Exception #OF printf("#OF\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 5: // BOUND Range Exceeded Exception #BR printf("#BR\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 6: // Invalid OpCode Exception #UD printf("#UD\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 7: // Device Not Available Exception #NM printf("#NM\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 8: // Double Fault Exception #DF printf("#DF\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); + while(true); break; case 9: @@ -99,64 +99,74 @@ void irs_handler (registers regs) { case 10: // Invalid TSS Exception #TS printf("#TS\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); + __asm__("cli;" "1: hlt;" "jmp 1b;"); break; case 11: // Segment Not Present #NP printf("#NP\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 12: // Stack Fault Exception #SS printf("#SS\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; - case 13: + case 13:{ // General Protection Exception #GP printf("#GP\n"); - printf("Accessing memory caused a general protectuion exception.\n"); - - printf("Fault due to entry at index: %d", (regs.err_code >> 3 & 0xFFF ) ); + printf("Accessing memory caused a general protection exception.\n"); + printf("Faulting instruction at addres: 0x%x\n", regs->eip ); + printf("Error code: 0x%x\n", regs->err_code); - if(regs.err_code & 0x3 >> 1 == 0 ){ - printf("* Index references GDT"); - } - if(regs.err_code & 0x3 >> 1 == 1 ){ - printf("* Index references IDT"); - } + if (regs->err_code != 0){ + printf("Fault due to entry at index: 0x%x (%d)\n", (regs->err_code >> 3 & 0xFFF ) , regs->err_code); - if(regs.err_code & 0x3 >> 1 == 2 ){ - printf("* Index references LDT"); - } - if(regs.err_code & 0x3 >> 1 == 4 ){ - printf("* Index references IDT"); - } + uint8_t table = regs->err_code >> 1 & 0x3 ; + + if(table == 0 ){ + printf("* Index references GDT\n"); + } + if(table == 1 ){ + printf("* Index references IDT\n"); + } - if( regs.err_code & 0x1) - { - printf("* Originated externally!"); + if(table == 2 ){ + printf("* Index references LDT\n"); + } + + if(table == 3 ){ + printf("* Index references IDT\n"); + } + + if( regs->err_code & 0x1) + { + printf("* Originated externally!\n"); + } } __asm__("cli;" "1: hlt;" "jmp 1b;"); + } break; case 14: // Page Fault Exception #PF printf("#PF\n"); - + #define ALIGN(addr, align) (((addr) & ~((align) - 1)) + (align)) FaultingAddress = GetCR2(); + printf("Accessing the linear address 0x%x resulted in a page fault!\n\n", FaultingAddress); // Error code of 32 bits are on the stack @@ -174,89 +184,86 @@ void irs_handler (registers regs) { printf("REASON: \n\n"); - if (regs.err_code & PF_ERR_PRESENT_BIT ){ + if (regs->err_code & PF_ERR_PRESENT_BIT ){ printf("* Page protection violation!\n"); } else{ printf("* Page not-present!\n"); + Immediate_Map(FaultingAddress, FaultingAddress - 0xC0000000); + } - if(regs.err_code & PF_ERR_WRITE_BIT){ + if(regs->err_code & PF_ERR_WRITE_BIT){ printf("* Write access violation!\n"); } else{ printf("* Read access violation!\n"); } - if(regs.err_code & PF_ERR_USER_BIT){ + if(regs->err_code & PF_ERR_USER_BIT){ printf("* Violation from user-space (CPL=3)\n"); } - if(regs.err_code & PF_ERR_INSTRUCTION_FETCH_BIT){ + if(regs->err_code & PF_ERR_INSTRUCTION_FETCH_BIT){ printf("* Caused by an instruction fetch. \n"); } - /* - Check the error code to figure out what happened here - */ + __asm__("cli;" "1: hlt;" "jmp 1b;"); - - - break; case 16: // x87 FPU Floating-point Error #MF printf("#MF\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 17: // Alignment Check Exception #AC printf("#AC\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 18: // Machine-Check Exception #MC printf("#MC\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 19: // SIMD Floating-point Exception #XM printf("#XM\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 20: // Virtualization Exception #VE printf("#VE\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; case 21: // Control Protection Exception #CP printf("#CP\n"); - printf("EIP: 0x%x\n", regs.eip); - printf("EAX: 0x%x\n", regs.eax); - printf("EBP: 0x%x\n", regs.ebp); + printf("EIP: 0x%x\n", regs->eip); + printf("EAX: 0x%x\n", regs->eax); + printf("EBP: 0x%x\n", regs->ebp); break; default: // PANIC!!! break; } - + } diff --git a/source/kernel/interrupts/idt/idt.h b/source/kernel/interrupts/idt/idt.h index 94e409f..e2a0bd5 100644 --- a/source/kernel/interrupts/idt/idt.h +++ b/source/kernel/interrupts/idt/idt.h @@ -36,7 +36,7 @@ extern "C" { void irq_handler (registers regs); - void irs_handler (registers regs); + void irs_handler (registers* regs); extern void irs0 (); extern void irs1 (); diff --git a/source/kernel/irs_table.s b/source/kernel/irs_table.s index 4beda70..a9c8cb8 100644 --- a/source/kernel/irs_table.s +++ b/source/kernel/irs_table.s @@ -1,234 +1,63 @@ +.code32 /* * Interupt handlers */ -.globl irs0 -irs0: - cli - push $0 - push $0 - jmp irs_common +.macro ISR_NOERRORCODE NAME, VECTOR + .globl irs\NAME + irs\NAME: + cli + push $0 + push \VECTOR + jmp irs_common +.endm -.globl irs1 -irs1: - cli - push $0 - push $1 - jmp irs_common +.macro ISR_ERROCODE NAME, VECTOR + .globl irs\NAME + irs\NAME: + cli + push \VECTOR + jmp irs_common +.endm -.globl irs2 -irs2: - cli - push $0 - push $2 - jmp irs_common -.globl irs3 -irs3: - cli - push $0 - push $3 - jmp irs_common +ISR_NOERRORCODE 0 $0 +ISR_NOERRORCODE 1 $1 +ISR_NOERRORCODE 2 $2 +ISR_NOERRORCODE 3 $3 +ISR_NOERRORCODE 4 $4 +ISR_NOERRORCODE 5 $5 +ISR_NOERRORCODE 6 $6 +ISR_NOERRORCODE 7 $7 +ISR_NOERRORCODE 8 $8 +ISR_NOERRORCODE 9 $9 +ISR_NOERRORCODE 10 $10 +ISR_NOERRORCODE 11 $11 +ISR_NOERRORCODE 12 $12 +ISR_NOERRORCODE 13 $13 +ISR_NOERRORCODE 14 $14 +ISR_NOERRORCODE 15 $15 +ISR_NOERRORCODE 16 $16 +ISR_NOERRORCODE 17 $17 +ISR_NOERRORCODE 18 $18 +ISR_NOERRORCODE 19 $19 +ISR_NOERRORCODE 20 $20 +ISR_NOERRORCODE 21 $21 +ISR_NOERRORCODE 22 $22 +ISR_NOERRORCODE 23 $23 +ISR_NOERRORCODE 24 $24 +ISR_NOERRORCODE 25 $25 +ISR_NOERRORCODE 26 $26 +ISR_NOERRORCODE 27 $27 +ISR_NOERRORCODE 28 $28 +ISR_NOERRORCODE 29 $29 +ISR_NOERRORCODE 30 $30 +ISR_NOERRORCODE 31 $31 -.globl irs4 -irs4: - cli - push $0 - push $4 - jmp irs_common - -.globl irs5 -irs5: - cli - push $0 - push $5 - jmp irs_common - -.globl irs6 -irs6: - cli - push $0 - push $6 - jmp irs_common - -.globl irs7 -irs7: - cli - push $0 - push $7 - jmp irs_common - -.globl irs8 -irs8: - cli - push $0 - push $8 - jmp irs_common - -.globl irs9 -irs9: - cli - push $0 - push $9 - jmp irs_common - -.globl irs10 -irs10: - cli - push $0 - push $10 - jmp irs_common - -.globl irs11 -irs11: - cli - push $0 - push $11 - jmp irs_common - -.globl irs12 -irs12: - cli - push $0 - push $12 - jmp irs_common - -.globl irs13 -irs13: - cli - push $13 - jmp irs_common - -.globl irs14 -irs14: - cli - push $0 - push $14 - jmp irs_common - -.globl irs15 -irs15: - cli - push $0 - push $15 - jmp irs_common - -.globl irs16 -irs16: - cli - push $0 - push $16 - jmp irs_common - -.globl irs17 -irs17: - cli - push $0 - push $17 - jmp irs_common - -.globl irs18 -irs18: - cli - push $0 - push $18 - jmp irs_common - -.globl irs19 -irs19: - cli - push $0 - push $19 - jmp irs_common - -.globl irs20 -irs20: - cli - push $0 - push $20 - jmp irs_common - -.globl irs21 -irs21: - cli - push $0 - push $21 - jmp irs_common - -.globl irs22 -irs22: - cli - push $0 - push $22 - jmp irs_common - -.globl irs23 -irs23: - cli - push $0 - push $23 - jmp irs_common - -.globl irs24 -irs24: - cli - push $0 - push $24 - jmp irs_common - -.globl irs25 -irs25: - cli - push $0 - push $25 - jmp irs_common - -.globl irs26 -irs26: - cli - push $0 - push $26 - jmp irs_common - -.globl irs27 -irs27: - cli - push $0 - push $27 - jmp irs_common - -.globl irs28 -irs28: - cli - push $0 - push $28 - jmp irs_common - -.globl irs29 -irs29: - cli - push $0 - push $29 - jmp irs_common - -.globl irs30 -irs30: - cli - push $0 - push $30 - jmp irs_common - -.globl irs31 -irs31: - cli - push $0 - push $31 - jmp irs_common irs_common: pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax - mov %ds, %ax push %eax @@ -239,17 +68,20 @@ irs_common: mov %ax, %es mov %ax, %fs mov %ax, %gs + + mov %esp, %eax + push %eax call irs_handler - + pop %eax - - mov %ax, %ds - mov %ax, %es - mov %ax, %fs - mov %ax, %gs + pop %ebx // reload ther orignal data segment descriptor + mov %bx, %ds + mov %bx, %es + mov %bx, %fs + mov %bx, %gs popa - add $8, %esp # cleans push error and irs code - sti + add $12, %esp # cleans push error and irs code + iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 685b344..b83f2a6 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -1,37 +1,46 @@ -extern "C"{ - #include "../lib/include/string.h" + +extern "C" +{ + #include "../lib/include/string.h" } -#include "definitions.h" #include "prekernel/bootstructure.h" -#include "drivers/vga/VBE.h" -#include "drivers/pit/pit.h" - +#include "memory/memory.h" +#include "memory/memoryinfo.h" #include "memory/memory.h" #include "memory/VirtualMemoryManager.h" #include "memory/KernelHeap.h" #include "memory/gdt/gdtc.h" -#include "drivers/acpi/rsdp.h" -#include "drivers/ide/ide.h" -#include "drivers/ata/ataDevice.h" -#include "PartitionTable/MBR/MasterBootRecord.h" -#include "interrupts/idt/idt.h" -#include "filesystem/FAT/BiosParameterBlock.h" -#include "filesystem/FAT/DirectoryEntry.h" +#include "supervisorterminal/superVisorTerminal.h" + #include "drivers/io/io.h" +#include "drivers/vga/VBE.h" #include "drivers/pci/pci.h" -#include "cpu.h" -#include "serial.h" -#include "time.h" +#include "drivers/pit/pit.h" + #include "terminal/kterm.h" -#include "supervisorterminal/superVisorTerminal.h" +#include "prekernel/multiboot.h" +#include "bootinfo.h" -extern "C" void kernel_main (); -void ProcessBootInfo(); +#include "bootcheck.h" + +#include "interrupts/idt/idt.h" +#include "time.h" +#include "cpu.h" +#include "serial.h" +#include "time.h" +#include "definitions.h" + + + + +/* + Copyright © Nigel Barink 2023 +*/ extern "C" void kernel_main () { @@ -40,152 +49,6 @@ extern "C" void kernel_main () */ printf("|=== BarinkOS ===|\n"); startSuperVisorTerminal(); - - RSDPTR* rsd = FindRSD(); - RSDT* rsd_table = getRSDT(rsd); - - - // Enumerate the PCI bus - PCI_Enumerate(); - TestIDEController(); - - int devNumber = 0 ; - for ( auto device : ide_devices){ - if (!device.Reserved) - continue; - printf("Device %d\n" , devNumber); - printf (" Device on Channel: (0x%x) %s\n" ,device.Channel, device.Channel == 0 ? "Primary" : "Secondary"); - printf (" Device drive:(0x%x) %s\n" , device.Drive, device.Drive? "Slave" : "Master"); - printf (" Device Type:(0x%x) %s\n" , device.Type, device.Type ? "ATAPI" : "ATA"); - devNumber ++; - - } - - enum BUS_PORT { - Primary= 0x1f0, - Secondary = 0x170 - }; - - - - ATA_DEVICE::Identify((uint16_t) BUS_PORT::Primary, DEVICE_DRIVE::MASTER); - - const int C = 0; - const int H = 0; - const int HPC = 16; - const int SPT = 63; - - int S = 1; - uint32_t LBA = (C*HPC+H) * SPT + (S-1); - printf("LBA: %d\n" , LBA); - uint16_t buffer [256]; - - - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, buffer); - - MBR* mbr = (MBR*) buffer; - - printf("BootSector: 0x%x\n", mbr->ValidBootsector ); - for( int i = 0 ; i < 4 ; i ++){ - PartitionTableEntry PT = mbr->TableEntries[i]; - - printf("Partition %d [ %d sectors, PartitionType: %x, 0x%x, \nLBA Start: 0x%x ]\n" , - i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); - } - - // Find the BiosParameter block - uint16_t biosparameterblock[256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, biosparameterblock); - - BiosParameterBlock* bpb = (BiosParameterBlock*) biosparameterblock; - - - printf("\nBPB: Bytes per Sector %d\n", bpb->BytesPerSector ); - printf("OEM ID: %s\n", bpb->OEM_id); - printf("Bytes per sector: %d\n", bpb->BytesPerSector); - printf("Sectors per cluster: %d\n", bpb->SectorsPerCluster); - printf("Reserved sectors: %d\n", bpb->ReservedSectors); - printf("Number of FAT: %d\n", bpb->NumberOfFileAllocationTables); - printf("Number of Dir entries: %d\n", bpb->NumberOfDirectoryEntries); - printf("Total Sectors in volume: %d\n", bpb->TotalSectorsInLogicalVolume); - printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); - - - - - /** - * @brief File Allocation Table - */ - - - uint32_t FATAddress = mbr->TableEntries[0].LBA_partition_start + bpb->ReservedSectors ; - uint16_t FAT[256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); - - // Show data in terminal - for(int i = 0; i < 256; i++ ) { - printf("%x ", FAT[i]); - } - kterm_put('\n'); - - - uint32_t RootDirectoryRegion = FATAddress + ( bpb->NumberOfFileAllocationTables * bpb->NumberOfSectorsPerFAT ); - uint32_t DataRegion = RootDirectoryRegion + ((bpb->NumberOfDirectoryEntries * 32) / bpb->BytesPerSector ); - - uint16_t data2 [256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, RootDirectoryRegion, data2 ); - DirectoryEntry* RootDirectory = (DirectoryEntry*) data2; - // List files in root - for(int i= 0; i < bpb->NumberOfDirectoryEntries ; i++ ) - { - DirectoryEntry* entry = (DirectoryEntry*)((uint32_t) RootDirectory + (i * sizeof(DirectoryEntry))); - - if( entry->filename[0] == (uint8_t) 0x00 ) - break; // There are no more entries in this directory or the entry is free - - if( entry->attribute & 0x01 == 0x01 || entry->attribute & 0x20 == 0x20) - continue; // Skip listing if hidden or Achieve flag is set - - // Print the filename; - for( int n = 0; n < 8; n++ ){ - if(entry->filename[n] == 0x20) - break; - kterm_put(entry->filename[n]); - }kterm_put('\n'); - - for( int n = 0; n < 3; n++){ - kterm_put(entry->Extension[n]); - }kterm_put('\n'); - - printf("Attribute: %x \n" , entry->attribute); - printf("FileSize: %d Bytes\n", entry->FilesizeInBytes); - - if( entry->FilesizeInBytes != 0x0 || entry->attribute & 0x8 == 0x0){ - printf("Show contents"); - - printf( "Start cluster of the file: 0x%x\n" , entry->StartingCluster); - - printf("IS it only 1 cluster? %s\n" , FAT[i] == 0xFFFF? "Yes": "No" ); - - uint32_t sector = DataRegion + ((entry->StartingCluster - 0x02 ) * bpb->SectorsPerCluster); - - - uint16_t dataBlob [256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob ); - for( int n = 0; n < 256; n++) - { - kterm_put(dataBlob[n] & 0x00ff); - - kterm_put(dataBlob[n] >> 8); - }kterm_put('\n'); - - - } - - printf("======================\n"); - - - } } @@ -198,38 +61,26 @@ extern "C" void early_main() initGDT(); init_idt(); - + // Enable interrupts asm volatile("STI"); - - - initHeap(); - - printf("TRY ALLOCATING 4 BYTES\n"); - uint32_t* MyVariable = (uint32_t*) malloc(4); // allocate 4 bytes using my heap - free(MyVariable); - - // test heap allocation - struct KernelInfo { - int bar; - bool foo; - }; - - KernelInfo* MyInfo = (KernelInfo*) malloc(sizeof(KernelInfo)); - - MyInfo->bar = 6; - MyInfo->foo = false; - printf("bar contains %d\n", MyInfo->bar); - free(MyInfo); - - + initHeap(); printf("Enable Protected mode and jump to kernel main\n"); + + // Set the protected bit of control register 0 + // this will put the CPU into protected mode + // NOTE: This should really be a assembly procedure + // We cant directly write to control register 0 + // therefor we copy the value of control register 0 into eax + // once we are done manipulating the value we write the value in + // eax back to control register 0 + asm volatile("mov %cr0, %eax "); asm volatile("or $1, %eax"); - asm volatile("mov %eax, %cr0"); // re-enable protected mode ? + asm volatile("mov %eax, %cr0"); pit_initialise(); diff --git a/source/kernel/kernel.h b/source/kernel/kernel.h index ae769df..0b861f8 100644 --- a/source/kernel/kernel.h +++ b/source/kernel/kernel.h @@ -1,43 +1,8 @@ #pragma once -extern "C" -{ - #include "../lib/include/string.h" -} - - -#include "drivers/VGA/VBE.h" -#include "terminal/kterm.h" - -#include "./boot/multiboot.h" -#include "bootinfo.h" - -#include "memory/memory.h" -#include "memory/memoryinfo.h" -#include "bootcheck.h" - -#include "gdt/gdtc.h" -#include "interrupts/idt/idt.h" - -#include "drivers/IO/io.h" -#include "time.h" -#include "drivers/pit/pit.h" - -#include "cpu.h" -#include "serial.h" -#include "drivers/IO/PCI/pci.h" -#include "drivers/ide/ide.h" -#include "./drivers/IO/ata/ataDevice.h" -#include "./PartitionTable/MBR/MasterBootRecord.h" -#include "./filesystem/FAT/BiosParameterBlock.h" -#include "./filesystem/FAT/ExtendBootRecord.h" -#include "./filesystem/FAT/DirectoryEntry.h" -#include "drivers/ACPI/rsdp.h" - - -#include "time.h" -#include "supervisorterminal/superVisorTerminal.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) #define PANIC(message) {return;} + + diff --git a/source/kernel/memory/KernelHeap.cpp b/source/kernel/memory/KernelHeap.cpp index adfd2b6..4483d2d 100644 --- a/source/kernel/memory/KernelHeap.cpp +++ b/source/kernel/memory/KernelHeap.cpp @@ -63,26 +63,24 @@ void free(void* addr) void initHeap() { - // put the start of our kernel heap 1 page after the kernel_end address - // Lets calculate the address - printf("FIND SUITABLE HEAP_ADDRESS\n"); - uint32_t alligned_k_end = (uint32_t) &kernel_end + ((uint32_t)&kernel_end % BLOCK_SIZE == 0 ? 4096 : 0); - uint32_t HEAP_ADDRESS = (uint32_t) alligned_k_end + 4096; - printf("HEAP_ADDRESS: 0x%x\n", HEAP_ADDRESS); - - // NOTE: we can't check if the mapping has failed or not here! - AllocatePage(HEAP_ADDRESS); - start = (heap_block*) HEAP_ADDRESS; + void* HEAP_ADDRESS = allocate_block(); + printf("0x%x HEAP Paddr\n", HEAP_ADDRESS); + + Immediate_Map((uint32_t)HEAP_ADDRESS + 0xC0000000, (uint32_t)HEAP_ADDRESS ); + start = (heap_block*) ((uint32_t)HEAP_ADDRESS + 0xC0000000); heap_size = 4096; printf("Clear heap\n"); // Clear the heap printf("set at 0x%x %d bytes to zero\n", start , heap_size); + memset((void*)start, 0x00, heap_size /4); + printf("Init first heap block\n"); // initialzie start->Size = heap_size - sizeof(heap_block); + start->Used = false; } \ No newline at end of file diff --git a/source/kernel/memory/VirtualMemoryManager.cpp b/source/kernel/memory/VirtualMemoryManager.cpp index 3ce9260..e866b28 100644 --- a/source/kernel/memory/VirtualMemoryManager.cpp +++ b/source/kernel/memory/VirtualMemoryManager.cpp @@ -1,7 +1,8 @@ #include "VirtualMemoryManager.h" #define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) -extern uint32_t boot_page_directory[1024] ; +extern uint32_t boot_page_directory[1024] ; // points to the wrong location + extern uint32_t boot_page_table[1024]; @@ -26,29 +27,28 @@ void AllocatePage(uint32_t vaddr) { printf("Directory entry is marked as present\n"); uint32_t* page_table = (uint32_t*)((boot_page_directory[PageDirectoryEntryIndex]) & 0xFFFFE000) ; - page_table = (uint32_t*) ((uint32_t)page_table + 0xC0000000); // Add kernel offset - printf("Page table address: 0x%x\n", (uint32_t)page_table); + //page_table = (uint32_t*) ((uint32_t)page_table + 0xC0000000); // Add kernel offset + printf("Page table address: 0x%x\n", (uint32_t)&page_table); // check if the page table entry is marked as present if ( page_table[PageTableEntryIndex] & 0x1 ) { printf("page already present!\n"); - return; } else{ printf("Mapping a physical page.\n"); // Map the entry to a physical page - page_table[PageTableEntryIndex] = (uint32_t)(allocate_block() + 0x3); - flush_cr3(); + page_table[PageTableEntryIndex] = (uint32_t)allocate_block() | 0x3; } } else { printf("Mapping a new page directory entry with a page table\n"); // mark the page table as present and allocate a physical block for it - boot_page_directory[PageDirectoryEntryIndex] = (uint32_t)(allocate_block() + 0x3); - flush_cr3(); + boot_page_directory[PageDirectoryEntryIndex] = (uint32_t)allocate_block() | 0x3; } + asm ("cli; invlpg (%0); sti" :: "r" (vaddr) : "memory" ); + } @@ -74,12 +74,45 @@ void FreePage(uint32_t vaddr ) void Immediate_Map ( uint32_t vaddr, uint32_t paddr) { - uint32_t page_aligned_address = ALIGN(vaddr, 4096); - + printf("map 0x%x to 0x%x\n", paddr, vaddr); // allocate a page at virtual address int PageDirectoryEntryIndex = vaddr >> 22; int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; + printf("Map address at PDE 0x%x PTE 0x%x\n", PageDirectoryEntryIndex, PageTableEntryIndex); + + if ((boot_page_directory - 0xC0000000)[PageDirectoryEntryIndex] & 0x1 ) + { + printf("Directory entry is marked as present\n"); + + } else { + printf("Mapping a new page directory entry with a page table\n"); + // mark the page table as present and allocate a physical block for it + + void* new_page_dir = allocate_block(); + printf("New page directory address 0x%x\n", new_page_dir); + boot_page_directory[PageDirectoryEntryIndex] = (uint32_t)new_page_dir | 0x3; + + } + + printf("PDE found at : 0x%x\n", (uint32_t) &boot_page_directory[PageDirectoryEntryIndex]); + uint32_t* page_table = (uint32_t*)(boot_page_directory[PageDirectoryEntryIndex] & 0xFFFFE000) ; + //page_table = (uint32_t*) ((uint32_t)page_table - 0xC0000000); // remove kernel offset + printf("Page table address: 0x%x\n", (uint32_t)page_table); + + // check if the page table entry is marked as present + if ( page_table[PageTableEntryIndex] & 0x1 ) + { + printf("page already present!\n"); + printf("Entry found at addr: 0x%x\n", &(page_table[PageTableEntryIndex])); + } else{ + printf("Mapping a physical page.\n"); + // Map the entry to a physical page + page_table[PageTableEntryIndex] = (uint32_t)(paddr | 0x3); + } + + + asm ("cli; invlpg (%0); sti" :: "r" (vaddr) : "memory" ); } void Immediate_Unmap(uint32_t vaddr) diff --git a/source/kernel/memory/VirtualMemoryManager.h b/source/kernel/memory/VirtualMemoryManager.h index ef80ffe..f4da57a 100644 --- a/source/kernel/memory/VirtualMemoryManager.h +++ b/source/kernel/memory/VirtualMemoryManager.h @@ -9,7 +9,7 @@ void SetupVMM(); void AllocatePage(uint32_t v_addr ); void FreePage(uint32_t v_addr); -void Immediate_Map(uint32_t p_addr, uint32_t v_addr); +void Immediate_Map(uint32_t vaddr, uint32_t paddr); void Immediate_Unmap (uint32_t v_addr); // void Demand_map(uint32_t p_addr, uint32_t v_addr); diff --git a/source/kernel/memory/gdt/gdtc.cpp b/source/kernel/memory/gdt/gdtc.cpp index 32b8ea3..55e0b92 100644 --- a/source/kernel/memory/gdt/gdtc.cpp +++ b/source/kernel/memory/gdt/gdtc.cpp @@ -6,9 +6,13 @@ #define KERNEL_DATA_SEGMENT 2 #define USER_CODE_SEGMENT 3 #define USER_DATA_SEGMENT 4 +#define TASK_STATE_SEGMENT 5 -SegmentDescriptor GlobalDescriptorTable[5]; +SegmentDescriptor GlobalDescriptorTable[6]; GlobalDescriptorTableDescriptor gdtDescriptor; +tss32 TaskStateSegment = {}; + + void add_descriptor(int which , unsigned long base, unsigned long limit, unsigned char access, unsigned char granularity ){ GlobalDescriptorTable[which].base_low = (base & 0xFFFF ); @@ -21,7 +25,6 @@ void add_descriptor(int which , unsigned long base, unsigned long limit, unsigne GlobalDescriptorTable[which].granularity |= (granularity & 0xF0); GlobalDescriptorTable[which].access = access; - } @@ -29,9 +32,9 @@ void add_descriptor(int which , unsigned long base, unsigned long limit, unsigne void initGDT(){ -#ifdef __VERBOSE__ + printf("Init GDT!\n"); -#endif + // NULL segment add_descriptor(NULL_SEGMENT, 0,0,0,0); @@ -42,16 +45,18 @@ void initGDT(){ add_descriptor(KERNEL_DATA_SEGMENT, 0, 0xFFFFFFFF, 0x92, 0xCF); // User Code Segment - // TODO: + add_descriptor(USER_CODE_SEGMENT, 0, 0xFFFFFFFF, 0xFA, 0xCF); // User Data Segement - // TODO: + add_descriptor(USER_DATA_SEGMENT, 0, 0xFFFFFFFF, 0xF2, 0xCF); + + // Task Segment Descriptor + add_descriptor(TASK_STATE_SEGMENT, (unsigned long)&TaskStateSegment, sizeof(TaskStateSegment), 0x89, 0x0); // init Gdt Descriptor gdtDescriptor.limit = ((sizeof(SegmentDescriptor ) * 5 ) - 1); - gdtDescriptor.base = (unsigned int) &GlobalDescriptorTable; + gdtDescriptor.base = (unsigned int) (&GlobalDescriptorTable); - printf("GDT at address 0x%x, with an size of 0x%x bytes\n" , (unsigned int)GlobalDescriptorTable, sizeof(GlobalDescriptorTable)); LoadGlobalDescriptorTable(); diff --git a/source/kernel/memory/gdt/gdtc.h b/source/kernel/memory/gdt/gdtc.h index 548bc5e..adca78e 100644 --- a/source/kernel/memory/gdt/gdtc.h +++ b/source/kernel/memory/gdt/gdtc.h @@ -1,6 +1,5 @@ +#pragma once #include - - struct SegmentDescriptor { unsigned short limit_low; unsigned short base_low; @@ -10,14 +9,16 @@ struct SegmentDescriptor { unsigned char base_high; }__attribute__((packed)); +struct tss32 { + uint64_t bits; + uint8_t other_bits :5; +}__attribute__((packed)); struct GlobalDescriptorTableDescriptor{ unsigned short limit; unsigned int base; -}__attribute__((packed)); +}__attribute__((packed)) ; -extern SegmentDescriptor GlobalDescriptorTable[]; -extern GlobalDescriptorTableDescriptor gdtDescriptor; void add_descriptor(int which , unsigned long base, unsigned long limit, unsigned char access, unsigned char granularity ); diff --git a/source/kernel/supervisorterminal/superVisorTerminal.cpp b/source/kernel/supervisorterminal/superVisorTerminal.cpp index 51aeff9..73ee676 100644 --- a/source/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/source/kernel/supervisorterminal/superVisorTerminal.cpp @@ -1,4 +1,10 @@ #include "superVisorTerminal.h" +#include "../drivers/ata/ataDevice.h" +#include "../drivers/acpi/acpi.h" +#include "../drivers/ide/ide.h" +#include "../PartitionTable/MBR/MasterBootRecord.h" +#include "../filesystem/FAT/BiosParameterBlock.h" +#include "../filesystem/FAT/DirectoryEntry.h" bool isRunning = true; void startSuperVisorTerminal(){ while (isRunning){ @@ -24,7 +30,7 @@ void startSuperVisorTerminal(){ } printf("\n"); KeyHandled(); - + if ( strncmp("DATE", command , characterCount ) == 0 ) { @@ -34,7 +40,7 @@ void startSuperVisorTerminal(){ printf(" - Time: %02d:%02d:%02d\n" , hour, minute, second); printf(" - Ticks: %09d\n", pit_tick); } - else if( strncmp ("MEMORY" , command , characterCount) == 0 ) + if( strncmp ("MEMORY" , command , characterCount) == 0 ) { // Show memory layout printf("========= Memory ==========\n"); @@ -51,33 +57,181 @@ void startSuperVisorTerminal(){ //printf("Reserved Memory: %d bytes\n", bootinfo->memory->ReservedMemory); } - else if(strncmp("TEST", command, characterCount) == 0) + if(strncmp("TEST", command, characterCount) == 0) { // TEST #DE exception asm volatile ("MOV $4, %AX ; MOV $0, %BX ; DIV %BX"); // IRS 0 } - else if (strncmp("VERSION", command , characterCount) == 0) + if (strncmp("VERSION", command , characterCount) == 0) { // Show version information printf("========= Version ========\n"); printf("Kernel v%d\n", 0); } - else if(strncmp("CLEAR", command, characterCount) == 0) + if(strncmp("CLEAR", command, characterCount) == 0) { kterm_init(); printf("|=== BarinkOS ===|\n"); } - else if(strncmp("FAT", command, characterCount) == 0){ - isRunning = false; + if(strncmp("FAT", command, characterCount) == 0) + { + printf("ACPI initialize!\n"); + ///ACPI::initialize(); + + // Enumerate the PCI bus + printf("PCI Enumeration\n"); + PCI_Enumerate(); + printf("TEST IDE Controller"); + TestIDEController(); + + int devNumber = 0 ; + for ( auto device : ide_devices){ + if (!device.Reserved) + continue; + printf("Device %d\n" , devNumber); + printf (" Device on Channel: (0x%x) %s\n" ,device.Channel, device.Channel == 0 ? "Primary" : "Secondary"); + printf (" Device drive:(0x%x) %s\n" , device.Drive, device.Drive? "Slave" : "Master"); + printf (" Device Type:(0x%x) %s\n" , device.Type, device.Type ? "ATAPI" : "ATA"); + devNumber ++; + + } + + enum BUS_PORT { + Primary= 0x1f0, + Secondary = 0x170 + }; + + + + ATA_DEVICE::Identify((uint16_t) BUS_PORT::Primary, DEVICE_DRIVE::MASTER); + + const int C = 0; + const int H = 0; + const int HPC = 16; + const int SPT = 63; + + int S = 1; + uint32_t LBA = (C*HPC+H) * SPT + (S-1); + printf("LBA: %d\n" , LBA); + uint16_t buffer [256]; + + + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, buffer); + + MBR* mbr = (MBR*) buffer; + + printf("BootSector: 0x%x\n", mbr->ValidBootsector ); + for( int i = 0 ; i < 4 ; i ++){ + PartitionTableEntry PT = mbr->TableEntries[i]; + + printf("Partition %d [ %d sectors, PartitionType: %x, 0x%x, \nLBA Start: 0x%x ]\n" , + i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); + } + + // Find the BiosParameter block + uint16_t biosparameterblock[256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, biosparameterblock); + + BiosParameterBlock* bpb = (BiosParameterBlock*) biosparameterblock; + + + printf("\nBPB: Bytes per Sector %d\n", bpb->BytesPerSector ); + printf("OEM ID: %s\n", bpb->OEM_id); + printf("Bytes per sector: %d\n", bpb->BytesPerSector); + printf("Sectors per cluster: %d\n", bpb->SectorsPerCluster); + printf("Reserved sectors: %d\n", bpb->ReservedSectors); + printf("Number of FAT: %d\n", bpb->NumberOfFileAllocationTables); + printf("Number of Dir entries: %d\n", bpb->NumberOfDirectoryEntries); + printf("Total Sectors in volume: %d\n", bpb->TotalSectorsInLogicalVolume); + printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); + + /** + * @brief File Allocation Table + */ + + + uint32_t FATAddress = mbr->TableEntries[0].LBA_partition_start + bpb->ReservedSectors ; + uint16_t FAT[256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); + + // Show data in terminal + for(int i = 0; i < 256; i++ ) { + printf("%x ", FAT[i]); + } + kterm_put('\n'); + + + uint32_t RootDirectoryRegion = FATAddress + ( bpb->NumberOfFileAllocationTables * bpb->NumberOfSectorsPerFAT ); + uint32_t DataRegion = RootDirectoryRegion + ((bpb->NumberOfDirectoryEntries * 32) / bpb->BytesPerSector ); + + uint16_t data2 [256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, RootDirectoryRegion, data2 ); + DirectoryEntry* RootDirectory = (DirectoryEntry*) data2; + // List files in root + for(int i= 0; i < bpb->NumberOfDirectoryEntries ; i++ ) + { + DirectoryEntry* entry = (DirectoryEntry*)((uint32_t) RootDirectory + (i * sizeof(DirectoryEntry))); + + if( entry->filename[0] == (uint8_t) 0x00 ) + break; // There are no more entries in this directory or the entry is free + + if( entry->attribute & 0x01 == 0x01 || entry->attribute & 0x20 == 0x20) + continue; // Skip listing if hidden or Achieve flag is set + + // Print the filename; + for( int n = 0; n < 8; n++ ){ + if(entry->filename[n] == 0x20) + break; + kterm_put(entry->filename[n]); + }kterm_put('\n'); + + for( int n = 0; n < 3; n++){ + kterm_put(entry->Extension[n]); + }kterm_put('\n'); + + printf("Attribute: %x \n" , entry->attribute); + printf("FileSize: %d Bytes\n", entry->FilesizeInBytes); + + if( entry->FilesizeInBytes != 0x0 || entry->attribute & 0x8 == 0x0){ + printf("Show contents"); + + printf( "Start cluster of the file: 0x%x\n" , entry->StartingCluster); + + printf("IS it only 1 cluster? %s\n" , FAT[i] == 0xFFFF? "Yes": "No" ); + + uint32_t sector = DataRegion + ((entry->StartingCluster - 0x02 ) * bpb->SectorsPerCluster); + + + uint16_t dataBlob [256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob ); + for( int n = 0; n < 256; n++) + { + kterm_put(dataBlob[n] & 0x00ff); + + kterm_put(dataBlob[n] >> 8); + }kterm_put('\n'); + + + } + + printf("======================\n"); + + + } continue; } - else - { - printf("Unknown command\n"); + + + + if(strncmp("glg", command, characterCount) == 0){ + printf("Why???"); } + printf("executed command: %s\n", command); + + delay(1000); } } \ No newline at end of file -- 2.39.5 From 1f90a5d862d5a80fef4fe78953f6bd8d8fdf8913 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 11 Feb 2023 12:22:45 +0100 Subject: [PATCH 087/115] Starting to move towards proper HAL and ring3 - slight clean up of PCI driver - Added TaskSegment header - Rename some folders --- .gitmodules | 3 + Makefile | 4 +- mlibc | 1 + source/kernel/boot/boot.s | 2 +- source/kernel/drivers/pci/pci.cpp | 42 ++++++----- .../idt => drivers/ps-2}/scancodes/set1.h | 0 source/kernel/interrupts/{idt => }/idt.cpp | 10 +-- source/kernel/interrupts/{idt => }/idt.h | 8 +- source/kernel/interrupts/{idt => }/idt.s | 0 source/kernel/kernel.cpp | 24 +++--- source/kernel/memory/TaskStateSegment.h | 59 +++++++++++++++ source/kernel/memory/gdt/gdtc.cpp | 16 ---- source/kernel/memory/gdt/gdtc.h | 16 +++- .../mbr}/MasterBootRecord.h | 0 .../mbr}/PartitionTableEntry.h | 0 .../supervisorterminal/superVisorTerminal.cpp | 37 ++++------ source/lib/include/stack.h | 73 +++++++++++++++++++ 17 files changed, 209 insertions(+), 86 deletions(-) create mode 100644 .gitmodules create mode 160000 mlibc rename source/kernel/{interrupts/idt => drivers/ps-2}/scancodes/set1.h (100%) rename source/kernel/interrupts/{idt => }/idt.cpp (98%) rename source/kernel/interrupts/{idt => }/idt.h (93%) rename source/kernel/interrupts/{idt => }/idt.s (100%) create mode 100644 source/kernel/memory/TaskStateSegment.h rename source/kernel/{PartitionTable/MBR => partitiontable/mbr}/MasterBootRecord.h (100%) rename source/kernel/{PartitionTable/MBR => partitiontable/mbr}/PartitionTableEntry.h (100%) create mode 100644 source/lib/include/stack.h diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..82ee6dd --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "mlibc"] + path = mlibc + url = https://github.com/managarm/mlibc.git diff --git a/Makefile b/Makefile index e4bb2ff..c48fc85 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o SRC_DIR = source BUILD_DIR = build @@ -68,7 +68,7 @@ $(BUILD_DIR)/io.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/io/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/idt.o: - $(CPP) -c $(SRC_DIR)/kernel/interrupts/idt/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/interrupts/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/gdtc.o: $(CPP) -c $(SRC_DIR)/kernel/memory/gdt/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/mlibc b/mlibc new file mode 160000 index 0000000..aad4e7f --- /dev/null +++ b/mlibc @@ -0,0 +1 @@ +Subproject commit aad4e7f64b8de2c113cf7fc08943d0f005b517f9 diff --git a/source/kernel/boot/boot.s b/source/kernel/boot/boot.s index 6013482..c5e9902 100644 --- a/source/kernel/boot/boot.s +++ b/source/kernel/boot/boot.s @@ -108,6 +108,6 @@ isPaging: .include "./source/kernel/memory/gdt/gdt.s" .include "./source/kernel/irs_table.s" .include "./source/kernel/irq_table.s" -.include "./source/kernel/interrupts/idt/idt.s" +.include "./source/kernel/interrupts/idt.s" diff --git a/source/kernel/drivers/pci/pci.cpp b/source/kernel/drivers/pci/pci.cpp index e45314c..25c5f45 100644 --- a/source/kernel/drivers/pci/pci.cpp +++ b/source/kernel/drivers/pci/pci.cpp @@ -114,6 +114,14 @@ const char* getVendor( uint32_t VendorID){ return "Advanced Micor Devices, Inc.[AMD/ATI]"; break; + case 0xbeef: + return "VirtualBox Graphics Adapter"; + break; + + case 0xcafe: + return "VirtualBox Guest Service"; + break; + default: return "Vendor Unkown"; break; @@ -126,6 +134,16 @@ uint32_t ConfigReadWord ( PCIBusAddress& PCIDeviceAddress , uint8_t offset){ return inl(CONFIG_DATA); } +uint8_t GetProgIF (PCIBusAddress& PCIDeviceAddress){ + uint32_t data = ConfigReadWord(PCIDeviceAddress, 0x8); + return ((data >> 8) & 0xFF); +} + +uint32_t ReadBAR ( PCIBusAddress& PCIDeviceAddress, int bar_number){ + int offsetToBar = 0x10 + (bar_number* 0x4); + return ConfigReadWord(PCIDeviceAddress, offsetToBar); +} + uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offset){ uint32_t address; @@ -185,8 +203,7 @@ void PrintPCIDeviceInfo (PCIBusAddress& PCIDeviceAddress) } void PCI_Enumerate(){ - - + int devicesFound = 0; printf("Start finding devices, Found: %d devices"); @@ -196,18 +213,14 @@ void PCI_Enumerate(){ for(int device = 0; device < 32 ; device ++) { - - int function = 0; - //uint64_t DeviceIdentify = ConfigReadWord(bus, device, function,0x0); + uint64_t DeviceIdentify = ConfigReadWord(bus, device, function,0x0); uint32_t DeviceID = GetDevice(bus, device, function) >> 16; - - if( DeviceID != 0xFFFF){ PCIBusAddress busAddress = - PCIBusAddress{bus, device, function }; + PCIBusAddress{bus, device, function }; PrintPCIDeviceInfo(busAddress); @@ -228,9 +241,7 @@ void PCI_Enumerate(){ } - - - + devicesFound++; } } @@ -240,12 +251,3 @@ void PCI_Enumerate(){ printf("Found %d PCI devices!\n", devicesFound); } -uint8_t GetProgIF (PCIBusAddress& PCIDeviceAddress){ - uint32_t data = ConfigReadWord(PCIDeviceAddress, 0x8); - return ((data >> 8) & 0xFF); -} - -uint32_t ReadBAR ( PCIBusAddress& PCIDeviceAddress, int bar_number){ - int offsetToBar = 0x10 + (bar_number* 0x4); - return ConfigReadWord(PCIDeviceAddress, offsetToBar); -} \ No newline at end of file diff --git a/source/kernel/interrupts/idt/scancodes/set1.h b/source/kernel/drivers/ps-2/scancodes/set1.h similarity index 100% rename from source/kernel/interrupts/idt/scancodes/set1.h rename to source/kernel/drivers/ps-2/scancodes/set1.h diff --git a/source/kernel/interrupts/idt/idt.cpp b/source/kernel/interrupts/idt.cpp similarity index 98% rename from source/kernel/interrupts/idt/idt.cpp rename to source/kernel/interrupts/idt.cpp index 3000fae..7d99ca3 100644 --- a/source/kernel/interrupts/idt/idt.cpp +++ b/source/kernel/interrupts/idt.cpp @@ -1,8 +1,8 @@ #include "idt.h" -#include "../../drivers/pit/pit.h" -#include "../../drivers/ps-2/keyboard.h" -#include "../../cpu.h" -#include "../../memory/VirtualMemoryManager.h" +#include "../drivers/pit/pit.h" +#include "../drivers/ps-2/keyboard.h" +#include "../cpu.h" +#include "../memory/VirtualMemoryManager.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; @@ -327,7 +327,7 @@ void irq_handler (registers regs) { } -void init_idt(){ +void initidt(){ // Initialise the IDT pointer idt_ptr.length = sizeof(IDT_entry) * 255; idt_ptr.base = (uint32_t)&idt_table; diff --git a/source/kernel/interrupts/idt/idt.h b/source/kernel/interrupts/idt.h similarity index 93% rename from source/kernel/interrupts/idt/idt.h rename to source/kernel/interrupts/idt.h index e2a0bd5..0a87d8d 100644 --- a/source/kernel/interrupts/idt/idt.h +++ b/source/kernel/interrupts/idt.h @@ -2,10 +2,10 @@ #include #include -#include "../../drivers/vga/colors.h" -#include "../../drivers/pic/pic.h" +#include "../drivers/vga/colors.h" +#include "../drivers/pic/pic.h" -#include "../../terminal/kterm.h" +#include "../terminal/kterm.h" extern "C" { @@ -32,7 +32,7 @@ extern "C" { extern void idt_flush(uint32_t); void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags); - void init_idt(); + void initidt(); void irq_handler (registers regs); diff --git a/source/kernel/interrupts/idt/idt.s b/source/kernel/interrupts/idt.s similarity index 100% rename from source/kernel/interrupts/idt/idt.s rename to source/kernel/interrupts/idt.s diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index b83f2a6..2972314 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -12,6 +12,7 @@ extern "C" #include "memory/VirtualMemoryManager.h" #include "memory/KernelHeap.h" #include "memory/gdt/gdtc.h" +#include "memory/TaskStateSegment.h" #include "supervisorterminal/superVisorTerminal.h" @@ -19,7 +20,8 @@ extern "C" #include "drivers/vga/VBE.h" #include "drivers/pci/pci.h" #include "drivers/pit/pit.h" - +#include "drivers/acpi/acpi.h" +#include "drivers/ide/ide.h" #include "terminal/kterm.h" @@ -28,16 +30,13 @@ extern "C" #include "bootcheck.h" -#include "interrupts/idt/idt.h" +#include "interrupts/idt.h" #include "time.h" #include "cpu.h" #include "serial.h" #include "time.h" #include "definitions.h" - - - /* Copyright © Nigel Barink 2023 */ @@ -55,16 +54,22 @@ extern "C" void kernel_main () extern "C" void early_main() { init_serial(); - kterm_init(); - printf("Allocated blocks: 0x%x \n", GetUsedBlocks()); + initGDT(); - init_idt(); + //setup_tss(); + initidt(); + // Enable interrupts asm volatile("STI"); - + + ACPI::initialize(); + PCI_Enumerate(); + + TestIDEController(); + initHeap(); printf("Enable Protected mode and jump to kernel main\n"); @@ -84,7 +89,6 @@ extern "C" void early_main() pit_initialise(); - kernel_main(); } diff --git a/source/kernel/memory/TaskStateSegment.h b/source/kernel/memory/TaskStateSegment.h new file mode 100644 index 0000000..c4860c1 --- /dev/null +++ b/source/kernel/memory/TaskStateSegment.h @@ -0,0 +1,59 @@ +#pragma once +#include "gdt/gdtc.h" +#include "../../lib/include/string.h" + +struct TaskStateSegment { + uint32_t prev_tss; + uint32_t esp0; + uint32_t ss0; + // everythinge else is unused + uint32_t esp1; + uint32_t ss1; + uint32_t esp2; + uint32_t ss2; + uint32_t cr3; + uint32_t eip; + uint32_t eflags; + uint32_t eax; + uint32_t ecx; + uint32_t edx; + uint32_t ebx; + uint32_t esp; + uint32_t ebp; + uint32_t esi; + uint32_t edi; + uint32_t es; + uint32_t cs; + uint32_t ss; + uint32_t ds; + uint32_t fs; + uint32_t gs; + uint32_t ldt; + uint16_t trap; + uint16_t iomap_base; +}__attribute__((packed)); + + +TaskStateSegment tss0 = {}; + +inline void flush_tss(){ + asm volatile("mov (5 * 8) |0 , %eax; ltr %ax"); +} + + +void setup_tss(){ + + + // ensure the tss is zero'd + //memset((void*)&tss0, 0, sizeof(tss0)); + tss0.ss0 = (uint32_t) &(GlobalDescriptorTable[KERNEL_DATA_SEGMENT]); + uint32_t esp_addr =0 ; + asm volatile ("movl %%esp, %0" : "=a"(esp_addr)); + tss0.esp0 = esp_addr; + + + // Task Segment Descriptor + add_descriptor(TASK_STATE_SEGMENT, (unsigned long)&tss0, sizeof(tss0), 0x89, 0x0); + flush_tss(); +} + diff --git a/source/kernel/memory/gdt/gdtc.cpp b/source/kernel/memory/gdt/gdtc.cpp index 55e0b92..c7f15c9 100644 --- a/source/kernel/memory/gdt/gdtc.cpp +++ b/source/kernel/memory/gdt/gdtc.cpp @@ -1,17 +1,9 @@ #include "gdtc.h" #include "../../terminal/kterm.h" -#define NULL_SEGMENT 0 -#define KERNEL_CODE_SEGMENT 1 -#define KERNEL_DATA_SEGMENT 2 -#define USER_CODE_SEGMENT 3 -#define USER_DATA_SEGMENT 4 -#define TASK_STATE_SEGMENT 5 SegmentDescriptor GlobalDescriptorTable[6]; GlobalDescriptorTableDescriptor gdtDescriptor; -tss32 TaskStateSegment = {}; - void add_descriptor(int which , unsigned long base, unsigned long limit, unsigned char access, unsigned char granularity ){ @@ -32,9 +24,6 @@ void add_descriptor(int which , unsigned long base, unsigned long limit, unsigne void initGDT(){ - - printf("Init GDT!\n"); - // NULL segment add_descriptor(NULL_SEGMENT, 0,0,0,0); @@ -50,14 +39,9 @@ void initGDT(){ // User Data Segement add_descriptor(USER_DATA_SEGMENT, 0, 0xFFFFFFFF, 0xF2, 0xCF); - // Task Segment Descriptor - add_descriptor(TASK_STATE_SEGMENT, (unsigned long)&TaskStateSegment, sizeof(TaskStateSegment), 0x89, 0x0); - // init Gdt Descriptor gdtDescriptor.limit = ((sizeof(SegmentDescriptor ) * 5 ) - 1); gdtDescriptor.base = (unsigned int) (&GlobalDescriptorTable); - LoadGlobalDescriptorTable(); - } diff --git a/source/kernel/memory/gdt/gdtc.h b/source/kernel/memory/gdt/gdtc.h index adca78e..17c8ec0 100644 --- a/source/kernel/memory/gdt/gdtc.h +++ b/source/kernel/memory/gdt/gdtc.h @@ -1,5 +1,16 @@ #pragma once #include + + +#define NULL_SEGMENT 0 +#define KERNEL_CODE_SEGMENT 1 +#define KERNEL_DATA_SEGMENT 2 +#define USER_CODE_SEGMENT 3 +#define USER_DATA_SEGMENT 4 +#define TASK_STATE_SEGMENT 5 + + + struct SegmentDescriptor { unsigned short limit_low; unsigned short base_low; @@ -9,10 +20,7 @@ struct SegmentDescriptor { unsigned char base_high; }__attribute__((packed)); -struct tss32 { - uint64_t bits; - uint8_t other_bits :5; -}__attribute__((packed)); +extern SegmentDescriptor GlobalDescriptorTable[6]; struct GlobalDescriptorTableDescriptor{ unsigned short limit; diff --git a/source/kernel/PartitionTable/MBR/MasterBootRecord.h b/source/kernel/partitiontable/mbr/MasterBootRecord.h similarity index 100% rename from source/kernel/PartitionTable/MBR/MasterBootRecord.h rename to source/kernel/partitiontable/mbr/MasterBootRecord.h diff --git a/source/kernel/PartitionTable/MBR/PartitionTableEntry.h b/source/kernel/partitiontable/mbr/PartitionTableEntry.h similarity index 100% rename from source/kernel/PartitionTable/MBR/PartitionTableEntry.h rename to source/kernel/partitiontable/mbr/PartitionTableEntry.h diff --git a/source/kernel/supervisorterminal/superVisorTerminal.cpp b/source/kernel/supervisorterminal/superVisorTerminal.cpp index 73ee676..a178fd8 100644 --- a/source/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/source/kernel/supervisorterminal/superVisorTerminal.cpp @@ -1,8 +1,6 @@ #include "superVisorTerminal.h" #include "../drivers/ata/ataDevice.h" -#include "../drivers/acpi/acpi.h" -#include "../drivers/ide/ide.h" -#include "../PartitionTable/MBR/MasterBootRecord.h" +#include "../partitiontable/mbr/MasterBootRecord.h" #include "../filesystem/FAT/BiosParameterBlock.h" #include "../filesystem/FAT/DirectoryEntry.h" bool isRunning = true; @@ -43,18 +41,10 @@ void startSuperVisorTerminal(){ if( strncmp ("MEMORY" , command , characterCount) == 0 ) { // Show memory layout - printf("========= Memory ==========\n"); + printf("========= Memory (very inaccurate) ==========\n"); printf("Kernel MemoryMap:\n"); printf("kernel: 0x%x - 0x%x\n", &kernel_begin , &kernel_end); - printf("Frames used: 0x%x blocks of 4 KiB\n", 0); - const int bytesInGiB = 1073741824; - //int64_t bytesLeft = (bootinfo->memory->TotalMemory % bytesInGiB) / bytesInGiB; - //int64_t effectiveNumberOfGib = bootinfo->memory->TotalMemory / bytesInGiB; - - //int64_t GiBs = effectiveNumberOfGib + bytesLeft; - - //printf("Available Memory: %d bytes, %d GiB\n", bootinfo->memory->TotalMemory, GiBs ); - //printf("Reserved Memory: %d bytes\n", bootinfo->memory->ReservedMemory); + printf("Frames used: %d blocks of 4 KiB\n", GetUsedBlocks()); } if(strncmp("TEST", command, characterCount) == 0) @@ -76,14 +66,6 @@ void startSuperVisorTerminal(){ } if(strncmp("FAT", command, characterCount) == 0) { - printf("ACPI initialize!\n"); - ///ACPI::initialize(); - - // Enumerate the PCI bus - printf("PCI Enumeration\n"); - PCI_Enumerate(); - printf("TEST IDE Controller"); - TestIDEController(); int devNumber = 0 ; for ( auto device : ide_devices){ @@ -129,7 +111,7 @@ void startSuperVisorTerminal(){ i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); } - // Find the BiosParameter block + // Find the BiosParameter block uint16_t biosparameterblock[256]; ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, biosparameterblock); @@ -224,8 +206,15 @@ void startSuperVisorTerminal(){ - if(strncmp("glg", command, characterCount) == 0){ - printf("Why???"); + if(strncmp("DEVICES", command, characterCount) == 0){ + printf("================ CONNECTED DEVICES ===============\n"); + + + + + + + } diff --git a/source/lib/include/stack.h b/source/lib/include/stack.h new file mode 100644 index 0000000..0128bf6 --- /dev/null +++ b/source/lib/include/stack.h @@ -0,0 +1,73 @@ +#pragma once +#include "../../kernel/memory/KernelHeap.h" +#include + +template +class Stack { + public: + inline Stack() { + elements = (T[MAX_STACK_SIZE]) malloc(MAX_STACK_SIZE * sizeof(T)); + num = 0; + + } + + inline void Push(T element){ + num++; + if(num > MAX_STACK_SIZE) + grow(); + + element[num] = element; + } + + + inline T Pop() + { + T temp = elements[num]; + num --; + + return temp; + } + + inline bool isEmpty() + { + return num == 0; + } + + inline bool isFull() + { + return num == MAX_STACK_SIZE; + } + + + inline int count() + { + return num; + } + + inline ~Stack() + { + free(elements); + } + + + private: + unsigned int MAX_STACK_SIZE; + T[MAX_STACK_SIZE] elements; + unsigned int num; + + inline void grow (){ + MAX_STACK_SIZE = MAX_STACK_SIZE + (int)(MAX_STACK_SIZE / 4); + T[] new_elements =(T[MAX_STACK_SIZE]) malloc(MAX_STACK_SIZE * sizeof(T)); + + for ( int i = 0; i < num ; i++){ + new_elements[i] = elements[i]; + } + free(elements); + elements = new_elements; + + } + + + +}; + -- 2.39.5 From c9a036bfbb73c47fa820cd5a869281e122b0c957 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 13 Feb 2023 22:44:47 +0100 Subject: [PATCH 088/115] Ring 3 ready - Fixed issue with setting up the Task Segment Register --- source/kernel/boot/boot.s | 23 ++++++++++++-------- source/kernel/kernel.cpp | 13 ++++++----- source/kernel/memory/TaskStateSegment.h | 29 +++++++++++++------------ source/kernel/memory/gdt/gdtc.cpp | 3 +-- source/kernel/memory/gdt/gdtc.h | 1 - 5 files changed, 38 insertions(+), 31 deletions(-) diff --git a/source/kernel/boot/boot.s b/source/kernel/boot/boot.s index c5e9902..c5414f9 100644 --- a/source/kernel/boot/boot.s +++ b/source/kernel/boot/boot.s @@ -5,6 +5,7 @@ .section .bootstrap_stack, "aw", @nobits stack_bottom: .skip 16384 # 16 KiB +.globl stack_top stack_top: /* @@ -75,16 +76,7 @@ _start: 4: # At this point, paging is fully set up and enabled isPaging: - /* push the pointer to the Multiboot information structure*/ - pushl %ebx - /* push the magic value */ - pushl %eax - call prekernelSetup - - # Unmap the identity mapping as it is now unnecessary - # movl $0, boot_page_directory + 0 - # Reload cr3 to force tlb flush movl %cr3, %ecx movl %ecx, %cr3 @@ -97,6 +89,19 @@ isPaging: pushl $0 popf + + /* push the pointer to the Multiboot information structure*/ + pushl %ebx + + /* push the magic value */ + pushl %eax + call prekernelSetup + + # Unmap the identity mapping as it is now unnecessary + # movl $0, boot_page_directory + 0 + + + call early_main diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 2972314..f2d056f 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -36,6 +36,8 @@ extern "C" #include "serial.h" #include "time.h" #include "definitions.h" +extern "C" void LoadGlobalDescriptorTable(); + /* Copyright © Nigel Barink 2023 @@ -50,18 +52,19 @@ extern "C" void kernel_main () startSuperVisorTerminal(); } - extern "C" void early_main() { init_serial(); kterm_init(); + setup_tss(); initGDT(); - //setup_tss(); initidt(); - - + LoadGlobalDescriptorTable(); + flush_tss(); + printf("Memory setup complete!\n"); + // Enable interrupts asm volatile("STI"); @@ -73,7 +76,7 @@ extern "C" void early_main() initHeap(); printf("Enable Protected mode and jump to kernel main\n"); - + // Set the protected bit of control register 0 // this will put the CPU into protected mode diff --git a/source/kernel/memory/TaskStateSegment.h b/source/kernel/memory/TaskStateSegment.h index c4860c1..b41a4fb 100644 --- a/source/kernel/memory/TaskStateSegment.h +++ b/source/kernel/memory/TaskStateSegment.h @@ -34,26 +34,27 @@ struct TaskStateSegment { }__attribute__((packed)); -TaskStateSegment tss0 = {}; +TaskStateSegment tss0 ={}; -inline void flush_tss(){ - asm volatile("mov (5 * 8) |0 , %eax; ltr %ax"); +inline void flush_tss() +{ + asm volatile("mov $0x2B, %ax ; ltr %ax"); } - void setup_tss(){ - - // ensure the tss is zero'd - //memset((void*)&tss0, 0, sizeof(tss0)); - tss0.ss0 = (uint32_t) &(GlobalDescriptorTable[KERNEL_DATA_SEGMENT]); - uint32_t esp_addr =0 ; - asm volatile ("movl %%esp, %0" : "=a"(esp_addr)); - tss0.esp0 = esp_addr; - + memset((void*)&tss0, 0, sizeof(tss0)); + tss0.ss0 = (uint32_t) &GlobalDescriptorTable[KERNEL_DATA_SEGMENT]; + + extern uint32_t stack_top; + tss0.esp0 = (unsigned long)&stack_top; // Task Segment Descriptor - add_descriptor(TASK_STATE_SEGMENT, (unsigned long)&tss0, sizeof(tss0), 0x89, 0x0); - flush_tss(); + + uint32_t address = (unsigned long) &tss0; + uint32_t size = sizeof(tss0); + uint32_t limit = (address + size ); + + add_descriptor(TASK_STATE_SEGMENT, address, limit- 1, 0xE9, 0x0); } diff --git a/source/kernel/memory/gdt/gdtc.cpp b/source/kernel/memory/gdt/gdtc.cpp index c7f15c9..a73b776 100644 --- a/source/kernel/memory/gdt/gdtc.cpp +++ b/source/kernel/memory/gdt/gdtc.cpp @@ -40,8 +40,7 @@ void initGDT(){ add_descriptor(USER_DATA_SEGMENT, 0, 0xFFFFFFFF, 0xF2, 0xCF); // init Gdt Descriptor - gdtDescriptor.limit = ((sizeof(SegmentDescriptor ) * 5 ) - 1); + gdtDescriptor.limit = ((sizeof(SegmentDescriptor ) * 6 ) - 1); gdtDescriptor.base = (unsigned int) (&GlobalDescriptorTable); - LoadGlobalDescriptorTable(); } diff --git a/source/kernel/memory/gdt/gdtc.h b/source/kernel/memory/gdt/gdtc.h index 17c8ec0..bf914a0 100644 --- a/source/kernel/memory/gdt/gdtc.h +++ b/source/kernel/memory/gdt/gdtc.h @@ -32,5 +32,4 @@ struct GlobalDescriptorTableDescriptor{ void add_descriptor(int which , unsigned long base, unsigned long limit, unsigned char access, unsigned char granularity ); -extern "C" void LoadGlobalDescriptorTable(); void initGDT(); -- 2.39.5 From 4ce7cc093b0ed924f10ba8701c56121307f79e20 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 17 Feb 2023 14:42:42 +0100 Subject: [PATCH 089/115] Cleanup of PCI API --- source/kernel/drivers/ide/ide.h | 12 +- source/kernel/drivers/pci/pci.cpp | 289 +++++++++++------------------- source/kernel/drivers/pci/pci.h | 69 ++++--- source/kernel/kernel.cpp | 71 +++----- 4 files changed, 180 insertions(+), 261 deletions(-) diff --git a/source/kernel/drivers/ide/ide.h b/source/kernel/drivers/ide/ide.h index e7195de..1a1310d 100644 --- a/source/kernel/drivers/ide/ide.h +++ b/source/kernel/drivers/ide/ide.h @@ -56,7 +56,7 @@ inline void TestIDEController(){ int device =1 , function = 1; PCIBusAddress IDEControllerPCIAddress = PCIBusAddress{bus,device, function}; - uint8_t ProgIF = GetProgIF(IDEControllerPCIAddress); + uint8_t ProgIF = PCI::GetProgIF(IDEControllerPCIAddress); printf( "ProgIF: 0x%x\n" ,ProgIF); //CheckProgIF(ProgIF); @@ -66,15 +66,15 @@ inline void TestIDEController(){ uint32_t BAR0,BAR1,BAR2,BAR3, BAR4; - BAR0 = ReadBAR(IDEControllerPCIAddress, 0); + BAR0 = PCI::ReadBAR(IDEControllerPCIAddress, 0); - BAR1 = ReadBAR(IDEControllerPCIAddress, 1); + BAR1 = PCI::ReadBAR(IDEControllerPCIAddress, 1); - BAR2 = ReadBAR(IDEControllerPCIAddress, 2); + BAR2 = PCI::ReadBAR(IDEControllerPCIAddress, 2); - BAR3 = ReadBAR(IDEControllerPCIAddress, 3); + BAR3 = PCI::ReadBAR(IDEControllerPCIAddress, 3); - BAR4 = ReadBAR(IDEControllerPCIAddress, 4); + BAR4 = PCI::ReadBAR(IDEControllerPCIAddress, 4); // All bars are return 0xffffff for some as of yet mysterious reason! printf( "BAR 0: 0x%x\n", BAR0); diff --git a/source/kernel/drivers/pci/pci.cpp b/source/kernel/drivers/pci/pci.cpp index 25c5f45..ba0fade 100644 --- a/source/kernel/drivers/pci/pci.cpp +++ b/source/kernel/drivers/pci/pci.cpp @@ -1,107 +1,66 @@ #include "pci.h" -#define PCI_BUS_ADDR_SHIFT 16 -#define PCI_DEVICE_ADDR_SHIFT 11 -#define PCI_FUNCTION_ADDR_SHIFT 8 -#define PCI_ENABLE_ADDR_SHIFT 31 +void PCI::Scan(){ + + int devicesFound = 0; -const char* GetClassCodeName (uint64_t ClassCode ) { - - switch (ClassCode) - { - case 0x0 : - return "Unclassified"; - break; + printf("Start finding devices, Found: %d devices"); + // loop through all possible busses, devices and their functions; + for( int bus = 0 ; bus < 256 ; bus++) + { + + for(int device = 0; device < 32 ; device ++) + { + int function = 0; - case 0x1: - return "Mass Storage Controller"; - break; + uint64_t DeviceIdentify = PCI::ConfigReadWord(bus, device, function,0x0); + uint32_t DeviceID = GetDevice(bus, device, function) >> 16; - case 0x2: - return "Network Controller"; - break; + if( DeviceID != 0xFFFF){ + PCIBusAddress busAddress = + PCIBusAddress{bus, device, function }; - case 0x3: - return "Display Controller"; - break; + PrintPCIDevice(busAddress); - case 0x4: - return "Multimedia Controller"; - break; + // iterate over the functions if it is a multi function device! + if( PCI::IsMultiFunctionDevice(busAddress) ){ + printf("Multi function device! \n"); + printf("Check remaining Functions\n"); + for ( function = 1 ; function < 8; function++) + { + uint32_t DeviceID = GetDevice(bus, device, function) >> 16; - case 0x5: - return "Memory Controller"; - break; - - case 0x6: - return "Bridge"; - break; + if( DeviceID != 0xFFFF){ + PCIBusAddress busAddress2 = PCIBusAddress{bus, device, function}; + PrintPCIDevice(busAddress2); + devicesFound++; + } + } + + } - case 0x7 : - return "Simple Communication Controller"; - break; - - case 0x8: - return "Base System Peripheral"; - break; - - case 0x9: - return "Input Device Controller"; - break; - - case 0xA: - return "Docking station"; - break; - case 0xB: - return "Processor"; - break; - - case 0xC: - return "Serial Bus Controller"; - break; - - case 0xD: - return "Wireless Controller"; - break; - - case 0xE: - return "Intelligent Controller"; - break; - - case 0xF: - return "Satellite Communication Controller"; - break; - - case 0x10: - return "Encryption Controller"; - break; - - case 0x11: - return "Signal Processing Controller"; - break; - - case 0x12: - return "Processing Accelerator"; - break; - - case 0x13: - return "Non-Essential Instrumentation"; - break; - - default: - return "Unknown"; - break; + + devicesFound++; + } + } + } - + + printf("Found %d PCI devices!\n", devicesFound); } -const char* getVendor( uint32_t VendorID){ +const char* PCI::getClassName (uint8_t ClassCode){ + bool isKnown = (ClassCode < PCI::KnownClassCodes); + return isKnown ? PCI::ClassCodeNames[ClassCode].name : "Unknown ClassCode"; +} + +const char* PCI::getVendor( uint32_t VendorID){ switch (VendorID) { case 0x8086: return "Intel Corporation"; break; - + case 0x10DE: return "NVIDIA Corporation"; break; @@ -129,125 +88,77 @@ const char* getVendor( uint32_t VendorID){ } -uint32_t ConfigReadWord ( PCIBusAddress& PCIDeviceAddress , uint8_t offset){ - outl(CONFIG_ADDRESS , PCIDeviceAddress.getAddress() | offset ); +uint64_t PCI::GetDevice (int bus, int device, int function ){ + return PCI::ConfigReadWord(bus, device, function,0x0); +} + +bool PCI::IsMultiFunctionDevice(PCIBusAddress& PCIDeviceAddress) +{ + uint32_t header_information = ConfigReadWord(PCIDeviceAddress, 0xC); + return (((header_information>>16) + & 0x80) + >> 7 ); +} + +uint16_t PCI::GetClassCodes( PCIBusAddress& PCIDeviceAddress ){ + return (uint16_t)(ConfigReadWord(PCIDeviceAddress, 0x8) >> 16); +} + +uint8_t PCI::GetHeaderType( PCIBusAddress& PCIDeviceAddress ){ + uint32_t header_information = ConfigReadWord(PCIDeviceAddress , 0xC); + return (uint8_t) ( + ((header_information >> 16) //Get higher half + & 0x00FF) // Select the last two bytes + & 0x7F ); // Mask bit 7 as it indicates if the device is a mulit function device! +} + +uint32_t PCI::ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offset){ + uint32_t address; + + address = (uint32_t) ( + ((uint32_t) 1 << PCI_ENABLE_ADDR_SHIFT) | + ((uint32_t)bus << PCI_BUS_ADDR_SHIFT) | + ((uint32_t)device << PCI_DEVICE_ADDR_SHIFT) | + ((uint32_t)func << PCI_FUNCTION_ADDR_SHIFT) | + offset ); + + outl(CONFIG_ADDRESS, address); + + return inl(CONFIG_DATA); } -uint8_t GetProgIF (PCIBusAddress& PCIDeviceAddress){ +uint8_t PCI::GetProgIF (PCIBusAddress& PCIDeviceAddress){ uint32_t data = ConfigReadWord(PCIDeviceAddress, 0x8); return ((data >> 8) & 0xFF); } -uint32_t ReadBAR ( PCIBusAddress& PCIDeviceAddress, int bar_number){ - int offsetToBar = 0x10 + (bar_number* 0x4); - return ConfigReadWord(PCIDeviceAddress, offsetToBar); -} - -uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offset){ - uint32_t address; - - address = (uint32_t) ( - ((uint32_t) 1 << PCI_ENABLE_ADDR_SHIFT) | - ((uint32_t)bus << PCI_BUS_ADDR_SHIFT) | - ((uint32_t)device << PCI_DEVICE_ADDR_SHIFT) | - ((uint32_t)func << PCI_FUNCTION_ADDR_SHIFT) | - offset ); - - outl(CONFIG_ADDRESS, address); - - +uint32_t PCI::ConfigReadWord ( PCIBusAddress& PCIDeviceAddress , uint8_t offset){ + outl(CONFIG_ADDRESS , PCIDeviceAddress.getAddress() | offset ); return inl(CONFIG_DATA); } -uint8_t GetHeaderType( PCIBusAddress& PCIDeviceAddress ){ - uint32_t header_information = ConfigReadWord(PCIDeviceAddress , 0xC); - return (uint8_t) ( - ((header_information >> 16) //Get higher half - & 0x00FF) // Select the last two bytes - & 0x7F ); // Mask bit 7 as it indicates if the device is a mulit function device! + +uint32_t PCI::ReadBAR ( PCIBusAddress& PCIDeviceAddress, int bar_number){ + int offsetToBar = 0x10 + (bar_number* 0x4); + return ConfigReadWord(PCIDeviceAddress, offsetToBar); } -uint16_t GetClassCodes( PCIBusAddress& PCIDeviceAddress ){ - uint32_t classcodes = ConfigReadWord(PCIDeviceAddress, 0x8); - return (uint16_t)((uint32_t)classcodes >> 16); - -} - -bool IsMultiFunctionDevice(PCIBusAddress& PCIDeviceAddress){ - uint32_t header_information = ConfigReadWord(PCIDeviceAddress, 0xC); - return (((header_information>>16) - & 0x80) - >> 7 ); -} - -void PrintPCIDeviceInfo (PCIBusAddress& PCIDeviceAddress) +void PCI::PrintPCIDevice (PCIBusAddress& PCIDeviceAddress) { - uint32_t DeviceID = (GetDevice(PCIDeviceAddress.bus, PCIDeviceAddress.device, PCIDeviceAddress.function) >> 16); - uint32_t VendorID = GetDevice(PCIDeviceAddress.bus, PCIDeviceAddress.device, PCIDeviceAddress.function) & 0xFFFF; + uint32_t DeviceID = (PCI::GetDevice(PCIDeviceAddress.bus, PCIDeviceAddress.device, PCIDeviceAddress.function) >> 16); + uint32_t VendorID = PCI::GetDevice(PCIDeviceAddress.bus, PCIDeviceAddress.device, PCIDeviceAddress.function) & 0xFFFF; printf("Device found!\n"); printf("Bus: %d, Device: %d, function: %d \n", PCIDeviceAddress.bus, PCIDeviceAddress.device, PCIDeviceAddress.function); - printf("DeviceID: 0x%x, Vendor: %s\n", - DeviceID - , getVendor(VendorID) ); + printf("DeviceID: 0x%x, Vendor: %s\n", + DeviceID + , PCI::getVendor(VendorID) ); - - - - uint8_t header_type = GetHeaderType(PCIDeviceAddress); + uint8_t header_type = PCI::GetHeaderType(PCIDeviceAddress); printf( "Header type: 0x%x\n", header_type); - uint16_t deviceClasses = GetClassCodes(PCIDeviceAddress); - printf("class: %s, subClass: %d\n\n", GetClassCodeName((deviceClasses >>8)), deviceClasses & 0xFF); + uint16_t deviceClasses = PCI::GetClassCodes(PCIDeviceAddress); -} - -void PCI_Enumerate(){ - - int devicesFound = 0; - - printf("Start finding devices, Found: %d devices"); - // loop through all possible busses, devices and their functions; - for( int bus = 0 ; bus < 256 ; bus++) - { - - for(int device = 0; device < 32 ; device ++) - { - int function = 0; - - uint64_t DeviceIdentify = ConfigReadWord(bus, device, function,0x0); - uint32_t DeviceID = GetDevice(bus, device, function) >> 16; - - if( DeviceID != 0xFFFF){ - PCIBusAddress busAddress = - PCIBusAddress{bus, device, function }; - - PrintPCIDeviceInfo(busAddress); - - // iterate over the functions if it is a multi function device! - if( IsMultiFunctionDevice(busAddress) ){ - printf("Multi function device! \n"); - printf("Check remaining Functions\n"); - for ( function = 1 ; function < 8; function++) - { - uint32_t DeviceID = GetDevice(bus, device, function) >> 16; - - if( DeviceID != 0xFFFF){ - PCIBusAddress busAddress2 = PCIBusAddress{bus, device, function}; - PrintPCIDeviceInfo(busAddress2); - devicesFound++; - } - } - - } - - - devicesFound++; - } - } - - } - - printf("Found %d PCI devices!\n", devicesFound); -} + printf("class: %s, subClass: %d\n\n", PCI::getClassName((deviceClasses >> 8)), deviceClasses & 0xFF); +} \ No newline at end of file diff --git a/source/kernel/drivers/pci/pci.h b/source/kernel/drivers/pci/pci.h index 7e60de4..e46a77e 100644 --- a/source/kernel/drivers/pci/pci.h +++ b/source/kernel/drivers/pci/pci.h @@ -7,30 +7,55 @@ // Configuration Space Access Mechanism #1 #define CONFIG_ADDRESS 0xCF8 // Configuration adress that is to be accessed #define CONFIG_DATA 0xCFC // Will do the actual configuration operation +#define PCI_BUS_ADDR_SHIFT 16 +#define PCI_DEVICE_ADDR_SHIFT 11 +#define PCI_FUNCTION_ADDR_SHIFT 8 +#define PCI_ENABLE_ADDR_SHIFT 31 -extern const char* ClassCodeTable [0x13]; +class PCI { +public: + static void Scan(); + static uint32_t ConfigReadWord ( PCIBusAddress& PCIDeviceAddress , uint8_t offset); + static uint8_t GetProgIF (PCIBusAddress& PCIDeviceAddress); + static uint32_t ReadBAR ( PCIBusAddress& PCIDeviceAddress, int bar_number); + static uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offset); + static uint8_t GetHeaderType( PCIBusAddress& PCIDeviceAddress ); + static uint16_t GetClassCodes( PCIBusAddress& PCIDeviceAddress ); + static bool IsMultiFunctionDevice(PCIBusAddress& PCIDeviceAddress); + static uint64_t GetDevice (int bus, int device, int function ); -// Note: this could be used to make the api for receiving PCI class codes a bit -// nicer. -struct ClassCodes { - uint8_t ClassCode; - uint8_t DeviceClass; -}__attribute__((packed)); -uint32_t ConfigReadWord (uint8_t bus, uint8_t device, uint8_t func, uint8_t offset); -uint32_t ConfigReadWord ( PCIBusAddress& PCIDeviceAddress , uint8_t offset); + static const char* getClassName (uint8_t ClassCode); + static const char* getVendor( uint32_t VendorID); + static void PrintPCIDevice(PCIBusAddress& PCIDevice); - inline uint64_t GetDevice (int bus, int device, int function ){ - return ConfigReadWord(bus, device, function,0x0); - } +private: + struct ClassCode { + const char* name; + uint8_t code; + }; + static constexpr ClassCode ClassCodeNames []= { + {"Unclassified", 0x0}, + {"MassStorage Controller", 0x1}, + {"Network Controller", 0x2}, + {"Display Controller", 0x3}, + {"Multimedia Controller", 0x4}, + {"Memory Controller", 0x5}, + {"Bridge", 0x6}, + {"Simple Communication Controller", 0x7}, + {"Base System Peripheral", 0x8}, + {"Input Device Controller", 0x9}, + {"Docking Station", 0xA}, + {"Processor", 0xB}, + {"Serial Bus Controller", 0xC}, + { "Wireless Controller", 0xD}, + {"Intelligent Controller", 0xE}, + {"Satellite Communication Controller", 0xF}, + {"Encryption Controller", 0x10}, + {"Signal Processing Controller", 0x11}, + { "Processing Accelerator", 0x12}, + { "Non-Essential Instrumentation", 0x13} + }; + static const uint8_t KnownClassCodes = sizeof(ClassCodeNames) / sizeof(ClassCode); +}; -uint8_t GetHeaderType( PCIBusAddress& PCIDeviceAddress ); - -uint16_t GetClassCodes( PCIBusAddress& PICDeviceAddress ); -const char* getVendor( uint64_t VendorID); -const char* GetClassCodeName (uint64_t ClassCode ); - -uint8_t GetProgIF (PCIBusAddress& PCIDeviceAddress); -void PCI_Enumerate(); - -uint32_t ReadBAR ( PCIBusAddress& PCIDeviceAddress, int bar_number); \ No newline at end of file diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index f2d056f..62a3ff0 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -1,22 +1,16 @@ - -extern "C" -{ - #include "../lib/include/string.h" +/* + Copyright © Nigel Barink 2023 +*/ +extern "C"{ +#include "../lib/include/string.h" } -#include "prekernel/bootstructure.h" - #include "memory/memory.h" -#include "memory/memoryinfo.h" -#include "memory/memory.h" -#include "memory/VirtualMemoryManager.h" #include "memory/KernelHeap.h" #include "memory/gdt/gdtc.h" #include "memory/TaskStateSegment.h" - #include "supervisorterminal/superVisorTerminal.h" -#include "drivers/io/io.h" #include "drivers/vga/VBE.h" #include "drivers/pci/pci.h" #include "drivers/pit/pit.h" @@ -24,59 +18,50 @@ extern "C" #include "drivers/ide/ide.h" #include "terminal/kterm.h" - -#include "prekernel/multiboot.h" -#include "bootinfo.h" - -#include "bootcheck.h" - #include "interrupts/idt.h" -#include "time.h" -#include "cpu.h" #include "serial.h" -#include "time.h" -#include "definitions.h" extern "C" void LoadGlobalDescriptorTable(); - -/* - Copyright © Nigel Barink 2023 -*/ - -extern "C" void kernel_main () +void set_protected_bit() { - /* - * Show a little banner for cuteness - */ - printf("|=== BarinkOS ===|\n"); - startSuperVisorTerminal(); -} + // Set the protected bit of control register 0 + // this will put the CPU into protected mode + // NOTE: This should really be a assembly procedure + // We cant directly write to control register 0 + // therefor we copy the value of control register 0 into eax + // once we are done manipulating the value we write the value in + // eax back to control register 0 -extern "C" void early_main() + asm volatile("mov %cr0, %eax "); + asm volatile("or $1, %eax"); + asm volatile("mov %eax, %cr0"); +} + +extern "C" void kernel () { + init_serial(); kterm_init(); - setup_tss(); initGDT(); initidt(); LoadGlobalDescriptorTable(); flush_tss(); printf("Memory setup complete!\n"); - + // Enable interrupts asm volatile("STI"); + initHeap(); + + pit_initialise(); ACPI::initialize(); - PCI_Enumerate(); + PCI::Scan(); - TestIDEController(); - - initHeap(); + TestIDEController(); printf("Enable Protected mode and jump to kernel main\n"); - // Set the protected bit of control register 0 // this will put the CPU into protected mode @@ -92,6 +77,4 @@ extern "C" void early_main() pit_initialise(); - kernel_main(); - -} +} \ No newline at end of file -- 2.39.5 From ecab248cd6643a5427ffbb21795477ab35c48427 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 17 Feb 2023 14:46:44 +0100 Subject: [PATCH 090/115] Clean up jump into RING 3 --- source/kernel/boot/boot.s | 18 ++++++-- source/kernel/definitions.h | 2 +- source/kernel/kernel.cpp | 20 ++++----- .../supervisorterminal/superVisorTerminal.cpp | 44 +++++++++++-------- .../supervisorterminal/superVisorTerminal.h | 2 +- 5 files changed, 51 insertions(+), 35 deletions(-) diff --git a/source/kernel/boot/boot.s b/source/kernel/boot/boot.s index c5414f9..ca822c4 100644 --- a/source/kernel/boot/boot.s +++ b/source/kernel/boot/boot.s @@ -99,11 +99,9 @@ isPaging: # Unmap the identity mapping as it is now unnecessary # movl $0, boot_page_directory + 0 - - - call early_main + call kernel cli 1: hlt @@ -115,4 +113,18 @@ isPaging: .include "./source/kernel/irq_table.s" .include "./source/kernel/interrupts/idt.s" +.globl jump_usermode +jump_usermode: + mov $((4*8) | 3) , %ax + mov %ax, %ds + mov %ax, %es + mov %ax, %fs + mov %ax, %gs + mov %esp, %eax + push $( (3*8) | 3) + push %eax + pushf + push $( ( 3 * 8) | 3) + push startSuperVisorTerminal + iret diff --git a/source/kernel/definitions.h b/source/kernel/definitions.h index 942949d..c29df40 100644 --- a/source/kernel/definitions.h +++ b/source/kernel/definitions.h @@ -4,6 +4,6 @@ */ #define __DEBUG__ false -#define KERNEL_VERSION 0 +#define KERNEL_VERSION 0.03 #define ARCHITECTURE "I386" diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 62a3ff0..5e0dd90 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -21,6 +21,7 @@ extern "C"{ #include "interrupts/idt.h" #include "serial.h" extern "C" void LoadGlobalDescriptorTable(); +extern "C" void jump_usermode(); void set_protected_bit() { @@ -63,18 +64,13 @@ extern "C" void kernel () printf("Enable Protected mode and jump to kernel main\n"); - // Set the protected bit of control register 0 - // this will put the CPU into protected mode - // NOTE: This should really be a assembly procedure - // We cant directly write to control register 0 - // therefor we copy the value of control register 0 into eax - // once we are done manipulating the value we write the value in - // eax back to control register 0 + set_protected_bit(); - asm volatile("mov %cr0, %eax "); - asm volatile("or $1, %eax"); - asm volatile("mov %eax, %cr0"); - - pit_initialise(); +#ifdef USERMODE_RELEASE + // Lets jump into user mode + jump_usermode(); +#else + startSuperVisorTerminal(); +#endif } \ No newline at end of file diff --git a/source/kernel/supervisorterminal/superVisorTerminal.cpp b/source/kernel/supervisorterminal/superVisorTerminal.cpp index a178fd8..1a5cc67 100644 --- a/source/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/source/kernel/supervisorterminal/superVisorTerminal.cpp @@ -4,7 +4,13 @@ #include "../filesystem/FAT/BiosParameterBlock.h" #include "../filesystem/FAT/DirectoryEntry.h" bool isRunning = true; -void startSuperVisorTerminal(){ +extern "C" void startSuperVisorTerminal() +{ + /* + * Show a little banner for cuteness + */ + printf("|=== BarinkOS ===|\n"); + while (isRunning){ printf("SUPERVISOR:>$ " ); @@ -115,7 +121,7 @@ void startSuperVisorTerminal(){ uint16_t biosparameterblock[256]; ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, biosparameterblock); - BiosParameterBlock* bpb = (BiosParameterBlock*) biosparameterblock; + auto* bpb = (BiosParameterBlock*) biosparameterblock; printf("\nBPB: Bytes per Sector %d\n", bpb->BytesPerSector ); @@ -138,8 +144,8 @@ void startSuperVisorTerminal(){ ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); // Show data in terminal - for(int i = 0; i < 256; i++ ) { - printf("%x ", FAT[i]); + for(unsigned short i : FAT) { + printf("%x ", i); } kterm_put('\n'); @@ -149,33 +155,35 @@ void startSuperVisorTerminal(){ uint16_t data2 [256]; ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, RootDirectoryRegion, data2 ); - DirectoryEntry* RootDirectory = (DirectoryEntry*) data2; + auto* RootDirectory = (DirectoryEntry*) data2; // List files in root for(int i= 0; i < bpb->NumberOfDirectoryEntries ; i++ ) { - DirectoryEntry* entry = (DirectoryEntry*)((uint32_t) RootDirectory + (i * sizeof(DirectoryEntry))); + auto* entry = (DirectoryEntry*)((uint32_t) RootDirectory + (i * sizeof(DirectoryEntry))); if( entry->filename[0] == (uint8_t) 0x00 ) break; // There are no more entries in this directory or the entry is free - if( entry->attribute & 0x01 == 0x01 || entry->attribute & 0x20 == 0x20) + if( (entry->attribute & 0x01) == 0x01 || (entry->attribute & 0x20) == 0x20) continue; // Skip listing if hidden or Achieve flag is set // Print the filename; - for( int n = 0; n < 8; n++ ){ - if(entry->filename[n] == 0x20) + for(char n : entry->filename){ + if(n == 0x20) break; - kterm_put(entry->filename[n]); - }kterm_put('\n'); + kterm_put(n); + } + kterm_put('\n'); - for( int n = 0; n < 3; n++){ - kterm_put(entry->Extension[n]); - }kterm_put('\n'); + for(unsigned char n : entry->Extension){ + kterm_put(n); + } + kterm_put('\n'); printf("Attribute: %x \n" , entry->attribute); printf("FileSize: %d Bytes\n", entry->FilesizeInBytes); - if( entry->FilesizeInBytes != 0x0 || entry->attribute & 0x8 == 0x0){ + if( entry->FilesizeInBytes != 0x0 || (entry->attribute & 0x8) == 0x0){ printf("Show contents"); printf( "Start cluster of the file: 0x%x\n" , entry->StartingCluster); @@ -187,11 +195,11 @@ void startSuperVisorTerminal(){ uint16_t dataBlob [256]; ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob ); - for( int n = 0; n < 256; n++) + for(unsigned short n : dataBlob) { - kterm_put(dataBlob[n] & 0x00ff); + kterm_put(n & 0x00ff); - kterm_put(dataBlob[n] >> 8); + kterm_put(n >> 8); }kterm_put('\n'); diff --git a/source/kernel/supervisorterminal/superVisorTerminal.h b/source/kernel/supervisorterminal/superVisorTerminal.h index 3ca186e..ad3c39b 100644 --- a/source/kernel/supervisorterminal/superVisorTerminal.h +++ b/source/kernel/supervisorterminal/superVisorTerminal.h @@ -8,4 +8,4 @@ extern "C" { #include "../../lib/include/string.h" } -void startSuperVisorTerminal(); \ No newline at end of file +extern "C" void startSuperVisorTerminal(); \ No newline at end of file -- 2.39.5 From 133c16cae70983cf901988aab345d529dc3cc91c Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 17 Feb 2023 16:27:36 +0100 Subject: [PATCH 091/115] Added CPUID based checks --- Makefile | 4 +- source/kernel/i386/README.md | 2 + source/kernel/i386/processor.cpp | 73 +++++++++++++++++++ source/kernel/i386/processor.h | 29 ++++++++ source/kernel/kernel.cpp | 12 ++- .../supervisorterminal/superVisorTerminal.cpp | 3 +- 6 files changed, 117 insertions(+), 6 deletions(-) create mode 100644 source/kernel/i386/README.md create mode 100644 source/kernel/i386/processor.cpp create mode 100644 source/kernel/i386/processor.h diff --git a/Makefile b/Makefile index c48fc85..95e595f 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o SRC_DIR = source BUILD_DIR = build @@ -128,6 +128,8 @@ $(BUILD_DIR)/prekernel.o: $(BUILD_DIR)/cpu.o: $(CPP) -c $(SRC_DIR)/kernel/cpu.cpp -o $(BUILD_DIR)/cpu.o $(CFLAGS) -fno-exceptions -fno-rtti +$(BUILD_DIR)/processor.o: + $(CPP) -c $(SRC_DIR)/kernel/i386/processor.cpp -o $(BUILD_DIR)/processor.o $(CFLAGS) -fno-exceptions -fno-rtti # Assembly -> Object files diff --git a/source/kernel/i386/README.md b/source/kernel/i386/README.md new file mode 100644 index 0000000..6de2022 --- /dev/null +++ b/source/kernel/i386/README.md @@ -0,0 +1,2 @@ +# architecture specific implementations +## This will contain I386 Architecture specific implementations diff --git a/source/kernel/i386/processor.cpp b/source/kernel/i386/processor.cpp new file mode 100644 index 0000000..cc58fef --- /dev/null +++ b/source/kernel/i386/processor.cpp @@ -0,0 +1,73 @@ +// +// Created by nigel on 17/02/23. +// + +#include "processor.h" + + +uint32_t processor::cap_page; +uint32_t processor::cap_page1; +uint32_t processor::cap_page7 ; + +void processor::initialize() +{ + + asm volatile ("movl $0x80000001, %%eax;" + "CPUID;" + "movl %%edx, %0" + :: "m"(cap_page)); + + asm volatile ("movl $0x01, %%eax; " + "CPUID;" + "movl %%edx, %0" + :: "m"(cap_page1)); + + asm volatile ("movl $0x07, %%eax;" + "movl $0x0, %%ecx;" + "CPUID;" + "movl %%edx, %0" + :: "m"(cap_page7)); + +} + +bool processor::hasAMXExtension() +{ + return (cap_page7 & AMX_TYPE::AMX_BF16) || (cap_page7 & AMX_TYPE::AMX_TILE) || (cap_page7 & AMX_TYPE::AMX_INT8); +} + + +/* + * PSE: page-size extensions for 32-bit paging. + * If CPUID.01H:EDX.PSE [bit 3] = 1, CR4.PSE may be set to 1, enabling support for 4-MByte pages with 32-bit paging + */ +bool processor::has32bitPagingSupport() { + // is the PSE bit set + return cap_page1 & (0x1 << 3); +} + +/* + * PAE: physical-address extension. + * If CPUID.01H:EDX.PAE [bit 6] = 1, CR4.PAE may be set to 1, enabling PAE paging (this setting is also required + * for 4-level paging and 5-level paging). + */ +bool processor::hasPAEExtension(){ + return cap_page1 & (0x1 << 6); +} + +/* + * PGE: global-page support. + * If CPUID.01H:EDX.PGE [bit 13] = 1, CR4.PGE may be set to 1, enabling the global-page feature (see Section + * 4.10.2.4). + */ +bool processor::hasPageSupport(){ + return cap_page1 & (0x1 << 13); +} + +/* + * Page1GB: 1-GByte pages. + * If CPUID.80000001H:EDX.Page1GB [bit 26] = 1, 1-GByte pages may be supported with 4-level paging and 5- + * level paging (see Section 4.5). + */ +bool processor::gigabytePages() { + return cap_page & (0x1 << 26); +} \ No newline at end of file diff --git a/source/kernel/i386/processor.h b/source/kernel/i386/processor.h new file mode 100644 index 0000000..b2d6286 --- /dev/null +++ b/source/kernel/i386/processor.h @@ -0,0 +1,29 @@ +// +// Created by nigel on 17/02/23. +// +#pragma once +#include "../terminal/kterm.h" +class processor { +public: + static void initialize(); + + // Based on information from https://en.wikichip.org/wiki/x86/amx#Detection + enum AMX_TYPE{ + AMX_BF16 = (0x1 << 22), + AMX_TILE = (0x1 << 24), + AMX_INT8 = (0x1 << 25) + }; + static bool hasAMXExtension(); + static bool has32bitPagingSupport(); + static bool hasPageSupport(); + static bool gigabytePages(); + + static bool hasPAEExtension(); + +private: + static uint32_t cap_page; + static uint32_t cap_page1; + static uint32_t cap_page7; + + +}; diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 5e0dd90..3b10a2b 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -10,19 +10,20 @@ extern "C"{ #include "memory/gdt/gdtc.h" #include "memory/TaskStateSegment.h" #include "supervisorterminal/superVisorTerminal.h" - #include "drivers/vga/VBE.h" #include "drivers/pci/pci.h" #include "drivers/pit/pit.h" #include "drivers/acpi/acpi.h" #include "drivers/ide/ide.h" - +#include "i386/processor.h" #include "terminal/kterm.h" #include "interrupts/idt.h" #include "serial.h" + extern "C" void LoadGlobalDescriptorTable(); extern "C" void jump_usermode(); + void set_protected_bit() { // Set the protected bit of control register 0 @@ -57,10 +58,13 @@ extern "C" void kernel () pit_initialise(); - ACPI::initialize(); + // ACPI::initialize(); PCI::Scan(); - TestIDEController(); + //TestIDEController(); + + + processor::initialize(); printf("Enable Protected mode and jump to kernel main\n"); diff --git a/source/kernel/supervisorterminal/superVisorTerminal.cpp b/source/kernel/supervisorterminal/superVisorTerminal.cpp index 1a5cc67..ea2cc32 100644 --- a/source/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/source/kernel/supervisorterminal/superVisorTerminal.cpp @@ -91,7 +91,8 @@ extern "C" void startSuperVisorTerminal() }; - + // FIXME: If no drive is connected we continue trying to read from + // a not connected drive! ATA_DEVICE::Identify((uint16_t) BUS_PORT::Primary, DEVICE_DRIVE::MASTER); const int C = 0; -- 2.39.5 From 490529099b0f378c4179bcbe8bf815a8b0bca1fc Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 17 Feb 2023 21:52:03 +0100 Subject: [PATCH 092/115] Started implementing the virtual file system - The FAT command is no longer available - At Startup the FileSystem initialise funciton is called, it should execute the same code as the FAT command did. - ACPI::initialise is commented out because it causes a Exception --- Makefile | 12 +- source/kernel/drivers/acpi/acpi.cpp | 3 +- source/kernel/drivers/acpi/rsdp.cpp | 5 +- source/kernel/filesystem/FAT/FAT16.cpp | 0 source/kernel/filesystem/FAT/FAT16.h | 8 - source/kernel/kernel.cpp | 12 +- .../supervisorterminal/superVisorTerminal.cpp | 150 +------ source/kernel/vfs/File.h | 9 - source/kernel/vfs/VFS.cpp | 376 ++++++++++++++++-- source/kernel/vfs/VFS.h | 91 ++++- 10 files changed, 429 insertions(+), 237 deletions(-) delete mode 100644 source/kernel/filesystem/FAT/FAT16.cpp delete mode 100644 source/kernel/filesystem/FAT/FAT16.h delete mode 100644 source/kernel/vfs/File.h diff --git a/Makefile b/Makefile index 95e595f..ae3954c 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/VFS.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o SRC_DIR = source BUILD_DIR = build @@ -42,7 +42,13 @@ test: test_iso: $(EMULATOR) -boot d -cdrom $(BUILD_DIR)/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-reboot -no-shutdown -test_disk: +test_disk: all + sudo losetup /dev/loop9 build/disk.img + sudo mount /dev/loop9 /mnt + sudo cp build/myos.bin /mnt/boot/myos.bin + sudo umount /mnt + sudo losetup -d /dev/loop9 + $(EMULATOR) -boot d -drive format=raw,file=build/disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo @@ -103,6 +109,8 @@ $(BUILD_DIR)/acpi.o: $(BUILD_DIR)/pit.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/pit/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti +$(BUILD_DIR)/VFS.o: + $(CPP) -c $(SRC_DIR)/kernel/vfs/VFS.cpp -o $(BUILD_DIR)/VFS.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/keyboard.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/ps-2/keyboard.cpp -o $(BUILD_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/source/kernel/drivers/acpi/acpi.cpp b/source/kernel/drivers/acpi/acpi.cpp index 6366d6f..cf73c27 100644 --- a/source/kernel/drivers/acpi/acpi.cpp +++ b/source/kernel/drivers/acpi/acpi.cpp @@ -9,6 +9,7 @@ void ACPI::initialize(){ // Find the Root System Description Pointer ACPI::rsd_ptr = FindRSD(); printRSD(rsd_ptr); + // Get the Root System Description Table - ACPI::rsd_table = getRSDT(rsd_ptr); + ACPI::rsd_table = getRSDT((RSDPTR*)((uint32_t)rsd_ptr + 0xC00000000)); } \ No newline at end of file diff --git a/source/kernel/drivers/acpi/rsdp.cpp b/source/kernel/drivers/acpi/rsdp.cpp index 5f4991f..910fadb 100644 --- a/source/kernel/drivers/acpi/rsdp.cpp +++ b/source/kernel/drivers/acpi/rsdp.cpp @@ -18,17 +18,16 @@ void printRSD(RSDPTR* rsd){ } RSDPTR* FindRSD(){ - char* memory_byte = (char*) 0x000f2e14; + char* memory_byte = (char*) 0xC00f2e14; const void* string = "RSD PTR "; - for( ; (uint32_t) memory_byte < 0x0100000; memory_byte+=10){ + for( ; (uint32_t) memory_byte < 0xC0100000; memory_byte+=10){ if( memcmp(memory_byte , string , 8 ) == 0 ) { printf("RSD PTR found at 0x%x !\n", memory_byte); break; } } - printRSD((RSDPTR*) memory_byte); return (RSDPTR*) memory_byte; } diff --git a/source/kernel/filesystem/FAT/FAT16.cpp b/source/kernel/filesystem/FAT/FAT16.cpp deleted file mode 100644 index e69de29..0000000 diff --git a/source/kernel/filesystem/FAT/FAT16.h b/source/kernel/filesystem/FAT/FAT16.h deleted file mode 100644 index bc24274..0000000 --- a/source/kernel/filesystem/FAT/FAT16.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once -#include "../../vfs/File.h" - - -class FAT16 : File { -public: - -}; \ No newline at end of file diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 3b10a2b..f0f9bc9 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -14,11 +14,11 @@ extern "C"{ #include "drivers/pci/pci.h" #include "drivers/pit/pit.h" #include "drivers/acpi/acpi.h" -#include "drivers/ide/ide.h" #include "i386/processor.h" #include "terminal/kterm.h" #include "interrupts/idt.h" #include "serial.h" +#include "vfs/VFS.h" extern "C" void LoadGlobalDescriptorTable(); extern "C" void jump_usermode(); @@ -54,17 +54,13 @@ extern "C" void kernel () // Enable interrupts asm volatile("STI"); + initHeap(); - pit_initialise(); - - // ACPI::initialize(); + // ACPI::initialize(); // FIXME: improper reading of bios memory PCI::Scan(); - - //TestIDEController(); - - processor::initialize(); + FileSystem::initialize(); printf("Enable Protected mode and jump to kernel main\n"); diff --git a/source/kernel/supervisorterminal/superVisorTerminal.cpp b/source/kernel/supervisorterminal/superVisorTerminal.cpp index ea2cc32..f2790e8 100644 --- a/source/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/source/kernel/supervisorterminal/superVisorTerminal.cpp @@ -70,160 +70,14 @@ extern "C" void startSuperVisorTerminal() kterm_init(); printf("|=== BarinkOS ===|\n"); } - if(strncmp("FAT", command, characterCount) == 0) + if(strncmp("LIST", command, characterCount) == 0) { - - int devNumber = 0 ; - for ( auto device : ide_devices){ - if (!device.Reserved) - continue; - printf("Device %d\n" , devNumber); - printf (" Device on Channel: (0x%x) %s\n" ,device.Channel, device.Channel == 0 ? "Primary" : "Secondary"); - printf (" Device drive:(0x%x) %s\n" , device.Drive, device.Drive? "Slave" : "Master"); - printf (" Device Type:(0x%x) %s\n" , device.Type, device.Type ? "ATAPI" : "ATA"); - devNumber ++; - - } - - enum BUS_PORT { - Primary= 0x1f0, - Secondary = 0x170 - }; - - - // FIXME: If no drive is connected we continue trying to read from - // a not connected drive! - ATA_DEVICE::Identify((uint16_t) BUS_PORT::Primary, DEVICE_DRIVE::MASTER); - - const int C = 0; - const int H = 0; - const int HPC = 16; - const int SPT = 63; - - int S = 1; - uint32_t LBA = (C*HPC+H) * SPT + (S-1); - printf("LBA: %d\n" , LBA); - uint16_t buffer [256]; - - - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, buffer); - - MBR* mbr = (MBR*) buffer; - - printf("BootSector: 0x%x\n", mbr->ValidBootsector ); - for( int i = 0 ; i < 4 ; i ++){ - PartitionTableEntry PT = mbr->TableEntries[i]; - - printf("Partition %d [ %d sectors, PartitionType: %x, 0x%x, \nLBA Start: 0x%x ]\n" , - i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); - } - - // Find the BiosParameter block - uint16_t biosparameterblock[256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, biosparameterblock); - - auto* bpb = (BiosParameterBlock*) biosparameterblock; - - - printf("\nBPB: Bytes per Sector %d\n", bpb->BytesPerSector ); - printf("OEM ID: %s\n", bpb->OEM_id); - printf("Bytes per sector: %d\n", bpb->BytesPerSector); - printf("Sectors per cluster: %d\n", bpb->SectorsPerCluster); - printf("Reserved sectors: %d\n", bpb->ReservedSectors); - printf("Number of FAT: %d\n", bpb->NumberOfFileAllocationTables); - printf("Number of Dir entries: %d\n", bpb->NumberOfDirectoryEntries); - printf("Total Sectors in volume: %d\n", bpb->TotalSectorsInLogicalVolume); - printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); - - /** - * @brief File Allocation Table - */ - - - uint32_t FATAddress = mbr->TableEntries[0].LBA_partition_start + bpb->ReservedSectors ; - uint16_t FAT[256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); - - // Show data in terminal - for(unsigned short i : FAT) { - printf("%x ", i); - } - kterm_put('\n'); - - - uint32_t RootDirectoryRegion = FATAddress + ( bpb->NumberOfFileAllocationTables * bpb->NumberOfSectorsPerFAT ); - uint32_t DataRegion = RootDirectoryRegion + ((bpb->NumberOfDirectoryEntries * 32) / bpb->BytesPerSector ); - - uint16_t data2 [256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, RootDirectoryRegion, data2 ); - auto* RootDirectory = (DirectoryEntry*) data2; - // List files in root - for(int i= 0; i < bpb->NumberOfDirectoryEntries ; i++ ) - { - auto* entry = (DirectoryEntry*)((uint32_t) RootDirectory + (i * sizeof(DirectoryEntry))); - - if( entry->filename[0] == (uint8_t) 0x00 ) - break; // There are no more entries in this directory or the entry is free - - if( (entry->attribute & 0x01) == 0x01 || (entry->attribute & 0x20) == 0x20) - continue; // Skip listing if hidden or Achieve flag is set - - // Print the filename; - for(char n : entry->filename){ - if(n == 0x20) - break; - kterm_put(n); - } - kterm_put('\n'); - - for(unsigned char n : entry->Extension){ - kterm_put(n); - } - kterm_put('\n'); - - printf("Attribute: %x \n" , entry->attribute); - printf("FileSize: %d Bytes\n", entry->FilesizeInBytes); - - if( entry->FilesizeInBytes != 0x0 || (entry->attribute & 0x8) == 0x0){ - printf("Show contents"); - - printf( "Start cluster of the file: 0x%x\n" , entry->StartingCluster); - - printf("IS it only 1 cluster? %s\n" , FAT[i] == 0xFFFF? "Yes": "No" ); - - uint32_t sector = DataRegion + ((entry->StartingCluster - 0x02 ) * bpb->SectorsPerCluster); - - - uint16_t dataBlob [256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob ); - for(unsigned short n : dataBlob) - { - kterm_put(n & 0x00ff); - - kterm_put(n >> 8); - }kterm_put('\n'); - - - } - - printf("======================\n"); - - - } - continue; + printf("=============== DIRECTORY LISTING =================\n"); } - - if(strncmp("DEVICES", command, characterCount) == 0){ printf("================ CONNECTED DEVICES ===============\n"); - - - - - - } diff --git a/source/kernel/vfs/File.h b/source/kernel/vfs/File.h deleted file mode 100644 index 5a76c48..0000000 --- a/source/kernel/vfs/File.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -class File { - -public: - virtual const File* Open () const ; // TODO: figure out a proper return value - virtual const char* Read() const; - virtual void Write(); -}; diff --git a/source/kernel/vfs/VFS.cpp b/source/kernel/vfs/VFS.cpp index 8eca77a..1c5cc17 100644 --- a/source/kernel/vfs/VFS.cpp +++ b/source/kernel/vfs/VFS.cpp @@ -1,50 +1,354 @@ #include "VFS.h" +#include "../filesystem/FAT/BiosParameterBlock.h" +#include "../drivers/ide/ide.h" +#include "../drivers/ata/ataDevice.h" +#include "../partitiontable/mbr/MasterBootRecord.h" +#include "../memory/KernelHeap.h" +#include "../../lib/include/string.h" +#include "../filesystem/FAT/DirectoryEntry.h" + +MOUNT_INFO mountInfo; + +PFILESYSTEM _filesystems[DEVICE_MAX]; + +FILE volOpenFile(const char* fname) +{ + if(fname){ + unsigned char device = 'a'; + + char* filename = (char*) fname; + + if(fname[1]== ':'){ + device = fname[0]; + filename += 2; // strip the volume component from the path + } + + if(_filesystems[device - 'a']){ + FILE file = _filesystems[device-'a']->Open(filename); + file.device = device; + return file; + } + } + + FILE file; + file.flags = FS_INVALID; + return file; +} + +extern void volReadFile(PFILE file, unsigned char* Buffer, unsigned int length) +{ + +} +extern void volCloseFile(PFILE file) +{ + if( file->device < DEVICE_MAX){ + // _filesystems[file->device]->Close(file); + } +} + +extern void volRegisterFilesystem(PFILESYSTEM fsys , unsigned int deviceID){ + if(deviceID < DEVICE_MAX) + if(fsys) + _filesystems[deviceID] = fsys; +} + +extern void volUnregisterFilesystem(PFILESYSTEM){ + +} + +extern void volUnregisterFileSystemByID(unsigned int deviceID){ + +} + +enum BUS_PORT { + Primary = 0x1f0, + Secondary = 0x170 +}; + +bool driveAvailable(){ + int devNumber = 0; + for ( auto device : ide_devices){ + if(!device.Reserved) + continue; + devNumber++; + } + + + // FIXME: If no drive is connected we continue trying to read from + // a not connected drive! + ATA_DEVICE::Identify((uint16_t) BUS_PORT::Primary, DEVICE_DRIVE::MASTER); + return true; +} + +MBR* getPartitions(){ + const int C = 0; + const int H = 0; + const int HPC = 16; + const int SPT = 63; + + int S =1; + uint32_t LBA = (C*HPC+H) * SPT + (S-1); + MBR* mbr =(MBR*) malloc(sizeof (MBR)); + + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, (uint16_t*)mbr); + + printf("BootSector: 0x%x\n", mbr->ValidBootsector ); + for( int i = 0 ; i < 4 ; i ++){ + PartitionTableEntry PT = mbr->TableEntries[i]; + + printf("Partition %d [ %d sectors, PartitionType: %x, 0x%x, \nLBA Start: 0x%x ]\n" , + i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); + } + + return mbr; +} + +BiosParameterBlock* getBPB(MBR* mbr){ + BiosParameterBlock* bpb = (BiosParameterBlock*) malloc(sizeof(BiosParameterBlock)); + + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, (uint16_t*) bpb); + + printf("OEM ID: %s\n", bpb->OEM_id); + printf("Bytes per sector: %d\n", bpb->BytesPerSector); + printf("Sectors per cluster: %d\n", bpb->SectorsPerCluster); + printf("Reserved sectors: %d\n", bpb->ReservedSectors); + printf("Number of FAT: %d\n", bpb->NumberOfFileAllocationTables); + printf("Number of Dir entries: %d\n", bpb->NumberOfDirectoryEntries); + printf("Total Sectors in volume: %d\n", bpb->TotalSectorsInLogicalVolume); + printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); + + + return bpb; +} + +uint16_t* ReadFAT (BiosParameterBlock& bpb , MBR& mbr) { + uint32_t FATAddress = mbr.TableEntries[0].LBA_partition_start + bpb.ReservedSectors ; + uint16_t* FAT = (uint16_t*)malloc(sizeof (uint16_t) * 256); + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); + + // Show data in terminal + /* + for(unsigned short i : FAT) { + printf("%x ", i); + } + kterm_put('\n');*/ + + return FAT; + +} + +void listFilesInRoot(MBR& mbr, BiosParameterBlock& bpb ){ + auto FATAddress = mbr.TableEntries[0].LBA_partition_start + bpb.ReservedSectors; + uint32_t RootDirectoryRegion = FATAddress + ( bpb.NumberOfFileAllocationTables * bpb.NumberOfSectorsPerFAT ); + uint32_t DataRegion = RootDirectoryRegion + ((bpb.NumberOfDirectoryEntries * 32) / bpb.BytesPerSector ); + uint16_t* FAT = ReadFAT(bpb, mbr); + + + uint16_t data2 [256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, RootDirectoryRegion, data2 ); + auto* RootDirectory = (DirectoryEntry*) data2; + // List files in root + for(int i= 0; i < bpb.NumberOfDirectoryEntries ; i++ ) { + auto *entry = (DirectoryEntry * )((uint32_t) RootDirectory + (i * sizeof(DirectoryEntry))); + + if (entry->filename[0] == (uint8_t) 0x00) + break; // There are no more entries in this directory or the entry is free + + if ((entry->attribute & 0x01) == 0x01 || (entry->attribute & 0x20) == 0x20) + continue; // Skip listing if hidden or Achieve flag is set + + // Print the filename; + for (char n: entry->filename) { + if (n == 0x20) + break; + kterm_put(n); + } + kterm_put('\n'); + + for (unsigned char n: entry->Extension) { + kterm_put(n); + } + kterm_put('\n'); + + printf("Attribute: %x \n", entry->attribute); + printf("FileSize: %d Bytes\n", entry->FilesizeInBytes); + + if (entry->FilesizeInBytes != 0x0 || (entry->attribute & 0x8) == 0x0) { + printf("Show contents"); + + printf("Start cluster of the file: 0x%x\n", entry->StartingCluster); + + printf("IS it only 1 cluster? %s\n", FAT[i] == 0xFFFF ? "Yes" : "No"); + + uint32_t sector = DataRegion + ((entry->StartingCluster - 0x02) * bpb.SectorsPerCluster); + + + uint16_t dataBlob[256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob); + for (unsigned short n: dataBlob) { + kterm_put(n & 0x00ff); + + kterm_put(n >> 8); + } + kterm_put('\n'); + + + } + printf("======================\n"); + + } + +} + + /* - * TODO: Implement this!! - * +FILE fsysFatDirectory (const char* DirectoryName){ + FILE file; + unsigned char* buf; + PDIRECTORY directory; + + char DosFileName[11]; + ToDosFileName(DirectoryName, DosFileName, 11); + DosFileName[11] =0; + + for (int sector=0; sector <14 ; sector++){ + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mountInfo.rootOffset + sector, (uint16_t*)buf); + directory = (PDIRECTORY) buf; + + for (int i =0; i < 16; i++){ + char name[11]; + memcpy(name, directory->Filename, 11); + name[11]=0; + + if(strncmp(DosFileName, name, 11) == 0){ + strcpy(file.name, DirectoryName); + file.id = 0; + file.currentCluster = directory->FirstCluster; + file.eof = 0; + file.filelength = directory->FileSize; + + if(directory->Attrib == 0x10){ + file.flags = FS_DIRECTORY; + } else { + file.flags = FS_FILE; + } + return file; + } + directory++; + } + } + + // Can't find file + file.flags = FS_INVALID; + return file; + +} */ +void fsysFATRead(PFILE file, unsigned char* buffer, unsigned int length){ + if(file){ + unsigned int physSector = 32 + (file->currentCluster - 1); + const unsigned int SECTOR_SIZE = 512; + // read sector + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, physSector, (uint16_t*) buffer ); + + unsigned int FAT_Offset = file->currentCluster + (file->currentCluster /2); + unsigned int FAT_Sector = 1 + (FAT_Offset / SECTOR_SIZE); + unsigned int entryOffset =FAT_Offset % SECTOR_SIZE; + + uint8_t FAT[SECTOR_SIZE*2]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FAT_Sector,(uint16_t*) FAT); // Read 1st FAT sector + + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FAT_Sector +1, (uint16_t*)FAT+SECTOR_SIZE); + + // read entry for next cluster + uint16_t nextCluster = *(uint16_t*) &FAT[entryOffset]; + + // test if entry is odd or even + if(file->currentCluster & 0x0001){ + nextCluster>>= 4; // grab the high 12 bits + }else{ + nextCluster &= 0x0FFF; // grab the low 12 bits + } + + // test for end of file + if(nextCluster >= 0xff8){ + file->eof -1; + return; + } + + // test for file corruption + if(nextCluster == 0){ + file->eof =1; + return; + } + + // set next cluster + file->currentCluster = nextCluster; -void VirtualFileSystem::Initialize(FS* root) -{ - root = root; + } } +/* +FILE fsysFatOpenSubDir(FILE kFile, const char* filename){ + FILE file; -void VirtualFileSystem::Open(const char* path) -{ - /* - What does this mean? - 1. Parse the path string - 2. Traverse the graph (Finding the correct Node) - 3. Create some kind of open file pointer thingy - */ + char DosFileName[11]; + ToDosFileName(filename, DosFileName, 11); + DosFileName[11] = 0; + + while(!kFile.eof){ + //read directory + unsigned char buf[512]; + fsysFATRead(&file, buf, 512); + + PDIRECTORY pkDir = (PDIRECTORY) buf; + + for (unsigned int i = 0; i < 16; i++){ + // get current filename + char name[11]; + memcpy(name, pkDir->Filename, 11); + name[11] = 0; + + if(strncmp(name, DosFileName, 11) == 0){ + strcpy(file.name, filename); + file.id = 0; + file.currentCluster = pkDir->FirstCluster; + file.filelength = pkDir->FileSize; + file.eof = 0; + + // set file type; + if(pkDir->Attrib == 0x10){ + file.flags = FS_DIRECTORY; + } else{ + file.flags = FS_FILE; + } + + return file; + } + // go to next entry + pkDir++; + } + } + // unable to find file + file.flags = FS_INVALID; + return file; } +*/ -void VirtualFileSystem::Read() +void FileSystem::initialize() { - // NOTE: we need some way to know what file we wish to read from -} + MBR* mbr = getPartitions(); + BiosParameterBlock* bootsector = getBPB(mbr); + listFilesInRoot(*mbr, *bootsector); +/* + mountInfo.numSectors = bootsector->NumberOfSectorsPerFAT; + mountInfo.fatOffset = 1; + mountInfo.fatSize = bootsector->NumberOfSectorsPerFAT; + mountInfo.fatEntrySize = 8; + mountInfo.numRootEntries = bootsector->NumberOfDirectoryEntries; + mountInfo.rootOffset = (bootsector->NumberOfFileAllocationTables * bootsector->NumberOfSectorsPerFAT) + 1; + mountInfo.rootSize = (bootsector->NumberOfDirectoryEntries * 32) / bootsector->BytesPerSector;*/ -void VirtualFileSystem::Write() -{ - // NOTE: we need some way to know what file we wish to write to -} -void VirtualFileSystem::Mount(const char* path, FS* FileSystem) -{ - /* - What does this mean? - 1. Parse the path string - 2. Add a node to our internal graph - */ -} - -void VirtualFileSystem::UnMount(FS* FileSystem) -{ - /* - What does this mean? - 1. Parse the path string - 2. Remve a node to our internal graph - */ } \ No newline at end of file diff --git a/source/kernel/vfs/VFS.h b/source/kernel/vfs/VFS.h index b525cc2..f7ec66d 100644 --- a/source/kernel/vfs/VFS.h +++ b/source/kernel/vfs/VFS.h @@ -1,29 +1,76 @@ #pragma once +#include +#define FS_FILE 0 +#define FS_DIRECTORY 1 +#define FS_INVALID 2 +#define DEVICE_MAX 26 -class VirtualFileSystem{ -public: - void Initialize( FS* root); - void Open (const char* path); - void Read(); - void Write(); +typedef struct _FILE { + char name [32]; + uint32_t flags; + uint32_t filelength; + uint32_t id; + uint32_t eof; + uint32_t position; + uint32_t currentCluster; + uint32_t device; +}FILE, *PFILE; - void Mount(const char* path,FS* FileSystem); - void UnMount(FS* FileSystem); +typedef struct _FILE_SYSTEM{ + char name[8]; + FILE (*Directory) (const char* Directoryname); + void (*Mount) (); + void (*Read) (PFILE file, unsigned char* buffer, unsigned int length); + void (Close) (PFILE); + FILE (*Open) (const char* filename); +}FILESYSTEM, *PFILESYSTEM; -private: - FS* root; +typedef struct _MOUNT_INFO{ + uint32_t numSectors; + uint32_t fatOffset; + uint32_t numRootEntries; + uint32_t rootOffset; + uint32_t rootSize; + uint32_t fatSize; + uint32_t fatEntrySize; +}MOUNT_INFO, *PMOUNT_INFO; + +typedef struct _DIRECTORY{ + uint8_t Filename[8]; + uint8_t Ext[3]; + uint8_t Attrib; + uint8_t Reserved; + uint8_t TimeCreatedMs; + uint16_t TimeCreated; + uint16_t DateCreated; + uint16_t DateLastAccessed; + uint16_t FirstClusterHiBytes; + uint16_t LastModTime; + uint16_t LastModDate; + uint16_t FirstCluster; + uint32_t FileSize; +}DIRECTORY, *PDIRECTORY; +// Date Format +// [0..4] Day +// [5..8] Month +// [9..15] Year + +// Time Format +// [0..4] Seconds +// [5..10] Minute +// [11..15] Hour +extern PFILESYSTEM _filesystems[DEVICE_MAX]; + + FILE volOpenFile(const char* fname); + + void volCloseFile(PFILE file); + void volRegisterFilesystem(PFILESYSTEM, unsigned int deviceID); + void volUnregisterFilesystem(PFILESYSTEM); + void volUnregisterFileSystemByID(unsigned int deviceID); -}; - -struct FS -{ - const char* name ; - int DeviceID; - int ManufacturerID; - FS* next; - char**(Read)(); - void*(Write)(); - void*(Open)(); -}; + class FileSystem{ + public: + static void initialize(); + }; \ No newline at end of file -- 2.39.5 From 37542b736fb9c8dd7c7bec3789c5866b10a4618f Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 17 Feb 2023 22:01:32 +0100 Subject: [PATCH 093/115] Remove cpu.h and cpu.cpp in favor of i386/processor.[h|cpp] Moving enable protected Mode to processor class --- Makefile | 4 +- source/kernel/cpu.cpp | 39 --------------- source/kernel/cpu.h | 16 ------ source/kernel/i386/processor.cpp | 54 +++++++++++++++++++++ source/kernel/i386/processor.h | 7 +++ source/kernel/interrupts/idt.cpp | 4 +- source/kernel/kernel.cpp | 21 +------- source/kernel/memory/VirtualMemoryManager.h | 2 +- 8 files changed, 67 insertions(+), 80 deletions(-) delete mode 100644 source/kernel/cpu.cpp delete mode 100644 source/kernel/cpu.h diff --git a/Makefile b/Makefile index ae3954c..84b3479 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/VFS.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/cpu.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/VFS.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o SRC_DIR = source BUILD_DIR = build @@ -133,8 +133,6 @@ $(BUILD_DIR)/KHeap.o: $(BUILD_DIR)/prekernel.o: $(CPP) -c $(SRC_DIR)/kernel/prekernel/prekernel.cpp -o $(BUILD_DIR)/prekernel.o $(CFLAGS) -fno-exceptions -fno-rtti -$(BUILD_DIR)/cpu.o: - $(CPP) -c $(SRC_DIR)/kernel/cpu.cpp -o $(BUILD_DIR)/cpu.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/processor.o: $(CPP) -c $(SRC_DIR)/kernel/i386/processor.cpp -o $(BUILD_DIR)/processor.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/source/kernel/cpu.cpp b/source/kernel/cpu.cpp deleted file mode 100644 index 897e92d..0000000 --- a/source/kernel/cpu.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "cpu.h" - - -uint32_t GetEFLAGS() -{ - uint32_t EFLAGS = 0; - asm volatile ("pushfl;" "movl 4(%%esp), %%edx" : "=d"(EFLAGS)); - return EFLAGS; -} - - -uint32_t GetCR0() -{ - uint32_t cr0_value; - asm volatile ("movl %%cr0, %%edx" : "=d"(cr0_value)); - return cr0_value; - -} - - -uint32_t GetCR2(){ - uint32_t cr2_value; - __asm__ volatile("movl %%cr2, %%edx": "=d"(cr2_value)); - return cr2_value; -} - - -uint32_t GetCR3(){ - uint32_t cr3_value; - __asm__ volatile("movl %%cr3, %%edx": "=d"(cr3_value)); - return cr3_value; -} - - -uint32_t GetCR4(){ - uint32_t cr4_value; - __asm__ volatile("movl %%cr4, %%edx": "=d"(cr4_value)); - return cr4_value; -} \ No newline at end of file diff --git a/source/kernel/cpu.h b/source/kernel/cpu.h deleted file mode 100644 index bde0024..0000000 --- a/source/kernel/cpu.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once -#include - -uint32_t GetEFLAGS(); - - -uint32_t GetCR0(); - - -uint32_t GetCR2(); - - -uint32_t GetCR3(); - - -uint32_t GetCR4(); \ No newline at end of file diff --git a/source/kernel/i386/processor.cpp b/source/kernel/i386/processor.cpp index cc58fef..d04bcdb 100644 --- a/source/kernel/i386/processor.cpp +++ b/source/kernel/i386/processor.cpp @@ -70,4 +70,58 @@ bool processor::hasPageSupport(){ */ bool processor::gigabytePages() { return cap_page & (0x1 << 26); +} + +void processor::enable_protectedMode() +{ + // Set the protected bit of control register 0 + // this will put the CPU into protected mode + // NOTE: This should really be an assembly procedure + // We cant directly write to control register 0 + // therefor we copy the value of control register 0 into eax + // once we are done manipulating the value we write the value in + // eax back to control register 0 + + asm volatile("mov %cr0, %eax "); + asm volatile("or $1, %eax"); + asm volatile("mov %eax, %cr0"); +} + + + +uint32_t processor::GetEFLAGS() +{ + uint32_t EFLAGS = 0; + asm volatile ("pushfl;" "movl 4(%%esp), %%edx" : "=d"(EFLAGS)); + return EFLAGS; +} + + +uint32_t processor::GetCR0() +{ + uint32_t cr0_value; + asm volatile ("movl %%cr0, %%edx" : "=d"(cr0_value)); + return cr0_value; + +} + + +uint32_t processor::GetCR2(){ + uint32_t cr2_value; + __asm__ volatile("movl %%cr2, %%edx": "=d"(cr2_value)); + return cr2_value; +} + + +uint32_t processor::GetCR3(){ + uint32_t cr3_value; + __asm__ volatile("movl %%cr3, %%edx": "=d"(cr3_value)); + return cr3_value; +} + + +uint32_t processor::GetCR4(){ + uint32_t cr4_value; + __asm__ volatile("movl %%cr4, %%edx": "=d"(cr4_value)); + return cr4_value; } \ No newline at end of file diff --git a/source/kernel/i386/processor.h b/source/kernel/i386/processor.h index b2d6286..7ff38fe 100644 --- a/source/kernel/i386/processor.h +++ b/source/kernel/i386/processor.h @@ -19,6 +19,13 @@ public: static bool gigabytePages(); static bool hasPAEExtension(); + static void enable_protectedMode(); + + static uint32_t GetEFLAGS(); + static uint32_t GetCR0(); + static uint32_t GetCR2(); + static uint32_t GetCR3(); + static uint32_t GetCR4(); private: static uint32_t cap_page; diff --git a/source/kernel/interrupts/idt.cpp b/source/kernel/interrupts/idt.cpp index 7d99ca3..7448de0 100644 --- a/source/kernel/interrupts/idt.cpp +++ b/source/kernel/interrupts/idt.cpp @@ -1,7 +1,7 @@ #include "idt.h" #include "../drivers/pit/pit.h" #include "../drivers/ps-2/keyboard.h" -#include "../cpu.h" +#include "../i386/processor.h" #include "../memory/VirtualMemoryManager.h" IDT_entry idt_table[256]; IDT_ptr idt_ptr; @@ -165,7 +165,7 @@ void irs_handler (registers* regs) { // Page Fault Exception #PF printf("#PF\n"); #define ALIGN(addr, align) (((addr) & ~((align) - 1)) + (align)) - FaultingAddress = GetCR2(); + FaultingAddress = processor::GetCR2(); printf("Accessing the linear address 0x%x resulted in a page fault!\n\n", FaultingAddress); diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index f0f9bc9..319b5a9 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -23,22 +23,6 @@ extern "C"{ extern "C" void LoadGlobalDescriptorTable(); extern "C" void jump_usermode(); - -void set_protected_bit() -{ - // Set the protected bit of control register 0 - // this will put the CPU into protected mode - // NOTE: This should really be a assembly procedure - // We cant directly write to control register 0 - // therefor we copy the value of control register 0 into eax - // once we are done manipulating the value we write the value in - // eax back to control register 0 - - asm volatile("mov %cr0, %eax "); - asm volatile("or $1, %eax"); - asm volatile("mov %eax, %cr0"); -} - extern "C" void kernel () { @@ -60,11 +44,10 @@ extern "C" void kernel () // ACPI::initialize(); // FIXME: improper reading of bios memory PCI::Scan(); processor::initialize(); + processor::enable_protectedMode(); + FileSystem::initialize(); - printf("Enable Protected mode and jump to kernel main\n"); - - set_protected_bit(); #ifdef USERMODE_RELEASE // Lets jump into user mode diff --git a/source/kernel/memory/VirtualMemoryManager.h b/source/kernel/memory/VirtualMemoryManager.h index f4da57a..1298c2b 100644 --- a/source/kernel/memory/VirtualMemoryManager.h +++ b/source/kernel/memory/VirtualMemoryManager.h @@ -1,6 +1,6 @@ #pragma once #include "../terminal/kterm.h" -#include "../cpu.h" +#include "../i386/processor.h" #include "PhysicalMemoryManager.h" -- 2.39.5 From dbb147e110f7157126c061cdd446cdea0df3b4a4 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 19 Feb 2023 14:17:47 +0100 Subject: [PATCH 094/115] Primitie listing rootdir of FAT16 filesystem --- features.md | 17 ++- source/kernel/drivers/ata/ataDevice.cpp | 4 +- source/kernel/drivers/ata/ataDevice.h | 4 - source/kernel/interrupts/idt.cpp | 4 +- source/kernel/memory/KernelHeap.cpp | 10 +- .../supervisorterminal/superVisorTerminal.cpp | 10 +- source/kernel/vfs/VFS.cpp | 107 ++++++++++-------- todo.md | 4 +- 8 files changed, 86 insertions(+), 74 deletions(-) diff --git a/features.md b/features.md index 577e666..a6d8e97 100644 --- a/features.md +++ b/features.md @@ -1,14 +1,17 @@ # TODO list ## Basics - Setup Cross-Compiler \ - Multiboot to kernel \ - Printing string to the screen \ + + Setup Cross-Compiler + Multiboot to kernel \ + Printing string to the screen \ Printing values/numbers to the screen \ Basic Terminal \ Extend Multiboot implementation \ Output to serial port \ Move to protected mode \ - Enabel CMOS clock \ + Enable CMOS clock \ Time measurement (PIC &| PIT) \ Detect CPU speed \ Interrupt / exception system (API) \ @@ -22,16 +25,13 @@ Virtual memory management \ The heap: allocating memory at runtime (malloc and free) is almost impossible to go without. \ Enable SIMD Extensions (SSE) - -## Other features I am thinking of: PCI support \ - ATA PIO Mode support \ + ATA PIO Mode support \ USTAR Filesystem ( For its simplicity this is very likely the first filesystem the OS is going to support) \ ACPI support ( Or some other basic way to support shutdown, reboot and possibly hibernation ) \ ATAPI support \ Memory Management (MMU) Hardware Management system - Preemptive multi tasking \ Processes \ Threads @@ -44,7 +44,6 @@ ACPI support \ ATAPI support \ -## Optional Basic Window server/client \ EXT2 Filesystem USTAR Filesystem \ diff --git a/source/kernel/drivers/ata/ataDevice.cpp b/source/kernel/drivers/ata/ataDevice.cpp index 05947f1..873aa0e 100644 --- a/source/kernel/drivers/ata/ataDevice.cpp +++ b/source/kernel/drivers/ata/ataDevice.cpp @@ -128,7 +128,7 @@ void ATA_DEVICE::Read(uint16_t DEVICE_CHANNEL, DEVICE_DRIVE drive, uint32_t LBA return ; } - printf("Read LBA: 0x%x\n", LBA); + //printf("Read LBA: 0x%x\n", LBA); // Send 0xE0 for the "master" or 0xF0 for the "slave", ORed with the highest 4 bits of the LBA to port 0x1F6: outb(0x1F6, 0xE0 | (slavebit << 4) | ((LBA >> 24) & 0x0F)) outb(DEVICE_CHANNEL | 6 , ( 0xE0 | (LBA >>28) ) ); // Send a NULL byte to port 0x1F1, if you like (it is ignored and wastes lots of CPU time): outb(0x1F1, 0x00) @@ -156,7 +156,7 @@ void ATA_DEVICE::Read(uint16_t DEVICE_CHANNEL, DEVICE_DRIVE drive, uint32_t LBA return; } - printf("Status: %x\n", status); + //printf("Status: %x\n", status); // Check if busy! while((status & 0x80) == 0x80){ printf("Reading....\r"); diff --git a/source/kernel/drivers/ata/ataDevice.h b/source/kernel/drivers/ata/ataDevice.h index 730de3c..30e75dc 100644 --- a/source/kernel/drivers/ata/ataDevice.h +++ b/source/kernel/drivers/ata/ataDevice.h @@ -10,7 +10,6 @@ * This first driver wil make use of IO ports. * Doing so means reading or writing from disk is going * to be very cpu intensive. -* */ enum DEVICE_DRIVE{ @@ -18,9 +17,6 @@ enum DEVICE_DRIVE{ SLAVE = 0xB0 }; - - - namespace ATA_DEVICE{ void Identify(uint16_t, DEVICE_DRIVE); void Read (uint16_t, DEVICE_DRIVE, uint32_t, uint16_t*); diff --git a/source/kernel/interrupts/idt.cpp b/source/kernel/interrupts/idt.cpp index 7448de0..50acd47 100644 --- a/source/kernel/interrupts/idt.cpp +++ b/source/kernel/interrupts/idt.cpp @@ -308,8 +308,8 @@ void irq_handler (registers regs) { break; default: - printf("Interrupt happened!"); - printf("Received INT: 0x%x\n", regs.int_no); + //printf("Interrupt happened!"); + //printf("Received INT: 0x%x\n", regs.int_no); break; } diff --git a/source/kernel/memory/KernelHeap.cpp b/source/kernel/memory/KernelHeap.cpp index 4483d2d..c935fb1 100644 --- a/source/kernel/memory/KernelHeap.cpp +++ b/source/kernel/memory/KernelHeap.cpp @@ -1,7 +1,7 @@ #include "KernelHeap.h" #include "VirtualMemoryManager.h" extern "C" const uint32_t kernel_end; -// Size of heap meta data is 5 bytes +// Size of heap metadata is 5 bytes struct heap_block{ uint8_t Used; uint32_t Size; @@ -12,7 +12,7 @@ heap_block* start ; void* malloc(size_t size) { - printf("Received request for %d bytes of memory\n", size); + //printf("Received request for %d bytes of memory\n", size); heap_block* current = start; // look for a free block @@ -21,14 +21,14 @@ void* malloc(size_t size) if(current->Size >= size && current->Used == false ) { // We found a spot - printf("Block found!\n"); + // printf("Block found!\n"); // Set the spot to in-use current->Used = true; // split the block - printf("Split block.\n"); + //printf("Split block.\n"); uint32_t oldSize = current->Size; current->Size = size; @@ -57,7 +57,7 @@ void free(void* addr) { // clear the free boolean that corresponds to this adddress // This should be fairly simple - heap_block* allocatedBlock = (heap_block*)(addr - sizeof(heap_block)); + heap_block* allocatedBlock = (heap_block*)((uint32_t)addr - sizeof(heap_block)); allocatedBlock->Used = false; } diff --git a/source/kernel/supervisorterminal/superVisorTerminal.cpp b/source/kernel/supervisorterminal/superVisorTerminal.cpp index f2790e8..d574b65 100644 --- a/source/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/source/kernel/supervisorterminal/superVisorTerminal.cpp @@ -70,9 +70,17 @@ extern "C" void startSuperVisorTerminal() kterm_init(); printf("|=== BarinkOS ===|\n"); } - if(strncmp("LIST", command, characterCount) == 0) + if(strncmp("LIST", command, 4) == 0) { + + // slice off the command part + char args[characterCount - 4]; + for(int i = 5 ; i < characterCount; i++) { + args[i] = command[i]; + } + printf("=============== DIRECTORY LISTING =================\n"); + printf("Path to show %s\n", args); } if(strncmp("DEVICES", command, characterCount) == 0){ diff --git a/source/kernel/vfs/VFS.cpp b/source/kernel/vfs/VFS.cpp index 1c5cc17..cdb787c 100644 --- a/source/kernel/vfs/VFS.cpp +++ b/source/kernel/vfs/VFS.cpp @@ -80,7 +80,7 @@ bool driveAvailable(){ return true; } -MBR* getPartitions(){ +MBR* getPartitions(bool DEBUG = false){ const int C = 0; const int H = 0; const int HPC = 16; @@ -92,67 +92,91 @@ MBR* getPartitions(){ ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, (uint16_t*)mbr); - printf("BootSector: 0x%x\n", mbr->ValidBootsector ); - for( int i = 0 ; i < 4 ; i ++){ - PartitionTableEntry PT = mbr->TableEntries[i]; + if(DEBUG){ + printf("BootSector: 0x%x\n", mbr->ValidBootsector ); + for( int i = 0 ; i < 4 ; i ++){ + PartitionTableEntry PT = mbr->TableEntries[i]; + + printf("Partition %d [ %d sectors, PartitionType: 0x%x, 0x%x, \nLBA Start: 0x%x ]\n" , + i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); + } - printf("Partition %d [ %d sectors, PartitionType: %x, 0x%x, \nLBA Start: 0x%x ]\n" , - i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); } return mbr; } -BiosParameterBlock* getBPB(MBR* mbr){ +BiosParameterBlock* getBPB(MBR* mbr, bool DEBUG =false ){ BiosParameterBlock* bpb = (BiosParameterBlock*) malloc(sizeof(BiosParameterBlock)); - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, (uint16_t*) bpb); - printf("OEM ID: %s\n", bpb->OEM_id); - printf("Bytes per sector: %d\n", bpb->BytesPerSector); - printf("Sectors per cluster: %d\n", bpb->SectorsPerCluster); - printf("Reserved sectors: %d\n", bpb->ReservedSectors); - printf("Number of FAT: %d\n", bpb->NumberOfFileAllocationTables); - printf("Number of Dir entries: %d\n", bpb->NumberOfDirectoryEntries); - printf("Total Sectors in volume: %d\n", bpb->TotalSectorsInLogicalVolume); - printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); + if(DEBUG) + { + printf("OEM ID: %s\n", bpb->OEM_id); + printf("Bytes per sector: %d\n", bpb->BytesPerSector); + printf("Sectors per cluster: %d\n", bpb->SectorsPerCluster); + printf("Reserved sectors: %d\n", bpb->ReservedSectors); + printf("Number of FAT: %d\n", bpb->NumberOfFileAllocationTables); + printf("Number of Dir entries: %d\n", bpb->NumberOfDirectoryEntries); + printf("Total Sectors in volume: %d\n", bpb->TotalSectorsInLogicalVolume); + printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); + } + return bpb; } -uint16_t* ReadFAT (BiosParameterBlock& bpb , MBR& mbr) { +uint16_t* ReadFAT (BiosParameterBlock& bpb , MBR& mbr, bool DEBUG = false ) { uint32_t FATAddress = mbr.TableEntries[0].LBA_partition_start + bpb.ReservedSectors ; uint16_t* FAT = (uint16_t*)malloc(sizeof (uint16_t) * 256); ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); // Show data in terminal - /* - for(unsigned short i : FAT) { - printf("%x ", i); + if(DEBUG){ + for( unsigned int i =0 ; i < 256 ; i++) { + printf("0x%x ", (unsigned short)FAT[i]); + } + kterm_put('\n'); } - kterm_put('\n');*/ return FAT; - } +void readFile(uint32_t DataRegion, DirectoryEntry* entry, uint16_t FATentry, BiosParameterBlock& bpb ){ + printf("Show contents"); + printf("Start cluster of the file: 0x%x\n", entry->StartingCluster); + + printf("IS it only 1 cluster? %s\n", FATentry == 0xFFFF ? "Yes" : "No"); + + uint32_t sector = DataRegion + ((entry->StartingCluster - 0x02) * bpb.SectorsPerCluster); + + + uint16_t dataBlob[256]; + ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob); + for (unsigned short n: dataBlob) { + kterm_put(n & 0x00ff); + + kterm_put(n >> 8); + } + kterm_put('\n'); +} void listFilesInRoot(MBR& mbr, BiosParameterBlock& bpb ){ auto FATAddress = mbr.TableEntries[0].LBA_partition_start + bpb.ReservedSectors; uint32_t RootDirectoryRegion = FATAddress + ( bpb.NumberOfFileAllocationTables * bpb.NumberOfSectorsPerFAT ); uint32_t DataRegion = RootDirectoryRegion + ((bpb.NumberOfDirectoryEntries * 32) / bpb.BytesPerSector ); uint16_t* FAT = ReadFAT(bpb, mbr); - uint16_t data2 [256]; ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, RootDirectoryRegion, data2 ); auto* RootDirectory = (DirectoryEntry*) data2; + // List files in root - for(int i= 0; i < bpb.NumberOfDirectoryEntries ; i++ ) { + for(int i= 0; i < sizeof (data2) / sizeof (DirectoryEntry); i++ ) { auto *entry = (DirectoryEntry * )((uint32_t) RootDirectory + (i * sizeof(DirectoryEntry))); if (entry->filename[0] == (uint8_t) 0x00) - break; // There are no more entries in this directory or the entry is free + continue; // There are no more entries in this directory or the entry is free if ((entry->attribute & 0x01) == 0x01 || (entry->attribute & 0x20) == 0x20) continue; // Skip listing if hidden or Achieve flag is set @@ -163,40 +187,21 @@ void listFilesInRoot(MBR& mbr, BiosParameterBlock& bpb ){ break; kterm_put(n); } - kterm_put('\n'); - for (unsigned char n: entry->Extension) { kterm_put(n); } kterm_put('\n'); + printf("Attribute: %x \n", entry->attribute); printf("FileSize: %d Bytes\n", entry->FilesizeInBytes); - if (entry->FilesizeInBytes != 0x0 || (entry->attribute & 0x8) == 0x0) { - printf("Show contents"); - - printf("Start cluster of the file: 0x%x\n", entry->StartingCluster); - - printf("IS it only 1 cluster? %s\n", FAT[i] == 0xFFFF ? "Yes" : "No"); - - uint32_t sector = DataRegion + ((entry->StartingCluster - 0x02) * bpb.SectorsPerCluster); - - - uint16_t dataBlob[256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob); - for (unsigned short n: dataBlob) { - kterm_put(n & 0x00ff); - - kterm_put(n >> 8); - } - kterm_put('\n'); - - + if (entry->FilesizeInBytes != 0x0 && (entry->attribute == 0x08)) { + readFile(DataRegion,entry, FAT[i], bpb); } - printf("======================\n"); } + free(FAT); } @@ -341,6 +346,9 @@ void FileSystem::initialize() MBR* mbr = getPartitions(); BiosParameterBlock* bootsector = getBPB(mbr); listFilesInRoot(*mbr, *bootsector); + + free(mbr); + free(bootsector); /* mountInfo.numSectors = bootsector->NumberOfSectorsPerFAT; mountInfo.fatOffset = 1; @@ -348,7 +356,8 @@ void FileSystem::initialize() mountInfo.fatEntrySize = 8; mountInfo.numRootEntries = bootsector->NumberOfDirectoryEntries; mountInfo.rootOffset = (bootsector->NumberOfFileAllocationTables * bootsector->NumberOfSectorsPerFAT) + 1; - mountInfo.rootSize = (bootsector->NumberOfDirectoryEntries * 32) / bootsector->BytesPerSector;*/ + mountInfo.rootSize = (bootsector->NumberOfDirectoryEntries * 32) / bootsector->BytesPerSector; +*/ } \ No newline at end of file diff --git a/todo.md b/todo.md index a47a9f3..cb71d04 100644 --- a/todo.md +++ b/todo.md @@ -13,9 +13,9 @@ to do on a more in depth level. [x] Setup a proper HEAP \ [ ] Setup a proper Stack \ [x] Setup KMalloc and KFree \ -[ ] Merge Functioning Feature branches into sandboxKernelDev \ +[x] Merge Functioning Feature branches into sandboxKernelDev \ [ ] Remove merged feature branches \ [ ] Merge sandboxKernelDev with dev \ -[ ] Remove sandboxKernelDev branch \ +[x] Remove sandboxKernelDev branch \ [ ] Implement proper virtual filesystem -- 2.39.5 From 94a2de3847ec9e7ef0943a1f788eee6c2894517f Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 19 Feb 2023 22:14:58 +0100 Subject: [PATCH 095/115] Started on path resolution algorithm - The algorithm will work once I am of better mind to deal with raw C strings - The resolution should look at each entry divided by '/'. if the entry is not there then we can quit early, however for now I am mostly concerned with getting the names of directory entries we would need to look for. --- Makefile | 5 ++- source/kernel/kernel.cpp | 4 ++ source/kernel/vfs/Path.cpp | 83 ++++++++++++++++++++++++++++++++++++++ source/kernel/vfs/Path.h | 46 +++++++++++++++++++++ source/kernel/vfs/VFS.cpp | 57 +++++++++++++++++++++++++- source/kernel/vfs/VFS.h | 4 ++ source/lib/include/mem.h | 27 +++++++------ 7 files changed, 210 insertions(+), 16 deletions(-) create mode 100644 source/kernel/vfs/Path.cpp create mode 100644 source/kernel/vfs/Path.h diff --git a/Makefile b/Makefile index 84b3479..faad734 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/VFS.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/Path.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/VFS.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o SRC_DIR = source BUILD_DIR = build @@ -133,10 +133,11 @@ $(BUILD_DIR)/KHeap.o: $(BUILD_DIR)/prekernel.o: $(CPP) -c $(SRC_DIR)/kernel/prekernel/prekernel.cpp -o $(BUILD_DIR)/prekernel.o $(CFLAGS) -fno-exceptions -fno-rtti - $(BUILD_DIR)/processor.o: $(CPP) -c $(SRC_DIR)/kernel/i386/processor.cpp -o $(BUILD_DIR)/processor.o $(CFLAGS) -fno-exceptions -fno-rtti +$(BUILD_DIR)/Path.o: + $(CPP) -c $(SRC_DIR)/kernel/vfs/Path.cpp -o $(BUILD_DIR)/Path.o $(CFLAGS) -fno-exceptions -fno-rtti # Assembly -> Object files $(BUILD_DIR)/boot.o: diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 319b5a9..7bd0ca1 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -48,6 +48,10 @@ extern "C" void kernel () FileSystem::initialize(); + // Testing my path resolution functions + Path test = Path("/boot/myos.bin"); + FileSystem::ResolvePath(test); + #ifdef USERMODE_RELEASE // Lets jump into user mode diff --git a/source/kernel/vfs/Path.cpp b/source/kernel/vfs/Path.cpp new file mode 100644 index 0000000..3489836 --- /dev/null +++ b/source/kernel/vfs/Path.cpp @@ -0,0 +1,83 @@ +// +// Created by nigel on 19/02/23. +// +#include "Path.h" +#include "../memory/KernelHeap.h" +String::String(char* characters) +: chars(characters) +{ + +} + +char* String::str(){ + return chars; +} + +unsigned int String::length () +{ + int i = 0; + + while ( chars[i] != '\0'){ + i++; + } + + return i; +} + +// Returns a null character if size exceeds limits +char String::operator[] (size_t idx) +{ + if( idx > this->length()) + return '\0'; + + return chars[idx]; +} + +const char String::operator[](size_t idx) const { + return (const char) chars[idx]; +} + +StringView::StringView(String &string, unsigned int start, unsigned int end) +: String(string), begin(start), end(end) +{ + +} + +char* StringView::str(){ + char* str = (char*) malloc((this->length() * sizeof(char))+1); + + int index = 0; + for ( int i = begin; i < end ; i++){ + str[index] = chars[i]; + index++; + } + chars[index+1] ='\0'; + return str; +} + + +Path::Path(char *path) +: path(String(path)) +{ + +} + +Path::Path(String &path) +: path(path) +{ + +} + +StringView Path::getbasename() +{ + unsigned int path_length = path.length(); + int i = path_length; + while (path[i] != '/') + i--; + + return StringView(path,i +1, path_length); +} + +char* Path::str() { + return path.str(); +} \ No newline at end of file diff --git a/source/kernel/vfs/Path.h b/source/kernel/vfs/Path.h new file mode 100644 index 0000000..2d6de27 --- /dev/null +++ b/source/kernel/vfs/Path.h @@ -0,0 +1,46 @@ +// +// Created by nigel on 19/02/23. +// +#pragma once +#include + +class String { +public: + String(char* characters); + String(String&) = default; + unsigned int length(); + + char* str (); + char operator[](size_t index) ; + const char operator[](size_t idx) const; + +protected: + char* chars; + + +}; + +class StringView : String { +public: + StringView(String& string, unsigned int start, unsigned int end ); + char* str (); +private: + unsigned int begin; + unsigned int end; +}; + +class Path{ +public: + Path(String& path); + Path(char* path); + + StringView getbasename(); + + char* str(); + +private: + String path; + +}; + + diff --git a/source/kernel/vfs/VFS.cpp b/source/kernel/vfs/VFS.cpp index cdb787c..3f59fc2 100644 --- a/source/kernel/vfs/VFS.cpp +++ b/source/kernel/vfs/VFS.cpp @@ -4,7 +4,7 @@ #include "../drivers/ata/ataDevice.h" #include "../partitiontable/mbr/MasterBootRecord.h" #include "../memory/KernelHeap.h" -#include "../../lib/include/string.h" +#include "Path.h" #include "../filesystem/FAT/DirectoryEntry.h" MOUNT_INFO mountInfo; @@ -360,4 +360,59 @@ void FileSystem::initialize() */ +} + +char* FindNextEntryName (char* path ) +{ + int length = strlen(path); + + char* name = path; + int i = 0; + + if( name[0] == '/') + i++; + + while ( name[i] != '/' && i <= length) + i++; + + char* s = (char*) malloc(i + 1 * sizeof(char)); + for ( int a = 0; a < i; a++) + s[a] = path[a]; + + s[i + 1] = '\0'; + + return s; + +} + + + +void FileSystem::ResolvePath(Path &path) +{ + char* string_path = path.str(); + void* cpy = string_path; + + bool isAbsolutePath = string_path[0] == '/'; + if(isAbsolutePath) + { + // strip the first slash + string_path++; + } + + char* entry_name = FindNextEntryName(string_path); + printf("Look for entry with name: %s\n", entry_name); + int skip = strlen(entry_name); + free(entry_name); + + + entry_name = FindNextEntryName(string_path + skip); + printf("Look for entry with name: %s\n", entry_name); + skip = strlen(entry_name); + free(entry_name); + + + + + free(cpy); + } \ No newline at end of file diff --git a/source/kernel/vfs/VFS.h b/source/kernel/vfs/VFS.h index f7ec66d..17b92c0 100644 --- a/source/kernel/vfs/VFS.h +++ b/source/kernel/vfs/VFS.h @@ -1,5 +1,7 @@ #pragma once #include +#include "Path.h" + #define FS_FILE 0 #define FS_DIRECTORY 1 #define FS_INVALID 2 @@ -73,4 +75,6 @@ extern PFILESYSTEM _filesystems[DEVICE_MAX]; public: static void initialize(); + static void ResolvePath(Path& path); + }; \ No newline at end of file diff --git a/source/lib/include/mem.h b/source/lib/include/mem.h index 83216f6..e5ff1dd 100644 --- a/source/lib/include/mem.h +++ b/source/lib/include/mem.h @@ -1,6 +1,7 @@ #pragma once // NOTE: These should not be inline -inline void* memset (void* ptr, int value, size_t num){ +inline void* memset (void* ptr, int value, size_t num) +{ for( int i = 0; i < num; i++ ) { unsigned char* data = (unsigned char*)ptr+ i; @@ -12,19 +13,19 @@ inline void* memset (void* ptr, int value, size_t num){ inline int memcmp( const void* ptr1, const void* ptr2, size_t num) - { - const unsigned char * cs = (const unsigned char*) ptr1; - const unsigned char * ct = (const unsigned char*) ptr2; +{ + const unsigned char * cs = (const unsigned char*) ptr1; + const unsigned char * ct = (const unsigned char*) ptr2; - for (int i = 0 ; i < num ; i++, cs++, ct++ ){ - if( *cs < *ct){ - return -1; - } else if( *cs > *ct){ - return 1; - } - } + for (int i = 0 ; i < num ; i++, cs++, ct++ ){ + if( *cs < *ct){ + return -1; + } else if( *cs > *ct){ + return 1; + } + } - return 0; + return 0; - } \ No newline at end of file +} \ No newline at end of file -- 2.39.5 From b07b4f0d38b40e709fe457c0a1a1e4aab6aeaf06 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 19 Feb 2023 23:38:32 +0100 Subject: [PATCH 096/115] Moving certain aspects into their own static library Problem: As our kernel grows we need more complex datastructures and functions these would come from the standard C/C++ library with normal programs. The kernel is a freestanding programme and has no access to standard libraries. Solution: We build a mini version of the standard C/C++ library which will contain the datastructures and functions we want. This library can then be statically linked into our kernel binary. Making it a statically linked library also gives more structure to the project. Keeping these random functions and datastructures in the kernel just clutters the kernel source code with less relevant source code. --- Makefile | 16 +--- source/CoreLib/Makefile | 33 +++++++ source/CoreLib/Memory.cpp | 58 ++++++++++++ source/CoreLib/Memory.h | 12 +++ source/CoreLib/Path.cpp | 24 +++++ source/CoreLib/Path.h | 22 +++++ source/CoreLib/Stack.cpp | 3 + .../{lib/include/stack.h => CoreLib/Stack.h} | 2 +- source/CoreLib/String.cpp | 39 ++++++++ source/CoreLib/String.h | 18 ++++ source/CoreLib/StringView.cpp | 14 +++ source/CoreLib/StringView.h | 14 +++ source/CoreLib/bin/memory.o | Bin 0 -> 4712 bytes source/CoreLib/bin/path.o | Bin 0 -> 4988 bytes source/CoreLib/bin/stack.o | Bin 0 -> 788 bytes source/CoreLib/bin/string.o | Bin 0 -> 4400 bytes source/CoreLib/bin/stringview.o | Bin 0 -> 3772 bytes source/kernel/drivers/acpi/rsdp.h | 3 +- source/kernel/drivers/ata/ataDevice.cpp | 1 - source/kernel/kernel.cpp | 4 - source/kernel/memory/PhysicalMemoryManager.h | 3 +- source/kernel/memory/TaskStateSegment.h | 2 +- source/kernel/memory/memory.h | 3 +- .../supervisorterminal/superVisorTerminal.h | 4 +- source/kernel/terminal/kterm.h | 5 +- source/kernel/vfs/Path.cpp | 83 ------------------ source/kernel/vfs/Path.h | 46 ---------- source/kernel/vfs/VFS.cpp | 7 +- source/kernel/vfs/VFS.h | 2 +- source/lib/include/mem.h | 31 ------- source/lib/include/string.c | 26 ------ source/lib/include/string.h | 4 - 32 files changed, 255 insertions(+), 224 deletions(-) create mode 100644 source/CoreLib/Makefile create mode 100644 source/CoreLib/Memory.cpp create mode 100644 source/CoreLib/Memory.h create mode 100644 source/CoreLib/Path.cpp create mode 100644 source/CoreLib/Path.h create mode 100644 source/CoreLib/Stack.cpp rename source/{lib/include/stack.h => CoreLib/Stack.h} (96%) create mode 100644 source/CoreLib/String.cpp create mode 100644 source/CoreLib/String.h create mode 100644 source/CoreLib/StringView.cpp create mode 100644 source/CoreLib/StringView.h create mode 100644 source/CoreLib/bin/memory.o create mode 100644 source/CoreLib/bin/path.o create mode 100644 source/CoreLib/bin/stack.o create mode 100644 source/CoreLib/bin/string.o create mode 100644 source/CoreLib/bin/stringview.o delete mode 100644 source/kernel/vfs/Path.cpp delete mode 100644 source/kernel/vfs/Path.h delete mode 100644 source/lib/include/mem.h delete mode 100644 source/lib/include/string.c delete mode 100644 source/lib/include/string.h diff --git a/Makefile b/Makefile index faad734..b4eb068 100644 --- a/Makefile +++ b/Makefile @@ -1,11 +1,10 @@ - EMULATOR = qemu-system-i386 AS = ${HOME}/opt/cross/bin/i686-elf-as CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ -CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra +CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -I source/CoreLib/build/include -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/Path.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/VFS.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/string.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o +OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/VFS.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o SRC_DIR = source BUILD_DIR = build @@ -53,8 +52,7 @@ test_disk: all build_kernel: $(OBJ_LINK_LIST) - $(CC) -T $(SRC_DIR)/kernel//linker.ld -o $(BUILD_DIR)/myos.bin \ - -ffreestanding -ggdb -Og -nostdlib $(OBJ_LINK_LIST) -lgcc + $(CPP) -T $(SRC_DIR)/kernel/linker.ld -o $(BUILD_DIR)/myos.bin -ffreestanding -ggdb -Og -nostdlib $(OBJ_LINK_LIST) -lgcc -L source/CoreLib/build -lCoreLib build_x86_64: $(AS) $(SRC_DIR)/cgc/x86_64/crti.s -o $(BUILD_DIR)/crti_64.o @@ -71,7 +69,7 @@ $(BUILD_DIR)/kterm.o: $(CPP) -c $(SRC_DIR)/kernel/terminal/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/io.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/io/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c $(SRC_DIR)/kernel/drivers/io/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti $(BUILD_DIR)/idt.o: $(CPP) -c $(SRC_DIR)/kernel/interrupts/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -82,9 +80,6 @@ $(BUILD_DIR)/gdtc.o: $(BUILD_DIR)/pic.o: $(CPP) -c $(SRC_DIR)/kernel/drivers/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti -$(BUILD_DIR)/string.o: - $(CC) -c $(SRC_DIR)/lib/include/string.c -o $(BUILD_DIR)/string.o $(CFLAGS) -std=gnu99 - $(BUILD_DIR)/PhysicalMemoryManager.o: $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -136,9 +131,6 @@ $(BUILD_DIR)/prekernel.o: $(BUILD_DIR)/processor.o: $(CPP) -c $(SRC_DIR)/kernel/i386/processor.cpp -o $(BUILD_DIR)/processor.o $(CFLAGS) -fno-exceptions -fno-rtti -$(BUILD_DIR)/Path.o: - $(CPP) -c $(SRC_DIR)/kernel/vfs/Path.cpp -o $(BUILD_DIR)/Path.o $(CFLAGS) -fno-exceptions -fno-rtti - # Assembly -> Object files $(BUILD_DIR)/boot.o: $(AS) $(SRC_DIR)/kernel/boot/boot.s -o $(BUILD_DIR)/boot.o diff --git a/source/CoreLib/Makefile b/source/CoreLib/Makefile new file mode 100644 index 0000000..b5a0cbb --- /dev/null +++ b/source/CoreLib/Makefile @@ -0,0 +1,33 @@ +CPP = ${HOME}/opt/cross/bin/i686-elf-g++ +CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra + +SRC_DIR = . +BUILD_DIR = build +OBJ_FOLDER = bin +OUTPUTFILE = $(BUILD_DIR)/libCoreLib.a + +OFILES = $(OBJ_FOLDER)/memory.o $(OBJ_FOLDER)/path.o $(OBJ_FOLDER)/stack.o $(OBJ_FOLDER)/string.o $(OBJ_FOLDER)/stringview.o + + +.phony: all +all: $(OUTPUTFILE) + cp *.h build/include/ + +$(OUTPUTFILE): $(OFILES) + ar -rc $(OUTPUTFILE) $(OFILES) + +$(OBJ_FOLDER)/memory.o: Memory.cpp + $(CPP) -c Memory.cpp -o $(OBJ_FOLDER)/memory.o $(CFLAGS) + +$(OBJ_FOLDER)/path.o: Path.cpp + $(CPP) -c Path.cpp -o $(OBJ_FOLDER)/path.o $(CFLAGS) + +$(OBJ_FOLDER)/stack.o: Stack.cpp + $(CPP) -c Stack.cpp -o $(OBJ_FOLDER)/stack.o $(CFLAGS) + +$(OBJ_FOLDER)/string.o: String.cpp + $(CPP) -c String.cpp -o $(OBJ_FOLDER)/string.o $(CFLAGS) + +$(OBJ_FOLDER)/stringview.o: StringView.cpp + $(CPP) -c StringView.cpp -o $(OBJ_FOLDER)/stringview.o $(CFLAGS) + diff --git a/source/CoreLib/Memory.cpp b/source/CoreLib/Memory.cpp new file mode 100644 index 0000000..fce2e66 --- /dev/null +++ b/source/CoreLib/Memory.cpp @@ -0,0 +1,58 @@ +// +// Created by nigel on 19/02/23. +// +#include "Memory.h" + +void* memset (void* ptr, int value, size_t num) +{ + for( int i = 0; i < num; i++ ) + { + unsigned char* data = (unsigned char*)ptr+ i; + *data = (unsigned char)value; + } + return ptr; +} + + +int memcmp( const void* ptr1, const void* ptr2, size_t num) +{ + const unsigned char * cs = (const unsigned char*) ptr1; + const unsigned char * ct = (const unsigned char*) ptr2; + + + for (int i = 0 ; i < num ; i++, cs++, ct++ ){ + if( *cs < *ct){ + return -1; + } else if( *cs > *ct){ + return 1; + } + } + + return 0; + +} + +size_t strlen(const char* str) { + size_t len = 0; + while(str[len]){ + len++; + } + return len; +} + +int strncmp ( const char* str1, const char* str2, size_t num ){ + for( int i = 0; i < num ; i++){ + + if( str1[i] < str2[i]){ + return -1; + } + + if( str1[i] > str2[i] ){ + return 1; + } + + + } + + return 0; +} \ No newline at end of file diff --git a/source/CoreLib/Memory.h b/source/CoreLib/Memory.h new file mode 100644 index 0000000..e31a5dc --- /dev/null +++ b/source/CoreLib/Memory.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +void* memset (void* ptr, int value, size_t num); + +int memcmp( const void* ptr1, const void* ptr2, size_t num); + +size_t strlen(const char* str); + +int strncmp ( const char* str1, const char* str2, size_t num ); \ No newline at end of file diff --git a/source/CoreLib/Path.cpp b/source/CoreLib/Path.cpp new file mode 100644 index 0000000..d23b226 --- /dev/null +++ b/source/CoreLib/Path.cpp @@ -0,0 +1,24 @@ +// +// Created by nigel on 19/02/23. +// +#include "Path.h" + +Path::Path(String path) +: path(path) +{ + +} + +StringView Path::getbasename() +{ + unsigned int path_length = path.length(); + int i = path_length; + while (path[i] != '/') + i--; + + return {path,static_cast(i +1), path_length}; +} + +char* Path::str() { + return path.str(); +} \ No newline at end of file diff --git a/source/CoreLib/Path.h b/source/CoreLib/Path.h new file mode 100644 index 0000000..ec4d955 --- /dev/null +++ b/source/CoreLib/Path.h @@ -0,0 +1,22 @@ +// +// Created by nigel on 19/02/23. +// +#pragma once +#include +#include "StringView.h" + + +class Path{ +public: + explicit Path(String path); + + StringView getbasename(); + + char* str(); + +private: + String path; + +}; + + diff --git a/source/CoreLib/Stack.cpp b/source/CoreLib/Stack.cpp new file mode 100644 index 0000000..af9520e --- /dev/null +++ b/source/CoreLib/Stack.cpp @@ -0,0 +1,3 @@ +// +// Created by nigel on 19/02/23. +// diff --git a/source/lib/include/stack.h b/source/CoreLib/Stack.h similarity index 96% rename from source/lib/include/stack.h rename to source/CoreLib/Stack.h index 0128bf6..b363fed 100644 --- a/source/lib/include/stack.h +++ b/source/CoreLib/Stack.h @@ -1,5 +1,5 @@ #pragma once -#include "../../kernel/memory/KernelHeap.h" +#include "../kernel/memory/KernelHeap.h" #include template diff --git a/source/CoreLib/String.cpp b/source/CoreLib/String.cpp new file mode 100644 index 0000000..1aaf064 --- /dev/null +++ b/source/CoreLib/String.cpp @@ -0,0 +1,39 @@ +#include "String.h" +#include +#include + + +String::String(char* characters) +: chars(characters) + { + + } + +char* String::str(){ + return chars; +} + +unsigned int String::length () +{ + int i = 0; + + while ( chars[i] != '\0'){ + i++; + } + + return i; +} + +// Returns a null character if size exceeds limits +char String::operator[] (size_t idx) +{ + if( idx > this->length()) + return '\0'; + + return chars[idx]; +} + +const char String::operator[](size_t idx) const { +return (const char) chars[idx]; +} + diff --git a/source/CoreLib/String.h b/source/CoreLib/String.h new file mode 100644 index 0000000..8ff3f05 --- /dev/null +++ b/source/CoreLib/String.h @@ -0,0 +1,18 @@ +#pragma once +#include + +class String { +public: + String(char* characters); + String(String&) = default; + unsigned int length(); + + char* str (); + char operator[](size_t index) ; + const char operator[](size_t idx) const; + +protected: + char* chars; + + +}; \ No newline at end of file diff --git a/source/CoreLib/StringView.cpp b/source/CoreLib/StringView.cpp new file mode 100644 index 0000000..5392c87 --- /dev/null +++ b/source/CoreLib/StringView.cpp @@ -0,0 +1,14 @@ +// +// Created by nigel on 19/02/23. +// +#include "StringView.h" + +StringView::StringView(String string, unsigned int start, unsigned int end) + : String(string), begin(start), end(end) +{ + +} + +char* StringView::str(){ + //TODO: Not implemented +} \ No newline at end of file diff --git a/source/CoreLib/StringView.h b/source/CoreLib/StringView.h new file mode 100644 index 0000000..725284b --- /dev/null +++ b/source/CoreLib/StringView.h @@ -0,0 +1,14 @@ +// +// Created by nigel on 19/02/23. +// +#pragma once +#include "String.h" + +class StringView : String { +public: + StringView(String string, unsigned int start, unsigned int end ); + char* str (); +private: + unsigned int begin; + unsigned int end; +}; diff --git a/source/CoreLib/bin/memory.o b/source/CoreLib/bin/memory.o new file mode 100644 index 0000000000000000000000000000000000000000..7b6893fc65737d96e5c0f55bb73064c293c0145a GIT binary patch literal 4712 zcmb_fYiv}<6`r~G&h^^6ek{9y!2}k93CMWYCKT3S5{#23yh#iM+!|*ech@WS#qM1b zsG&(nN~qhYNLAY(Ak-gKD^==4RR~d|0&=bZWGoHLJ|d-wB??)o(6oax4y$!0CaBJEz!dI_u9d=_R0&fOWAKH!@k z3rz3sxI!Iw?U$AqXRh&qo0Y$vduw{^AGc;edg|cF^lsnuDaC04;mmb@=FtEj_^{g9 zez_kJ+AnvV`*ZxAN@()kE0p)HkO4n)WPEJq%ExGTKR_g8^YWO8@$8_%YJVTo8BY18 zYk}!8m4pZbzpT!0zZ__4zZ|yXZ%>6z-~CUapEVd0j9WB^mT%#)oHRc@&~AHxez6L* zNw@L#!U4Fs)wGqsC;mhbum(Zk9abJzAWSZ9KTa+~EFs{&b#OLKP><2{B!RE#Wk9PX zaz&ToJqOD&LGBUz@q8ZUS;#PiU-&1U;y4~XU8GWm0J)~f)l06;kOv`Vu~uL`n|h%p zA)^pq2oEF2*0xd5a}dhKnB9UrD3pdbQD$ouwEKNAs5HI=>4fkLBk-72x5Dn1>Awr- zw;@K}DYBIT;=T@%TVyps3kp9*P_}N!4hX;SE<9~69z3{+bmKe|CxF2ovfc#e7DSdG zj8n*WAU}r~sVWO~y$8}?VZARsE(=Q!Rm~wjS`AEbp`7A8cxY~z;_m?MHqFFx$ZpEO zF=bGnR~)}UmRZK+?D?dw1z|Nrw1HtSrAg4{#v!sedo2~W8|HRMb1RG>1j&6e`53&1 zsfRYngme&}w{)IH@T2I+LC}JhO~--pmCWyd$ZsN@v7VW}P0RUa|A2pc$XNL5wuJ~G z{*BX$@`o3hZHilL+a3z?dG^-MlZ!YuTVROptH-h1nSZ&p9onF-^(&zdNqdfIKPA53P&OZ*9Dz$(!=Ivdoe6H()zMfM{pJSGad z0JfNhE$&8s$z&@r&|2ATxLA8Mi-jpqxEpb0p4Kph3P%utGb_Bf={&Q`Y{ezE1Z`y}a(O6w)n)iv)DA#~q|lsoJ_I!&kGha-^) z64j!I3UbH!R(#>4ckLwPH1w zEjsB)Y9di#`BE_(sk`WnQJpAN+_^49uR1OpAJ61V3AcY;oC5aKW8G{x8Y`pS8}hL| z2O`5gJ^dRa{r%DYXkVna;MR)HmaJ2BD!CNQL?tz`rR)^lT&+;9lp?*^Y&sd~-J6Z{ zW-=AWsk(_`I#QT% z9oD!en&n08oR4SI+ z5Z}=2v0rn8?aEe!k=y?g^9Y+6TcD6?A5Mt_U2*Hag98^g6 zHTmVY8Sn{Z(`%IcV+zv>k19N_@U+4&DLk+6>k2OsqK@w=o4yUX@Lmdp*OmWG<^P$& zUn~5r!uJTVr5`B!Lxnb$mFnzJxIp1jLgd{@h&-DW?ohZ#A$?-g_)&#PLX116>}M5z zkq~iSR(Mh2Hx+(g;g1wvS9n9=Z9>%l3uXUG;U5T*|1SzZB1HZ$gz|MNypIsP2bA5T zaFfD^6b=(Y_AC34!ZGE~5F*Yo<*zBEUkk^VNCzQ&D+qC(Rw?XL_$h^(6h1--egud& z93z|1RrpnfELuHLa1%+OTk&v0Yp(N*%cAma7fn{HELw5$(X^ASWyf>HObK05Pb8BS zXHr}FQYxRTx^vixN}`x`;PM7kirIT8`CQS_{m8FXa*s`o{)a$CLL)gZ~(U9M_%jYxPKjPW0d7Y)42@ zP4h-!H`a%1SDs0#kLsct2@4QC1}gJm!IzSvn(liJw$`a@6?j7p4y~R-Ut``5nyK6GU{0)$DLzO(@Q!IT(p|UgE~DmulH%WqxT6}oaHdb$0? z?B~H99Uq&yz5GfeI{x;1b8~Z-U%xy%^W*kg{+U~H=5}bzkwUUH)wn$~E02!N4b3$| z$`+13WBvX3V-qKSWC;42x!vjNemeUFzYwO71_zJ5ho*O1X< zc5MRqjo?d!ka+?cf7JK|q20IvVf%;Cg!ZE`d`4&^6idkX0_IwPd>qYFB(_20+kr-O zD1Fd83r5N>Lh_BK!59t9cW4{x_%!HaAa4L)LsdRRxNg^kujR{7(A{sLc(bWAb0B?@ zmX8DWK>IE*0Ca}$11B7lXgk;7AXKYS*VE)A8lN(WKTonPqQdowz#}j_e#X+IH;oRjxTbL{aa0gSwcSuU_(~t4l(*g=szj?tau@0u8rga0m_e zRqy~B3;soqVU{YkNcVyB9+*__&~4R z+MSO}=mPhue!;!s6Y?VXkWcz!k%(hUgRtrxQi9&ay<1G-`sF~8Ru8)|f)uHD0&Gpn zJ@L)Gk}>4tOJql2c=?5Hju2ZS?}^1D{+^XR6t{Qb5?SVPgw@;v78k_AJO(0e5*>Fc zu1JhR@9~8(4Irw{c1#lEUAhX%GtOmqI>^Tp5%%vwe-^*OTDkTv^jS&v@ckPrzqpK3|nPEAYK%5-2mNHg$?xk2HK8CIAw!^g}Pkez`o zW(V;FSe-SKARpXn%2(`U!i)zFDB}XGq$y{7K7=&!$icxw8M~NH7c4uQsauuIl(p-O zsFyBS6SkmAz-DO7u9Yf<(ZOAZa^xSC59*d6^$&sBBdVb`eoHKF3SeSz#ATby2QX3W-LgUMf_q ze1aFw#KdH|nz7RZ8|hD_f*^HtVjAI3INrp9ZneLgtmc&L!PHAMFQ_ zBEnbUs)nI@CfJiZqCGq|F(3RuGkC^W_gHGDZkpaP=$^ScBj&4(Y}sN@Z%m_U*Yl}U zLeI%!ljh99Bvq_VS*c2?V3kvQGr7}9Gquw?W0kAZQ<#y|jto}u^uuGRdbLr@S*g)# z%{oxZsx6buO;7*d4!i?br|nd(R;|}lIs=dY6uio9?b&$N(S88r-kuXq8l zvhbTFMq;5)`gXLM`+fooA=W{(71jOTHubxo@_)*hF(02Dd2QtN5oJt27{B=`Z`vMk zd_lFKVEAS+#9!u`42Xp2*Od5?QH$o7cLy#sJ`z}5 zz8|!kH}!j!)@k_AcytkedJ)f;u=}iG|K}Fz=a<+$0;BVXr73Fe^5&6Re6_(;-w*Q_ z&AiOLi~i%$aYvdzj@p|RI3EeTs`za3VRASRK1@uWh>76L^LGa4O=4L(h!8H*xPpj# ze+@B!_csxCNsZiJ#=mL&m&Q19r+$UT2Q(hkcuM10jh8e&qwzWs z^@p0jsrffF{#ncaLBuinr^ffSJdDRD<*gc5YV6UtmI&KEjYAqgN<`cljWvxIwEij) zexKEdr4FpQ}#stKtl56(=TZc!wbH|FQ6=9JY_(oU-uutM_4s=}=`Q z+A!*{;)Hk`=QIIYok1Xur8=MY0O=3QqY8hddJAu(bRA99oQ=ni^lkfMqS`UnYKTpwBRE=|=e>=Gn&adnS@ z_r}-W=Imd_N4YzH4bW~Mkm61FdzpkTuI^*tz5WvLw-++{;}^;G_XKG6;ry^XtM3Pg zb9B@{gX*=r4(ES#jkJ#XYm4lj!^aK3gPMgltS@SGr}kU0d$MWe#7FjPsNOt^$bOAynca(-Jsu0hLI!-4@EH0sh^9`I=ipAV6kVRg zICEd9NvG~3&T*FIDGhSlfk^nY*LRDo6cM_9Ca{}?03F|dV0GH*TCZcCvdO#eslv~4 z=T>lv&r}8>WhvHqVk(Ir5}Z*W18~Bkpc2C}9?lYurY6*ssy$r!C`;AGo9p)$7euHX z4>h^|*W1s`{+F7o?BTBH{D`!VyV3LXIQZ}0d(Aa9sJK`2kv>y9`nopUf_$4~LNQ8x zoelRz{+wjOa4H{|CgpDuBOQ}eze+mQ-n^A8{E}*_(4pq2I3w+HOY#GCpu=!~^A=-L literal 0 HcmV?d00001 diff --git a/source/CoreLib/bin/string.o b/source/CoreLib/bin/string.o new file mode 100644 index 0000000000000000000000000000000000000000..482fce0ad4b555babe51f8a5a91c4429992ea669 GIT binary patch literal 4400 zcmb_fU2Ggj9iQ3T-8=iv=d;hBv0I<3#MlJi#m2aaW4Cr(CoyT#5-TB1xY+lx_d(Bh z*S)=vgpU-tpIjoyLmw)cf`mY=D53=k5LAG015~I8Bp%8O5)y?<i+4>XdYtv`p(zV+_y+qbt~ zjU0Nz?r4~u-_ZwdSpU3mF}dTq|4qe>G*&{;YRR1+YK$3->lD8Iml#Hg3ete~2^XL@ zidcXU`+nVj2x6}LuM-4}321mow+SNp%Mga*7&_jELD%%a-B5&y(M-b+;Ge?qB=Pgm z_>N*=okH(7$d>ajLh^jm;G<+dTh3sfmI>my?X9zUol;8qapyrzYIf8)yCWKLxy6iB6GTa+_8DkF0 zE;87D9bAAaN1LJDWIe^~Wybf8QHI)0of)*|Ve^mB&Vovy^X&+BSU4@YPQAiuc$A#F z(L?BcAI3n2%%HkQ!V{neK;4PXw@-rWr+F#Fe&9azfgF!>E4`b%Vo)`8Bq+sF+|Z@VrK=a%nf z!QeeXA7<1Hwi=xo#GVm>nvV%E;`~^2Zj>Jm9tvioUA)^|9Jo5jVPMAjy@S5++^9yn za(Fd5J<8_?vr$s|J6Uj4r#JzF`JkH_)KHT)gH1(=Xz$|t!qK2_WN3t9(&-8I!Ei1} z!N@Ok7%Vc^xGx+Gx^jvfmeUHua(FtZrtJJrMS~+}a*7CDz>OkOZMt=Jc&0rVoW^t7 z9YIwnho~%1fUzDdL;A0Z74+^B^ndpVme6;ceVSi`V}Eneu3})u>+Q-0MP)@HU%$$kZb8=M(pj((FHz6GQ0aihn)2ee@>7$G2k$ea>vy~k)XBZhGvkTBXI z>o*S@VZu19KW=a{I&V%3+iw`dgx@z$iWt3dgP+J5kvohj^GPT;V)p{?JZJE_rXkl_ z@v61%u=Vq&X4f3MSk5octUQ<@{)7}1FRyGeSI4qersQ0yTI1z{Q0F z>>8_7Ej#5@>)iPg)sV!mu;V-$fog<_4BD&>5vDW|KeR;bv{ zZqfRBu2e}mQ_}}qA;?sOIduSQ}L1#6I z-3A}T8wKlax(Xs&si#X8^OnG^jAx!*m2fv8o~c$@qEOki66IpvDkYAmG7lr$#C_H! zt5m6OVqu9RDeU9J53D6>mAaj=63Z3ay1$tIzxY+EP9kGhYPCeEm`>y~nM85+;OwMT z$|c;2CyM1vsh+jui4h5Va+hR*)tqeB%Eb$e9a~S?^;1AHi? z>rdgyqQ{atHM+vtQaJFqcBI2ty#)(bHxIFTVKnteU40C?kD;r#QB%LP<$LJXj)*Z1 z{iEpWrPs7M@`P_o-)P@i`soryTf)Uixx9$3-l|R8lkR*_?P_#EsHU^O-c~f>?yoxH z4X+x!|2;fzVNdflKeSw-&#h3?!iTER>zNwWt{YdCx0b|z0CH73;^{@KYDN4Cz^oFBn2vFX35<7bF%WRwOJw4 zgy=&O-%p5nrwL&s8 z4@sPpc&|iyx07ECNVzXc+>rQ~#Fr$pccp|A^m#FLl*qq-&rkb+bhJa{g z_j}mkZ9u7jRi4#1x|kf(%j@v jc4SYqI#VFoi}=&45+NJKq1J`&wVT1b-xeBoPz6D4^ROQv=R~$Ra=R^Q6Z3!B7u+qA@Kr;z90eLH+ROq z_5<+1k!HU0H|Lx=b7#E1y>jW3Qc7V+iiFsagt+fSmZJ&|iz!hMt9O6DwUXId&ECy# zt>*7uNp7u9-Mx}|@txORwuG>SOwu`9M4S@2aZaH95eO@3zX5h^3RCif=@S4eneGrW zHfCXElT%o1<&zg7<>oMDUci*Jl9@#qMkrXRFJa!qxPu{|fIhK=NsKFN+Wsfi@^#GL z-gbDF4)*hyGLvs(z6SXxz;`fI2r)Vc17ZCRGK2jZ_?vB;{U%sv^ac!1V|+*hFv>j- zNhptO{&i?CV9a2AgdS^{63Qdbimh=+m1>F98pNcU7}AodO+bqLgi@n3zoZNIo%tKM zY$Bch0Ky~}i4m$2Be$WrgYk6?No#`E1h=QAXj_Tbpk(47V7!T;Tty*A-|Qs4lT)tW z5{WS-WJIzCU5Wu8QlYcyzk}Zof0Dd!;lTHeL-i{R>z)wP0T`K*1sKF>Of$yn@DvWR zET@6#D6`EnnM_?EFZMGSd-Oclf@U$~{WL=%^xOep9;z%x`jAp)(hCZqlD4>5IEp3K zqr!2XbQ0K9f;#MJTsWm9IlC;MnoZY}qWyCt2d-uzf>#c^j5H+3S9y>t2G0qo^CG=<$x zLQFxyI2*o(AIK`bTbz z!0(42o|Ffz^Wbk|Sm4L)AAu9^a{2|Q2b}(dA#Evam1sI8?S=M|Jy%|`k1W~Jvu9FI zrX+%O`+mEqCeIH=!)<%M7i?IO5qP%e5m1ie|4i?qL4a62B`_*eT5q7*m zl%~}mHoC4je|fdI{P^S5CyLc-xmsQ*&iBHh@1AbEz8iQ=i1nb^IlbZfp*QSp1pVTC zyWMIO=bvjA=hxQ**Tw$*7OUSW#Cv6>r}n>hyQm`8(Y4E;(vn)RQ+K(!u^}p*e$TD= zUfbw_z5vK}-=k`{2e{1oZt#1ncKp-D~>x>bxok=2;`!uo^i6`a}BDQ~o2*0vM_M7su z#%DBsTH|$%{5?ZIoVh|@h_ymZxHVCt_O9$?e0=_J>NA;kk7DG*Oc7s_xLJBN!?CuJ*f9w z6#YNa9Q@FF!Tyo>Tix6P%4mV25@!0L#fsRcIMGIW41?eHfAdr4!3CNa@AD=ZcoUEJ zbOhrJ25AYx6&NSL^OfLWK6M{}hTcc4@0lP_8dlvC;{+TcfO*@fHh!Op@zmdgUy+O^ ztkJ}zR!U-Yru*h!q6q7$=G_3J>+`&v7hA4Hw9KafFIAu5aW>8r?}srk@x$`5>3YM E-;p%>LI3~& literal 0 HcmV?d00001 diff --git a/source/kernel/drivers/acpi/rsdp.h b/source/kernel/drivers/acpi/rsdp.h index eb5a87a..7d7aecb 100644 --- a/source/kernel/drivers/acpi/rsdp.h +++ b/source/kernel/drivers/acpi/rsdp.h @@ -1,7 +1,8 @@ #pragma once #include #include "./../../terminal/kterm.h" -#include "../../../lib/include/mem.h" +#include + struct RSDPTR { char signature[8]; uint8_t Checksum ; diff --git a/source/kernel/drivers/ata/ataDevice.cpp b/source/kernel/drivers/ata/ataDevice.cpp index 873aa0e..bde914a 100644 --- a/source/kernel/drivers/ata/ataDevice.cpp +++ b/source/kernel/drivers/ata/ataDevice.cpp @@ -12,7 +12,6 @@ void ATA_DEVICE::Soft_Reset(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive){ } - void ATA_DEVICE::Identify(uint16_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ // lets ignore which port we actually want to check for now ! diff --git a/source/kernel/kernel.cpp b/source/kernel/kernel.cpp index 7bd0ca1..9440716 100644 --- a/source/kernel/kernel.cpp +++ b/source/kernel/kernel.cpp @@ -1,10 +1,6 @@ /* Copyright © Nigel Barink 2023 */ -extern "C"{ -#include "../lib/include/string.h" -} - #include "memory/memory.h" #include "memory/KernelHeap.h" #include "memory/gdt/gdtc.h" diff --git a/source/kernel/memory/PhysicalMemoryManager.h b/source/kernel/memory/PhysicalMemoryManager.h index 9aa9c15..f83fff1 100644 --- a/source/kernel/memory/PhysicalMemoryManager.h +++ b/source/kernel/memory/PhysicalMemoryManager.h @@ -1,8 +1,9 @@ #pragma once #include +#include + #include "../prekernel/bootstructure.h" #include "../terminal/kterm.h" -#include "../../lib/include/mem.h" #include "../bitmap.h" #define BLOCK_SIZE 4092 diff --git a/source/kernel/memory/TaskStateSegment.h b/source/kernel/memory/TaskStateSegment.h index b41a4fb..f26b3ec 100644 --- a/source/kernel/memory/TaskStateSegment.h +++ b/source/kernel/memory/TaskStateSegment.h @@ -1,6 +1,6 @@ #pragma once #include "gdt/gdtc.h" -#include "../../lib/include/string.h" +#include struct TaskStateSegment { uint32_t prev_tss; diff --git a/source/kernel/memory/memory.h b/source/kernel/memory/memory.h index ea609ac..1f2df61 100644 --- a/source/kernel/memory/memory.h +++ b/source/kernel/memory/memory.h @@ -5,7 +5,8 @@ #include "memoryinfo.h" #include "../prekernel/multiboot.h" #include "../terminal/kterm.h" -#include "../../lib/include/mem.h" +#include + #include "../bitmap.h" #define BLOCK_SIZE 4092 diff --git a/source/kernel/supervisorterminal/superVisorTerminal.h b/source/kernel/supervisorterminal/superVisorTerminal.h index ad3c39b..f68456c 100644 --- a/source/kernel/supervisorterminal/superVisorTerminal.h +++ b/source/kernel/supervisorterminal/superVisorTerminal.h @@ -4,8 +4,6 @@ #include "../drivers/pit/pit.h" #include "../drivers/ps-2/keyboard.h" #include "../memory/PhysicalMemoryManager.h" -extern "C" { - #include "../../lib/include/string.h" -} +#include extern "C" void startSuperVisorTerminal(); \ No newline at end of file diff --git a/source/kernel/terminal/kterm.h b/source/kernel/terminal/kterm.h index 7ac6d27..8cce182 100644 --- a/source/kernel/terminal/kterm.h +++ b/source/kernel/terminal/kterm.h @@ -5,10 +5,7 @@ #include "../drivers/vga/colors.h" #include "../drivers/io/io.h" -extern "C" { -#include "../../lib/include/string.h" -} - +#include "CoreLib/Memory.h" void kterm_init(); diff --git a/source/kernel/vfs/Path.cpp b/source/kernel/vfs/Path.cpp deleted file mode 100644 index 3489836..0000000 --- a/source/kernel/vfs/Path.cpp +++ /dev/null @@ -1,83 +0,0 @@ -// -// Created by nigel on 19/02/23. -// -#include "Path.h" -#include "../memory/KernelHeap.h" -String::String(char* characters) -: chars(characters) -{ - -} - -char* String::str(){ - return chars; -} - -unsigned int String::length () -{ - int i = 0; - - while ( chars[i] != '\0'){ - i++; - } - - return i; -} - -// Returns a null character if size exceeds limits -char String::operator[] (size_t idx) -{ - if( idx > this->length()) - return '\0'; - - return chars[idx]; -} - -const char String::operator[](size_t idx) const { - return (const char) chars[idx]; -} - -StringView::StringView(String &string, unsigned int start, unsigned int end) -: String(string), begin(start), end(end) -{ - -} - -char* StringView::str(){ - char* str = (char*) malloc((this->length() * sizeof(char))+1); - - int index = 0; - for ( int i = begin; i < end ; i++){ - str[index] = chars[i]; - index++; - } - chars[index+1] ='\0'; - return str; -} - - -Path::Path(char *path) -: path(String(path)) -{ - -} - -Path::Path(String &path) -: path(path) -{ - -} - -StringView Path::getbasename() -{ - unsigned int path_length = path.length(); - int i = path_length; - while (path[i] != '/') - i--; - - return StringView(path,i +1, path_length); -} - -char* Path::str() { - return path.str(); -} \ No newline at end of file diff --git a/source/kernel/vfs/Path.h b/source/kernel/vfs/Path.h deleted file mode 100644 index 2d6de27..0000000 --- a/source/kernel/vfs/Path.h +++ /dev/null @@ -1,46 +0,0 @@ -// -// Created by nigel on 19/02/23. -// -#pragma once -#include - -class String { -public: - String(char* characters); - String(String&) = default; - unsigned int length(); - - char* str (); - char operator[](size_t index) ; - const char operator[](size_t idx) const; - -protected: - char* chars; - - -}; - -class StringView : String { -public: - StringView(String& string, unsigned int start, unsigned int end ); - char* str (); -private: - unsigned int begin; - unsigned int end; -}; - -class Path{ -public: - Path(String& path); - Path(char* path); - - StringView getbasename(); - - char* str(); - -private: - String path; - -}; - - diff --git a/source/kernel/vfs/VFS.cpp b/source/kernel/vfs/VFS.cpp index 3f59fc2..9fe8d3f 100644 --- a/source/kernel/vfs/VFS.cpp +++ b/source/kernel/vfs/VFS.cpp @@ -4,7 +4,7 @@ #include "../drivers/ata/ataDevice.h" #include "../partitiontable/mbr/MasterBootRecord.h" #include "../memory/KernelHeap.h" -#include "Path.h" +#include "../../CoreLib/Memory.h" #include "../filesystem/FAT/DirectoryEntry.h" MOUNT_INFO mountInfo; @@ -389,6 +389,8 @@ char* FindNextEntryName (char* path ) void FileSystem::ResolvePath(Path &path) { + // See reference material (1) https://man7.org/linux/man-pages/man7/path_resolution.7.html + char* string_path = path.str(); void* cpy = string_path; @@ -410,9 +412,6 @@ void FileSystem::ResolvePath(Path &path) skip = strlen(entry_name); free(entry_name); - - - free(cpy); } \ No newline at end of file diff --git a/source/kernel/vfs/VFS.h b/source/kernel/vfs/VFS.h index 17b92c0..b294244 100644 --- a/source/kernel/vfs/VFS.h +++ b/source/kernel/vfs/VFS.h @@ -1,6 +1,6 @@ #pragma once #include -#include "Path.h" +#include "../../CoreLib/Path.h" #define FS_FILE 0 #define FS_DIRECTORY 1 diff --git a/source/lib/include/mem.h b/source/lib/include/mem.h deleted file mode 100644 index e5ff1dd..0000000 --- a/source/lib/include/mem.h +++ /dev/null @@ -1,31 +0,0 @@ -#pragma once -// NOTE: These should not be inline -inline void* memset (void* ptr, int value, size_t num) -{ - for( int i = 0; i < num; i++ ) - { - unsigned char* data = (unsigned char*)ptr+ i; - *data = (unsigned char)value; - } - return ptr; -} - - - -inline int memcmp( const void* ptr1, const void* ptr2, size_t num) -{ - const unsigned char * cs = (const unsigned char*) ptr1; - const unsigned char * ct = (const unsigned char*) ptr2; - - - for (int i = 0 ; i < num ; i++, cs++, ct++ ){ - if( *cs < *ct){ - return -1; - } else if( *cs > *ct){ - return 1; - } - } - - return 0; - -} \ No newline at end of file diff --git a/source/lib/include/string.c b/source/lib/include/string.c deleted file mode 100644 index 672d1a8..0000000 --- a/source/lib/include/string.c +++ /dev/null @@ -1,26 +0,0 @@ -#include "string.h" - -size_t strlen(const char* str) { - size_t len = 0; - while(str[len]){ - len++; - } - return len; -} - -int strncmp ( const char* str1, const char* str2, size_t num ){ - for( int i = 0; i < num ; i++){ - - if( str1[i] < str2[i]){ - return -1; - } - - if( str1[i] > str2[i] ){ - return 1; - } - - - } - - return 0; -} diff --git a/source/lib/include/string.h b/source/lib/include/string.h deleted file mode 100644 index 7009681..0000000 --- a/source/lib/include/string.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once -#include -size_t strlen(const char* str); -int strncmp ( const char* str1, const char* str2, size_t num ); \ No newline at end of file -- 2.39.5 From 2bcc79216e52769b542ed2d7df4cfaf3c20fdb27 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 19 Feb 2023 23:47:43 +0100 Subject: [PATCH 097/115] Remove mlibc submodule. The standarc C/C++ will use later on will be added later. It may or not be mlibc --- .gitmodules | 3 --- mlibc | 1 - 2 files changed, 4 deletions(-) delete mode 100644 .gitmodules delete mode 160000 mlibc diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 82ee6dd..0000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "mlibc"] - path = mlibc - url = https://github.com/managarm/mlibc.git diff --git a/mlibc b/mlibc deleted file mode 160000 index aad4e7f..0000000 --- a/mlibc +++ /dev/null @@ -1 +0,0 @@ -Subproject commit aad4e7f64b8de2c113cf7fc08943d0f005b517f9 -- 2.39.5 From dea8ab7d710e386c198deb1a2973fee54792f9d2 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 20 Feb 2023 00:29:06 +0100 Subject: [PATCH 098/115] Improved build system Added new entries to .gitignore Moved away from source directory as central spot for all source code --- .gitignore | 9 +- {source/CoreLib => CoreLib}/Makefile | 8 +- {source/CoreLib => CoreLib}/Memory.cpp | 0 {source/CoreLib => CoreLib}/Memory.h | 0 {source/CoreLib => CoreLib}/Path.cpp | 0 {source/CoreLib => CoreLib}/Path.h | 0 {source/CoreLib => CoreLib}/Stack.cpp | 0 {source/CoreLib => CoreLib}/Stack.h | 0 {source/CoreLib => CoreLib}/String.cpp | 0 {source/CoreLib => CoreLib}/String.h | 0 {source/CoreLib => CoreLib}/StringView.cpp | 0 {source/CoreLib => CoreLib}/StringView.h | 0 Makefile | 142 ------------------ kernel/Makefile | 125 +++++++++++++++ {source/kernel => kernel}/bitmap.h | 0 {source/kernel => kernel}/boot/boot.s | 10 +- {source/kernel => kernel}/boot/multiboot.s | 0 {source/kernel => kernel}/bootcheck.h | 0 {source/kernel => kernel}/bootinfo.h | 0 {source/kernel => kernel}/crti.s | 0 {source/kernel => kernel}/crtn.s | 0 {source/kernel => kernel}/definitions.h | 0 .../kernel => kernel}/drivers/acpi/acpi.cpp | 0 {source/kernel => kernel}/drivers/acpi/acpi.h | 0 .../kernel => kernel}/drivers/acpi/rsdp.cpp | 0 {source/kernel => kernel}/drivers/acpi/rsdp.h | 0 .../drivers/ata/ataDevice.cpp | 0 .../kernel => kernel}/drivers/ata/ataDevice.h | 0 .../drivers/atapi/atapiDevice.cpp | 0 .../drivers/atapi/atapiDevice.h | 0 .../kernel => kernel}/drivers/cmos/cmos.cpp | 0 {source/kernel => kernel}/drivers/ide/ide.h | 0 .../drivers/ide/ideCommands.h | 0 .../drivers/ide/sampleIDE.definitions.h | 0 .../kernel => kernel}/drivers/ide/sampleIDE.h | 0 {source/kernel => kernel}/drivers/io/io.cpp | 0 {source/kernel => kernel}/drivers/io/io.h | 0 {source/kernel => kernel}/drivers/pci/pci.cpp | 0 {source/kernel => kernel}/drivers/pci/pci.h | 0 .../drivers/pci/pciDevice.cpp | 0 .../kernel => kernel}/drivers/pci/pciDevice.h | 0 {source/kernel => kernel}/drivers/pic/pic.cpp | 0 {source/kernel => kernel}/drivers/pic/pic.h | 0 {source/kernel => kernel}/drivers/pit/pit.cpp | 0 {source/kernel => kernel}/drivers/pit/pit.h | 0 .../drivers/ps-2/keyboard.cpp | 0 .../kernel => kernel}/drivers/ps-2/keyboard.h | 0 .../drivers/ps-2/scancodes/set1.h | 0 .../drivers/serial/serial.cpp | 0 .../kernel => kernel}/drivers/serial/serial.h | 0 {source/kernel => kernel}/drivers/vga/VBE.h | 0 .../kernel => kernel}/drivers/vga/colors.h | 0 .../filesystem/EXT2/SuperBlock.h | 0 .../filesystem/FAT/BiosParameterBlock.h | 0 .../filesystem/FAT/DirectoryEntry.h | 0 .../filesystem/FAT/ExtendBootRecord.h | 0 {source => kernel}/grub.cfg | 0 {source/kernel => kernel}/i386/README.md | 0 {source/kernel => kernel}/i386/processor.cpp | 0 {source/kernel => kernel}/i386/processor.h | 0 {source/kernel => kernel}/interrupts/idt.cpp | 0 {source/kernel => kernel}/interrupts/idt.h | 0 {source/kernel => kernel}/interrupts/idt.s | 0 {source/kernel => kernel}/irq_table.s | 0 {source/kernel => kernel}/irs_table.s | 0 {source/kernel => kernel}/kernel.cpp | 0 {source/kernel => kernel}/kernel.h | 0 {source/kernel => kernel}/linker.ld | 0 .../kernel => kernel}/memory/KernelHeap.cpp | 0 {source/kernel => kernel}/memory/KernelHeap.h | 0 .../memory/PageDirectory.cpp | 0 .../kernel => kernel}/memory/PageDirectory.h | 0 .../memory/PhysicalMemoryManager.cpp | 0 .../memory/PhysicalMemoryManager.h | 0 .../memory/TaskStateSegment.h | 0 .../memory/VirtualMemoryManager.cpp | 0 .../memory/VirtualMemoryManager.h | 0 {source/kernel => kernel}/memory/gdt/gdt.s | 0 {source/kernel => kernel}/memory/gdt/gdtc.cpp | 0 {source/kernel => kernel}/memory/gdt/gdtc.h | 0 {source/kernel => kernel}/memory/memory.cpp | 0 {source/kernel => kernel}/memory/memory.h | 0 {source/kernel => kernel}/memory/memoryinfo.h | 0 {source/kernel => kernel}/memory/paging.s | 0 .../partitiontable/mbr/MasterBootRecord.h | 0 .../partitiontable/mbr/PartitionTableEntry.h | 0 .../prekernel/bootstructure.h | 0 .../kernel => kernel}/prekernel/multiboot.h | 0 .../kernel => kernel}/prekernel/prekernel.cpp | 0 {source/kernel => kernel}/serial.h | 0 .../supervisorterminal/superVisorTerminal.cpp | 0 .../supervisorterminal/superVisorTerminal.h | 0 {source/kernel => kernel}/terminal/kterm.cpp | 0 {source/kernel => kernel}/terminal/kterm.h | 2 +- {source/kernel => kernel}/time.cpp | 0 {source/kernel => kernel}/time.h | 0 {source/kernel => kernel}/timer.cpp | 0 {source/kernel => kernel}/timer.h | 0 {source/kernel => kernel}/vfs/VFS.cpp | 0 {source/kernel => kernel}/vfs/VFS.h | 0 source/CoreLib/bin/memory.o | Bin 4712 -> 0 bytes source/CoreLib/bin/path.o | Bin 4988 -> 0 bytes source/CoreLib/bin/stack.o | Bin 788 -> 0 bytes source/CoreLib/bin/string.o | Bin 4400 -> 0 bytes source/CoreLib/bin/stringview.o | Bin 3772 -> 0 bytes 105 files changed, 140 insertions(+), 156 deletions(-) rename {source/CoreLib => CoreLib}/Makefile (89%) rename {source/CoreLib => CoreLib}/Memory.cpp (100%) rename {source/CoreLib => CoreLib}/Memory.h (100%) rename {source/CoreLib => CoreLib}/Path.cpp (100%) rename {source/CoreLib => CoreLib}/Path.h (100%) rename {source/CoreLib => CoreLib}/Stack.cpp (100%) rename {source/CoreLib => CoreLib}/Stack.h (100%) rename {source/CoreLib => CoreLib}/String.cpp (100%) rename {source/CoreLib => CoreLib}/String.h (100%) rename {source/CoreLib => CoreLib}/StringView.cpp (100%) rename {source/CoreLib => CoreLib}/StringView.h (100%) delete mode 100644 Makefile create mode 100644 kernel/Makefile rename {source/kernel => kernel}/bitmap.h (100%) rename {source/kernel => kernel}/boot/boot.s (92%) rename {source/kernel => kernel}/boot/multiboot.s (100%) rename {source/kernel => kernel}/bootcheck.h (100%) rename {source/kernel => kernel}/bootinfo.h (100%) rename {source/kernel => kernel}/crti.s (100%) rename {source/kernel => kernel}/crtn.s (100%) rename {source/kernel => kernel}/definitions.h (100%) rename {source/kernel => kernel}/drivers/acpi/acpi.cpp (100%) rename {source/kernel => kernel}/drivers/acpi/acpi.h (100%) rename {source/kernel => kernel}/drivers/acpi/rsdp.cpp (100%) rename {source/kernel => kernel}/drivers/acpi/rsdp.h (100%) rename {source/kernel => kernel}/drivers/ata/ataDevice.cpp (100%) rename {source/kernel => kernel}/drivers/ata/ataDevice.h (100%) rename {source/kernel => kernel}/drivers/atapi/atapiDevice.cpp (100%) rename {source/kernel => kernel}/drivers/atapi/atapiDevice.h (100%) rename {source/kernel => kernel}/drivers/cmos/cmos.cpp (100%) rename {source/kernel => kernel}/drivers/ide/ide.h (100%) rename {source/kernel => kernel}/drivers/ide/ideCommands.h (100%) rename {source/kernel => kernel}/drivers/ide/sampleIDE.definitions.h (100%) rename {source/kernel => kernel}/drivers/ide/sampleIDE.h (100%) rename {source/kernel => kernel}/drivers/io/io.cpp (100%) rename {source/kernel => kernel}/drivers/io/io.h (100%) rename {source/kernel => kernel}/drivers/pci/pci.cpp (100%) rename {source/kernel => kernel}/drivers/pci/pci.h (100%) rename {source/kernel => kernel}/drivers/pci/pciDevice.cpp (100%) rename {source/kernel => kernel}/drivers/pci/pciDevice.h (100%) rename {source/kernel => kernel}/drivers/pic/pic.cpp (100%) rename {source/kernel => kernel}/drivers/pic/pic.h (100%) rename {source/kernel => kernel}/drivers/pit/pit.cpp (100%) rename {source/kernel => kernel}/drivers/pit/pit.h (100%) rename {source/kernel => kernel}/drivers/ps-2/keyboard.cpp (100%) rename {source/kernel => kernel}/drivers/ps-2/keyboard.h (100%) rename {source/kernel => kernel}/drivers/ps-2/scancodes/set1.h (100%) rename {source/kernel => kernel}/drivers/serial/serial.cpp (100%) rename {source/kernel => kernel}/drivers/serial/serial.h (100%) rename {source/kernel => kernel}/drivers/vga/VBE.h (100%) rename {source/kernel => kernel}/drivers/vga/colors.h (100%) rename {source/kernel => kernel}/filesystem/EXT2/SuperBlock.h (100%) rename {source/kernel => kernel}/filesystem/FAT/BiosParameterBlock.h (100%) rename {source/kernel => kernel}/filesystem/FAT/DirectoryEntry.h (100%) rename {source/kernel => kernel}/filesystem/FAT/ExtendBootRecord.h (100%) rename {source => kernel}/grub.cfg (100%) rename {source/kernel => kernel}/i386/README.md (100%) rename {source/kernel => kernel}/i386/processor.cpp (100%) rename {source/kernel => kernel}/i386/processor.h (100%) rename {source/kernel => kernel}/interrupts/idt.cpp (100%) rename {source/kernel => kernel}/interrupts/idt.h (100%) rename {source/kernel => kernel}/interrupts/idt.s (100%) rename {source/kernel => kernel}/irq_table.s (100%) rename {source/kernel => kernel}/irs_table.s (100%) rename {source/kernel => kernel}/kernel.cpp (100%) rename {source/kernel => kernel}/kernel.h (100%) rename {source/kernel => kernel}/linker.ld (100%) rename {source/kernel => kernel}/memory/KernelHeap.cpp (100%) rename {source/kernel => kernel}/memory/KernelHeap.h (100%) rename {source/kernel => kernel}/memory/PageDirectory.cpp (100%) rename {source/kernel => kernel}/memory/PageDirectory.h (100%) rename {source/kernel => kernel}/memory/PhysicalMemoryManager.cpp (100%) rename {source/kernel => kernel}/memory/PhysicalMemoryManager.h (100%) rename {source/kernel => kernel}/memory/TaskStateSegment.h (100%) rename {source/kernel => kernel}/memory/VirtualMemoryManager.cpp (100%) rename {source/kernel => kernel}/memory/VirtualMemoryManager.h (100%) rename {source/kernel => kernel}/memory/gdt/gdt.s (100%) rename {source/kernel => kernel}/memory/gdt/gdtc.cpp (100%) rename {source/kernel => kernel}/memory/gdt/gdtc.h (100%) rename {source/kernel => kernel}/memory/memory.cpp (100%) rename {source/kernel => kernel}/memory/memory.h (100%) rename {source/kernel => kernel}/memory/memoryinfo.h (100%) rename {source/kernel => kernel}/memory/paging.s (100%) rename {source/kernel => kernel}/partitiontable/mbr/MasterBootRecord.h (100%) rename {source/kernel => kernel}/partitiontable/mbr/PartitionTableEntry.h (100%) rename {source/kernel => kernel}/prekernel/bootstructure.h (100%) rename {source/kernel => kernel}/prekernel/multiboot.h (100%) rename {source/kernel => kernel}/prekernel/prekernel.cpp (100%) rename {source/kernel => kernel}/serial.h (100%) rename {source/kernel => kernel}/supervisorterminal/superVisorTerminal.cpp (100%) rename {source/kernel => kernel}/supervisorterminal/superVisorTerminal.h (100%) rename {source/kernel => kernel}/terminal/kterm.cpp (100%) rename {source/kernel => kernel}/terminal/kterm.h (96%) rename {source/kernel => kernel}/time.cpp (100%) rename {source/kernel => kernel}/time.h (100%) rename {source/kernel => kernel}/timer.cpp (100%) rename {source/kernel => kernel}/timer.h (100%) rename {source/kernel => kernel}/vfs/VFS.cpp (100%) rename {source/kernel => kernel}/vfs/VFS.h (100%) delete mode 100644 source/CoreLib/bin/memory.o delete mode 100644 source/CoreLib/bin/path.o delete mode 100644 source/CoreLib/bin/stack.o delete mode 100644 source/CoreLib/bin/string.o delete mode 100644 source/CoreLib/bin/stringview.o diff --git a/.gitignore b/.gitignore index 82ca499..689ffcd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,10 +1,13 @@ -build -CON -.vscode +build/ +bin/ +.vscode/ +.idea/ isodir/ root/ *.iso *.img *.sym +*.o +*.a diff --git a/source/CoreLib/Makefile b/CoreLib/Makefile similarity index 89% rename from source/CoreLib/Makefile rename to CoreLib/Makefile index b5a0cbb..a37ab45 100644 --- a/source/CoreLib/Makefile +++ b/CoreLib/Makefile @@ -1,17 +1,15 @@ CPP = ${HOME}/opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -SRC_DIR = . -BUILD_DIR = build -OBJ_FOLDER = bin +BUILD_DIR = ../build/CoreLib +OBJ_FOLDER = ../bin/CoreLib OUTPUTFILE = $(BUILD_DIR)/libCoreLib.a OFILES = $(OBJ_FOLDER)/memory.o $(OBJ_FOLDER)/path.o $(OBJ_FOLDER)/stack.o $(OBJ_FOLDER)/string.o $(OBJ_FOLDER)/stringview.o - .phony: all all: $(OUTPUTFILE) - cp *.h build/include/ + cp *.h $(BUILD_DIR)/include/CoreLib $(OUTPUTFILE): $(OFILES) ar -rc $(OUTPUTFILE) $(OFILES) diff --git a/source/CoreLib/Memory.cpp b/CoreLib/Memory.cpp similarity index 100% rename from source/CoreLib/Memory.cpp rename to CoreLib/Memory.cpp diff --git a/source/CoreLib/Memory.h b/CoreLib/Memory.h similarity index 100% rename from source/CoreLib/Memory.h rename to CoreLib/Memory.h diff --git a/source/CoreLib/Path.cpp b/CoreLib/Path.cpp similarity index 100% rename from source/CoreLib/Path.cpp rename to CoreLib/Path.cpp diff --git a/source/CoreLib/Path.h b/CoreLib/Path.h similarity index 100% rename from source/CoreLib/Path.h rename to CoreLib/Path.h diff --git a/source/CoreLib/Stack.cpp b/CoreLib/Stack.cpp similarity index 100% rename from source/CoreLib/Stack.cpp rename to CoreLib/Stack.cpp diff --git a/source/CoreLib/Stack.h b/CoreLib/Stack.h similarity index 100% rename from source/CoreLib/Stack.h rename to CoreLib/Stack.h diff --git a/source/CoreLib/String.cpp b/CoreLib/String.cpp similarity index 100% rename from source/CoreLib/String.cpp rename to CoreLib/String.cpp diff --git a/source/CoreLib/String.h b/CoreLib/String.h similarity index 100% rename from source/CoreLib/String.h rename to CoreLib/String.h diff --git a/source/CoreLib/StringView.cpp b/CoreLib/StringView.cpp similarity index 100% rename from source/CoreLib/StringView.cpp rename to CoreLib/StringView.cpp diff --git a/source/CoreLib/StringView.h b/CoreLib/StringView.h similarity index 100% rename from source/CoreLib/StringView.h rename to CoreLib/StringView.h diff --git a/Makefile b/Makefile deleted file mode 100644 index b4eb068..0000000 --- a/Makefile +++ /dev/null @@ -1,142 +0,0 @@ -EMULATOR = qemu-system-i386 -AS = ${HOME}/opt/cross/bin/i686-elf-as -CC = ${HOME}/opt/cross/bin/i686-elf-gcc -CPP = ${HOME}/opt/cross/bin/i686-elf-g++ -CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -I source/CoreLib/build/include - -OFILES =$(BUILD_DIR)/boot.o $(BUILD_DIR)/kterm.o $(BUILD_DIR)/kernel.o $(BUILD_DIR)/memory.o $(BUILD_DIR)/paging.o $(BUILD_DIR)/VFS.o $(BUILD_DIR)/pit.o $(BUILD_DIR)/time.o $(BUILD_DIR)/keyboard.o $(BUILD_DIR)/io.o $(BUILD_DIR)/processor.o $(BUILD_DIR)/gdtc.o $(BUILD_DIR)/idt.o $(BUILD_DIR)/pic.o $(BUILD_DIR)/sv-terminal.o $(BUILD_DIR)/prekernel.o $(BUILD_DIR)/KHeap.o $(BUILD_DIR)/pci.o $(BUILD_DIR)/pcidevice.o $(BUILD_DIR)/atapiDevice.o $(BUILD_DIR)/ataDevice.o $(BUILD_DIR)/rsdp.o $(BUILD_DIR)/acpi.o - -SRC_DIR = source -BUILD_DIR = build - -CRTBEGIN_OBJ = $(shell $(CC) $(CFLAGS) -print-file-name=crtbegin.o) -CRTEND_OBJ = $(shell $(CC) $(CFLAGS) -print-file-name=crtend.o) - -CRTI_OBJ = $(BUILD_DIR)/crti.o -CRTN_OBJ = $(BUILD_DIR)/crtn.o -OBJ_LINK_LIST = $(CRTI_OBJ) $(CRTBEGIN_OBJ) $(OFILES) $(CRTEND_OBJ) $(CRTN_OBJ) -INTERNAL_OBJS = $(CRTI_OBJ) $(OFILES) $(CRTN_OBJ) - - -all: clean build - -build: build_kernel iso - -clean_iso: - if [[ -a isodir/boot ]] ; then rm root/boot -rd ; fi - if [ -f build/barinkOS.iso ] ; then rm build/barinkOS.iso ; fi - -iso: clean_iso clean build - mkdir -p root/boot/grub - cp build/myos.bin root/boot/myos.bin - cp source/grub.cfg root/boot/grub/grub.cfg - grub-mkrescue -o build/barinkOS.iso root -run: all - virtualboxvm --startvm "BarinkOS_test" -debug: all - objcopy --only-keep-debug build/myos.bin kernel.sym - $(EMULATOR) -cdrom build/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -s -d int -no-shutdown -no-reboot -test: - $(EMULATOR) -kernel $(BUILD_DIR)/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-shutdown -no-reboot - -test_iso: - $(EMULATOR) -boot d -cdrom $(BUILD_DIR)/barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-reboot -no-shutdown -test_disk: all - sudo losetup /dev/loop9 build/disk.img - sudo mount /dev/loop9 /mnt - sudo cp build/myos.bin /mnt/boot/myos.bin - sudo umount /mnt - sudo losetup -d /dev/loop9 - - $(EMULATOR) -boot d -drive format=raw,file=build/disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo - - -build_kernel: $(OBJ_LINK_LIST) - $(CPP) -T $(SRC_DIR)/kernel/linker.ld -o $(BUILD_DIR)/myos.bin -ffreestanding -ggdb -Og -nostdlib $(OBJ_LINK_LIST) -lgcc -L source/CoreLib/build -lCoreLib - -build_x86_64: - $(AS) $(SRC_DIR)/cgc/x86_64/crti.s -o $(BUILD_DIR)/crti_64.o - $(AS) $(SRC_DIR)/cgc/x86_64/crtn.s -o $(BUILD_DIR)/crtn.o - -clean: - rm -f $(BUILD_DIR)/myos.bin $(INTERNAL_OBJS) - -# C++ definition -> Object files -$(BUILD_DIR)/kernel.o: - $(CPP) -c $(SRC_DIR)/kernel/kernel.cpp -o $(BUILD_DIR)/kernel.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/kterm.o: - $(CPP) -c $(SRC_DIR)/kernel/terminal/kterm.cpp -o $(BUILD_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/io.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/io/io.cpp -o $(BUILD_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/idt.o: - $(CPP) -c $(SRC_DIR)/kernel/interrupts/idt.cpp -o $(BUILD_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/gdtc.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/gdt/gdtc.cpp -o $(BUILD_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/pic.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/pic/pic.cpp -o $(BUILD_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/PhysicalMemoryManager.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/pci.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/pci/pci.cpp -o $(BUILD_DIR)/pci.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/pcidevice.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/pci/pciDevice.cpp -o $(BUILD_DIR)/pcidevice.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/atapiDevice.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/atapi/atapiDevice.cpp -o $(BUILD_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/ataDevice.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/ata/ataDevice.cpp -o $(BUILD_DIR)/ataDevice.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/rsdp.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/acpi/rsdp.cpp -o $(BUILD_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/acpi.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/acpi/acpi.cpp -o $(BUILD_DIR)/acpi.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/pit.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/pit/pit.cpp -o $(BUILD_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/VFS.o: - $(CPP) -c $(SRC_DIR)/kernel/vfs/VFS.cpp -o $(BUILD_DIR)/VFS.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/keyboard.o: - $(CPP) -c $(SRC_DIR)/kernel/drivers/ps-2/keyboard.cpp -o $(BUILD_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/time.o: - $(CPP) -c $(SRC_DIR)/kernel/time.cpp -o $(BUILD_DIR)/time.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/sv-terminal.o: - $(CPP) -c $(SRC_DIR)/kernel/supervisorterminal/superVisorTerminal.cpp -o $(BUILD_DIR)/sv-terminal.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/memory.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/PhysicalMemoryManager.cpp -o $(BUILD_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/paging.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/VirtualMemoryManager.cpp -o $(BUILD_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/KHeap.o: - $(CPP) -c $(SRC_DIR)/kernel/memory/KernelHeap.cpp -o $(BUILD_DIR)/KHeap.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/prekernel.o: - $(CPP) -c $(SRC_DIR)/kernel/prekernel/prekernel.cpp -o $(BUILD_DIR)/prekernel.o $(CFLAGS) -fno-exceptions -fno-rtti - -$(BUILD_DIR)/processor.o: - $(CPP) -c $(SRC_DIR)/kernel/i386/processor.cpp -o $(BUILD_DIR)/processor.o $(CFLAGS) -fno-exceptions -fno-rtti - -# Assembly -> Object files -$(BUILD_DIR)/boot.o: - $(AS) $(SRC_DIR)/kernel/boot/boot.s -o $(BUILD_DIR)/boot.o - -$(BUILD_DIR)/crti.o: - $(AS) $(SRC_DIR)/kernel/crti.s -o $(BUILD_DIR)/crti.o - -$(BUILD_DIR)/crtn.o: - $(AS) $(SRC_DIR)/kernel/crtn.s -o $(BUILD_DIR)/crtn.o diff --git a/kernel/Makefile b/kernel/Makefile new file mode 100644 index 0000000..96ccbb1 --- /dev/null +++ b/kernel/Makefile @@ -0,0 +1,125 @@ +EMULATOR = qemu-system-i386 +AS = ${HOME}/opt/cross/bin/i686-elf-as +CC = ${HOME}/opt/cross/bin/i686-elf-gcc +CPP = ${HOME}/opt/cross/bin/i686-elf-g++ +CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -I ../build/CoreLib/include +BUILD_DIR = ../build/kernel +OBJ_DIR = ../bin/kernel + +CRTBEGIN_OBJ = $(shell $(CC) $(CFLAGS) -print-file-name=crtbegin.o) +CRTEND_OBJ = $(shell $(CC) $(CFLAGS) -print-file-name=crtend.o) + +CRTI_OBJ = $(OBJ_DIR)/crti.o +CRTN_OBJ = $(OBJ_DIR)/crtn.o + +OFILES = $(OBJ_DIR)/boot.o \ + $(OBJ_DIR)/kterm.o \ + $(OBJ_DIR)/kernel.o \ + $(OBJ_DIR)/memory.o \ + $(OBJ_DIR)/paging.o \ + $(OBJ_DIR)/VFS.o \ + $(OBJ_DIR)/pit.o \ + $(OBJ_DIR)/time.o \ + $(OBJ_DIR)/keyboard.o \ + $(OBJ_DIR)/io.o \ + $(OBJ_DIR)/processor.o \ + $(OBJ_DIR)/gdtc.o \ + $(OBJ_DIR)/idt.o \ + $(OBJ_DIR)/pic.o \ + $(OBJ_DIR)/sv-terminal.o \ + $(OBJ_DIR)/prekernel.o \ + $(OBJ_DIR)/KHeap.o \ + $(OBJ_DIR)/pci.o \ + $(OBJ_DIR)/pcidevice.o \ + $(OBJ_DIR)/atapiDevice.o \ + $(OBJ_DIR)/ataDevice.o \ + $(OBJ_DIR)/rsdp.o \ + $(OBJ_DIR)/acpi.o + +OBJ_LINK_LIST = $(CRTI_OBJ) $(CRTBEGIN_OBJ) $(OFILES) $(CRTEND_OBJ) $(CRTN_OBJ) +INTERNAL_OBJS = $(CRTI_OBJ) $(OFILES) $(CRTN_OBJ) + +all: build + +build: $(OBJ_LINK_LIST) + $(CPP) -T linker.ld -o $(BUILD_DIR)/myos.bin -ffreestanding -ggdb -Og -nostdlib $(OBJ_LINK_LIST) -lgcc -L ../build/CoreLib -lCoreLib + +# C++ definition -> Object files +$(OBJ_DIR)/kernel.o: + $(CPP) -c kernel.cpp -o $(OBJ_DIR)/kernel.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/kterm.o: + $(CPP) -c terminal/kterm.cpp -o $(OBJ_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/io.o: + $(CPP) -c drivers/io/io.cpp -o $(OBJ_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/idt.o: + $(CPP) -c interrupts/idt.cpp -o $(OBJ_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/gdtc.o: + $(CPP) -c memory/gdt/gdtc.cpp -o $(OBJ_DIR)/gdtc.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/pic.o: + $(CPP) -c drivers/pic/pic.cpp -o $(OBJ_DIR)/pic.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/PhysicalMemoryManager.o: + $(CPP) -c memory/PhysicalMemoryManager.cpp -o $(OBJ_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/pci.o: + $(CPP) -c drivers/pci/pci.cpp -o $(OBJ_DIR)/pci.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/pcidevice.o: + $(CPP) -c drivers/pci/pciDevice.cpp -o $(OBJ_DIR)/pcidevice.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/atapiDevice.o: + $(CPP) -c drivers/atapi/atapiDevice.cpp -o $(OBJ_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/ataDevice.o: + $(CPP) -c drivers/ata/ataDevice.cpp -o $(OBJ_DIR)/ataDevice.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/rsdp.o: + $(CPP) -c drivers/acpi/rsdp.cpp -o $(OBJ_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/acpi.o: + $(CPP) -c drivers/acpi/acpi.cpp -o $(OBJ_DIR)/acpi.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/pit.o: + $(CPP) -c drivers/pit/pit.cpp -o $(OBJ_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/VFS.o: + $(CPP) -c vfs/VFS.cpp -o $(OBJ_DIR)/VFS.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/keyboard.o: + $(CPP) -c drivers/ps-2/keyboard.cpp -o $(OBJ_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/time.o: + $(CPP) -c time.cpp -o $(OBJ_DIR)/time.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/sv-terminal.o: + $(CPP) -c supervisorterminal/superVisorTerminal.cpp -o $(OBJ_DIR)/sv-terminal.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/memory.o: + $(CPP) -c memory/PhysicalMemoryManager.cpp -o $(OBJ_DIR)/memory.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/paging.o: + $(CPP) -c memory/VirtualMemoryManager.cpp -o $(OBJ_DIR)/paging.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/KHeap.o: + $(CPP) -c memory/KernelHeap.cpp -o $(OBJ_DIR)/KHeap.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/prekernel.o: + $(CPP) -c prekernel/prekernel.cpp -o $(OBJ_DIR)/prekernel.o $(CFLAGS) -fno-exceptions -fno-rtti + +$(OBJ_DIR)/processor.o: + $(CPP) -c i386/processor.cpp -o $(OBJ_DIR)/processor.o $(CFLAGS) -fno-exceptions -fno-rtti + +# Assembly -> Object files +$(OBJ_DIR)/boot.o: + $(AS) boot/boot.s -o $(OBJ_DIR)/boot.o + +$(OBJ_DIR)/crti.o: + $(AS) crti.s -o $(OBJ_DIR)/crti.o + +$(OBJ_DIR)/crtn.o: + $(AS) crtn.s -o $(OBJ_DIR)/crtn.o diff --git a/source/kernel/bitmap.h b/kernel/bitmap.h similarity index 100% rename from source/kernel/bitmap.h rename to kernel/bitmap.h diff --git a/source/kernel/boot/boot.s b/kernel/boot/boot.s similarity index 92% rename from source/kernel/boot/boot.s rename to kernel/boot/boot.s index ca822c4..b45b3a8 100644 --- a/source/kernel/boot/boot.s +++ b/kernel/boot/boot.s @@ -1,4 +1,4 @@ -.include "./source/kernel/boot/multiboot.s" +.include "./boot/multiboot.s" /* * Allocate initial stack */ @@ -108,10 +108,10 @@ isPaging: jmp 1b -.include "./source/kernel/memory/gdt/gdt.s" -.include "./source/kernel/irs_table.s" -.include "./source/kernel/irq_table.s" -.include "./source/kernel/interrupts/idt.s" +.include "./memory/gdt/gdt.s" +.include "./irs_table.s" +.include "./irq_table.s" +.include "./interrupts/idt.s" .globl jump_usermode jump_usermode: diff --git a/source/kernel/boot/multiboot.s b/kernel/boot/multiboot.s similarity index 100% rename from source/kernel/boot/multiboot.s rename to kernel/boot/multiboot.s diff --git a/source/kernel/bootcheck.h b/kernel/bootcheck.h similarity index 100% rename from source/kernel/bootcheck.h rename to kernel/bootcheck.h diff --git a/source/kernel/bootinfo.h b/kernel/bootinfo.h similarity index 100% rename from source/kernel/bootinfo.h rename to kernel/bootinfo.h diff --git a/source/kernel/crti.s b/kernel/crti.s similarity index 100% rename from source/kernel/crti.s rename to kernel/crti.s diff --git a/source/kernel/crtn.s b/kernel/crtn.s similarity index 100% rename from source/kernel/crtn.s rename to kernel/crtn.s diff --git a/source/kernel/definitions.h b/kernel/definitions.h similarity index 100% rename from source/kernel/definitions.h rename to kernel/definitions.h diff --git a/source/kernel/drivers/acpi/acpi.cpp b/kernel/drivers/acpi/acpi.cpp similarity index 100% rename from source/kernel/drivers/acpi/acpi.cpp rename to kernel/drivers/acpi/acpi.cpp diff --git a/source/kernel/drivers/acpi/acpi.h b/kernel/drivers/acpi/acpi.h similarity index 100% rename from source/kernel/drivers/acpi/acpi.h rename to kernel/drivers/acpi/acpi.h diff --git a/source/kernel/drivers/acpi/rsdp.cpp b/kernel/drivers/acpi/rsdp.cpp similarity index 100% rename from source/kernel/drivers/acpi/rsdp.cpp rename to kernel/drivers/acpi/rsdp.cpp diff --git a/source/kernel/drivers/acpi/rsdp.h b/kernel/drivers/acpi/rsdp.h similarity index 100% rename from source/kernel/drivers/acpi/rsdp.h rename to kernel/drivers/acpi/rsdp.h diff --git a/source/kernel/drivers/ata/ataDevice.cpp b/kernel/drivers/ata/ataDevice.cpp similarity index 100% rename from source/kernel/drivers/ata/ataDevice.cpp rename to kernel/drivers/ata/ataDevice.cpp diff --git a/source/kernel/drivers/ata/ataDevice.h b/kernel/drivers/ata/ataDevice.h similarity index 100% rename from source/kernel/drivers/ata/ataDevice.h rename to kernel/drivers/ata/ataDevice.h diff --git a/source/kernel/drivers/atapi/atapiDevice.cpp b/kernel/drivers/atapi/atapiDevice.cpp similarity index 100% rename from source/kernel/drivers/atapi/atapiDevice.cpp rename to kernel/drivers/atapi/atapiDevice.cpp diff --git a/source/kernel/drivers/atapi/atapiDevice.h b/kernel/drivers/atapi/atapiDevice.h similarity index 100% rename from source/kernel/drivers/atapi/atapiDevice.h rename to kernel/drivers/atapi/atapiDevice.h diff --git a/source/kernel/drivers/cmos/cmos.cpp b/kernel/drivers/cmos/cmos.cpp similarity index 100% rename from source/kernel/drivers/cmos/cmos.cpp rename to kernel/drivers/cmos/cmos.cpp diff --git a/source/kernel/drivers/ide/ide.h b/kernel/drivers/ide/ide.h similarity index 100% rename from source/kernel/drivers/ide/ide.h rename to kernel/drivers/ide/ide.h diff --git a/source/kernel/drivers/ide/ideCommands.h b/kernel/drivers/ide/ideCommands.h similarity index 100% rename from source/kernel/drivers/ide/ideCommands.h rename to kernel/drivers/ide/ideCommands.h diff --git a/source/kernel/drivers/ide/sampleIDE.definitions.h b/kernel/drivers/ide/sampleIDE.definitions.h similarity index 100% rename from source/kernel/drivers/ide/sampleIDE.definitions.h rename to kernel/drivers/ide/sampleIDE.definitions.h diff --git a/source/kernel/drivers/ide/sampleIDE.h b/kernel/drivers/ide/sampleIDE.h similarity index 100% rename from source/kernel/drivers/ide/sampleIDE.h rename to kernel/drivers/ide/sampleIDE.h diff --git a/source/kernel/drivers/io/io.cpp b/kernel/drivers/io/io.cpp similarity index 100% rename from source/kernel/drivers/io/io.cpp rename to kernel/drivers/io/io.cpp diff --git a/source/kernel/drivers/io/io.h b/kernel/drivers/io/io.h similarity index 100% rename from source/kernel/drivers/io/io.h rename to kernel/drivers/io/io.h diff --git a/source/kernel/drivers/pci/pci.cpp b/kernel/drivers/pci/pci.cpp similarity index 100% rename from source/kernel/drivers/pci/pci.cpp rename to kernel/drivers/pci/pci.cpp diff --git a/source/kernel/drivers/pci/pci.h b/kernel/drivers/pci/pci.h similarity index 100% rename from source/kernel/drivers/pci/pci.h rename to kernel/drivers/pci/pci.h diff --git a/source/kernel/drivers/pci/pciDevice.cpp b/kernel/drivers/pci/pciDevice.cpp similarity index 100% rename from source/kernel/drivers/pci/pciDevice.cpp rename to kernel/drivers/pci/pciDevice.cpp diff --git a/source/kernel/drivers/pci/pciDevice.h b/kernel/drivers/pci/pciDevice.h similarity index 100% rename from source/kernel/drivers/pci/pciDevice.h rename to kernel/drivers/pci/pciDevice.h diff --git a/source/kernel/drivers/pic/pic.cpp b/kernel/drivers/pic/pic.cpp similarity index 100% rename from source/kernel/drivers/pic/pic.cpp rename to kernel/drivers/pic/pic.cpp diff --git a/source/kernel/drivers/pic/pic.h b/kernel/drivers/pic/pic.h similarity index 100% rename from source/kernel/drivers/pic/pic.h rename to kernel/drivers/pic/pic.h diff --git a/source/kernel/drivers/pit/pit.cpp b/kernel/drivers/pit/pit.cpp similarity index 100% rename from source/kernel/drivers/pit/pit.cpp rename to kernel/drivers/pit/pit.cpp diff --git a/source/kernel/drivers/pit/pit.h b/kernel/drivers/pit/pit.h similarity index 100% rename from source/kernel/drivers/pit/pit.h rename to kernel/drivers/pit/pit.h diff --git a/source/kernel/drivers/ps-2/keyboard.cpp b/kernel/drivers/ps-2/keyboard.cpp similarity index 100% rename from source/kernel/drivers/ps-2/keyboard.cpp rename to kernel/drivers/ps-2/keyboard.cpp diff --git a/source/kernel/drivers/ps-2/keyboard.h b/kernel/drivers/ps-2/keyboard.h similarity index 100% rename from source/kernel/drivers/ps-2/keyboard.h rename to kernel/drivers/ps-2/keyboard.h diff --git a/source/kernel/drivers/ps-2/scancodes/set1.h b/kernel/drivers/ps-2/scancodes/set1.h similarity index 100% rename from source/kernel/drivers/ps-2/scancodes/set1.h rename to kernel/drivers/ps-2/scancodes/set1.h diff --git a/source/kernel/drivers/serial/serial.cpp b/kernel/drivers/serial/serial.cpp similarity index 100% rename from source/kernel/drivers/serial/serial.cpp rename to kernel/drivers/serial/serial.cpp diff --git a/source/kernel/drivers/serial/serial.h b/kernel/drivers/serial/serial.h similarity index 100% rename from source/kernel/drivers/serial/serial.h rename to kernel/drivers/serial/serial.h diff --git a/source/kernel/drivers/vga/VBE.h b/kernel/drivers/vga/VBE.h similarity index 100% rename from source/kernel/drivers/vga/VBE.h rename to kernel/drivers/vga/VBE.h diff --git a/source/kernel/drivers/vga/colors.h b/kernel/drivers/vga/colors.h similarity index 100% rename from source/kernel/drivers/vga/colors.h rename to kernel/drivers/vga/colors.h diff --git a/source/kernel/filesystem/EXT2/SuperBlock.h b/kernel/filesystem/EXT2/SuperBlock.h similarity index 100% rename from source/kernel/filesystem/EXT2/SuperBlock.h rename to kernel/filesystem/EXT2/SuperBlock.h diff --git a/source/kernel/filesystem/FAT/BiosParameterBlock.h b/kernel/filesystem/FAT/BiosParameterBlock.h similarity index 100% rename from source/kernel/filesystem/FAT/BiosParameterBlock.h rename to kernel/filesystem/FAT/BiosParameterBlock.h diff --git a/source/kernel/filesystem/FAT/DirectoryEntry.h b/kernel/filesystem/FAT/DirectoryEntry.h similarity index 100% rename from source/kernel/filesystem/FAT/DirectoryEntry.h rename to kernel/filesystem/FAT/DirectoryEntry.h diff --git a/source/kernel/filesystem/FAT/ExtendBootRecord.h b/kernel/filesystem/FAT/ExtendBootRecord.h similarity index 100% rename from source/kernel/filesystem/FAT/ExtendBootRecord.h rename to kernel/filesystem/FAT/ExtendBootRecord.h diff --git a/source/grub.cfg b/kernel/grub.cfg similarity index 100% rename from source/grub.cfg rename to kernel/grub.cfg diff --git a/source/kernel/i386/README.md b/kernel/i386/README.md similarity index 100% rename from source/kernel/i386/README.md rename to kernel/i386/README.md diff --git a/source/kernel/i386/processor.cpp b/kernel/i386/processor.cpp similarity index 100% rename from source/kernel/i386/processor.cpp rename to kernel/i386/processor.cpp diff --git a/source/kernel/i386/processor.h b/kernel/i386/processor.h similarity index 100% rename from source/kernel/i386/processor.h rename to kernel/i386/processor.h diff --git a/source/kernel/interrupts/idt.cpp b/kernel/interrupts/idt.cpp similarity index 100% rename from source/kernel/interrupts/idt.cpp rename to kernel/interrupts/idt.cpp diff --git a/source/kernel/interrupts/idt.h b/kernel/interrupts/idt.h similarity index 100% rename from source/kernel/interrupts/idt.h rename to kernel/interrupts/idt.h diff --git a/source/kernel/interrupts/idt.s b/kernel/interrupts/idt.s similarity index 100% rename from source/kernel/interrupts/idt.s rename to kernel/interrupts/idt.s diff --git a/source/kernel/irq_table.s b/kernel/irq_table.s similarity index 100% rename from source/kernel/irq_table.s rename to kernel/irq_table.s diff --git a/source/kernel/irs_table.s b/kernel/irs_table.s similarity index 100% rename from source/kernel/irs_table.s rename to kernel/irs_table.s diff --git a/source/kernel/kernel.cpp b/kernel/kernel.cpp similarity index 100% rename from source/kernel/kernel.cpp rename to kernel/kernel.cpp diff --git a/source/kernel/kernel.h b/kernel/kernel.h similarity index 100% rename from source/kernel/kernel.h rename to kernel/kernel.h diff --git a/source/kernel/linker.ld b/kernel/linker.ld similarity index 100% rename from source/kernel/linker.ld rename to kernel/linker.ld diff --git a/source/kernel/memory/KernelHeap.cpp b/kernel/memory/KernelHeap.cpp similarity index 100% rename from source/kernel/memory/KernelHeap.cpp rename to kernel/memory/KernelHeap.cpp diff --git a/source/kernel/memory/KernelHeap.h b/kernel/memory/KernelHeap.h similarity index 100% rename from source/kernel/memory/KernelHeap.h rename to kernel/memory/KernelHeap.h diff --git a/source/kernel/memory/PageDirectory.cpp b/kernel/memory/PageDirectory.cpp similarity index 100% rename from source/kernel/memory/PageDirectory.cpp rename to kernel/memory/PageDirectory.cpp diff --git a/source/kernel/memory/PageDirectory.h b/kernel/memory/PageDirectory.h similarity index 100% rename from source/kernel/memory/PageDirectory.h rename to kernel/memory/PageDirectory.h diff --git a/source/kernel/memory/PhysicalMemoryManager.cpp b/kernel/memory/PhysicalMemoryManager.cpp similarity index 100% rename from source/kernel/memory/PhysicalMemoryManager.cpp rename to kernel/memory/PhysicalMemoryManager.cpp diff --git a/source/kernel/memory/PhysicalMemoryManager.h b/kernel/memory/PhysicalMemoryManager.h similarity index 100% rename from source/kernel/memory/PhysicalMemoryManager.h rename to kernel/memory/PhysicalMemoryManager.h diff --git a/source/kernel/memory/TaskStateSegment.h b/kernel/memory/TaskStateSegment.h similarity index 100% rename from source/kernel/memory/TaskStateSegment.h rename to kernel/memory/TaskStateSegment.h diff --git a/source/kernel/memory/VirtualMemoryManager.cpp b/kernel/memory/VirtualMemoryManager.cpp similarity index 100% rename from source/kernel/memory/VirtualMemoryManager.cpp rename to kernel/memory/VirtualMemoryManager.cpp diff --git a/source/kernel/memory/VirtualMemoryManager.h b/kernel/memory/VirtualMemoryManager.h similarity index 100% rename from source/kernel/memory/VirtualMemoryManager.h rename to kernel/memory/VirtualMemoryManager.h diff --git a/source/kernel/memory/gdt/gdt.s b/kernel/memory/gdt/gdt.s similarity index 100% rename from source/kernel/memory/gdt/gdt.s rename to kernel/memory/gdt/gdt.s diff --git a/source/kernel/memory/gdt/gdtc.cpp b/kernel/memory/gdt/gdtc.cpp similarity index 100% rename from source/kernel/memory/gdt/gdtc.cpp rename to kernel/memory/gdt/gdtc.cpp diff --git a/source/kernel/memory/gdt/gdtc.h b/kernel/memory/gdt/gdtc.h similarity index 100% rename from source/kernel/memory/gdt/gdtc.h rename to kernel/memory/gdt/gdtc.h diff --git a/source/kernel/memory/memory.cpp b/kernel/memory/memory.cpp similarity index 100% rename from source/kernel/memory/memory.cpp rename to kernel/memory/memory.cpp diff --git a/source/kernel/memory/memory.h b/kernel/memory/memory.h similarity index 100% rename from source/kernel/memory/memory.h rename to kernel/memory/memory.h diff --git a/source/kernel/memory/memoryinfo.h b/kernel/memory/memoryinfo.h similarity index 100% rename from source/kernel/memory/memoryinfo.h rename to kernel/memory/memoryinfo.h diff --git a/source/kernel/memory/paging.s b/kernel/memory/paging.s similarity index 100% rename from source/kernel/memory/paging.s rename to kernel/memory/paging.s diff --git a/source/kernel/partitiontable/mbr/MasterBootRecord.h b/kernel/partitiontable/mbr/MasterBootRecord.h similarity index 100% rename from source/kernel/partitiontable/mbr/MasterBootRecord.h rename to kernel/partitiontable/mbr/MasterBootRecord.h diff --git a/source/kernel/partitiontable/mbr/PartitionTableEntry.h b/kernel/partitiontable/mbr/PartitionTableEntry.h similarity index 100% rename from source/kernel/partitiontable/mbr/PartitionTableEntry.h rename to kernel/partitiontable/mbr/PartitionTableEntry.h diff --git a/source/kernel/prekernel/bootstructure.h b/kernel/prekernel/bootstructure.h similarity index 100% rename from source/kernel/prekernel/bootstructure.h rename to kernel/prekernel/bootstructure.h diff --git a/source/kernel/prekernel/multiboot.h b/kernel/prekernel/multiboot.h similarity index 100% rename from source/kernel/prekernel/multiboot.h rename to kernel/prekernel/multiboot.h diff --git a/source/kernel/prekernel/prekernel.cpp b/kernel/prekernel/prekernel.cpp similarity index 100% rename from source/kernel/prekernel/prekernel.cpp rename to kernel/prekernel/prekernel.cpp diff --git a/source/kernel/serial.h b/kernel/serial.h similarity index 100% rename from source/kernel/serial.h rename to kernel/serial.h diff --git a/source/kernel/supervisorterminal/superVisorTerminal.cpp b/kernel/supervisorterminal/superVisorTerminal.cpp similarity index 100% rename from source/kernel/supervisorterminal/superVisorTerminal.cpp rename to kernel/supervisorterminal/superVisorTerminal.cpp diff --git a/source/kernel/supervisorterminal/superVisorTerminal.h b/kernel/supervisorterminal/superVisorTerminal.h similarity index 100% rename from source/kernel/supervisorterminal/superVisorTerminal.h rename to kernel/supervisorterminal/superVisorTerminal.h diff --git a/source/kernel/terminal/kterm.cpp b/kernel/terminal/kterm.cpp similarity index 100% rename from source/kernel/terminal/kterm.cpp rename to kernel/terminal/kterm.cpp diff --git a/source/kernel/terminal/kterm.h b/kernel/terminal/kterm.h similarity index 96% rename from source/kernel/terminal/kterm.h rename to kernel/terminal/kterm.h index 8cce182..3207a47 100644 --- a/source/kernel/terminal/kterm.h +++ b/kernel/terminal/kterm.h @@ -5,7 +5,7 @@ #include "../drivers/vga/colors.h" #include "../drivers/io/io.h" -#include "CoreLib/Memory.h" +#include void kterm_init(); diff --git a/source/kernel/time.cpp b/kernel/time.cpp similarity index 100% rename from source/kernel/time.cpp rename to kernel/time.cpp diff --git a/source/kernel/time.h b/kernel/time.h similarity index 100% rename from source/kernel/time.h rename to kernel/time.h diff --git a/source/kernel/timer.cpp b/kernel/timer.cpp similarity index 100% rename from source/kernel/timer.cpp rename to kernel/timer.cpp diff --git a/source/kernel/timer.h b/kernel/timer.h similarity index 100% rename from source/kernel/timer.h rename to kernel/timer.h diff --git a/source/kernel/vfs/VFS.cpp b/kernel/vfs/VFS.cpp similarity index 100% rename from source/kernel/vfs/VFS.cpp rename to kernel/vfs/VFS.cpp diff --git a/source/kernel/vfs/VFS.h b/kernel/vfs/VFS.h similarity index 100% rename from source/kernel/vfs/VFS.h rename to kernel/vfs/VFS.h diff --git a/source/CoreLib/bin/memory.o b/source/CoreLib/bin/memory.o deleted file mode 100644 index 7b6893fc65737d96e5c0f55bb73064c293c0145a..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4712 zcmb_fYiv}<6`r~G&h^^6ek{9y!2}k93CMWYCKT3S5{#23yh#iM+!|*ech@WS#qM1b zsG&(nN~qhYNLAY(Ak-gKD^==4RR~d|0&=bZWGoHLJ|d-wB??)o(6oax4y$!0CaBJEz!dI_u9d=_R0&fOWAKH!@k z3rz3sxI!Iw?U$AqXRh&qo0Y$vduw{^AGc;edg|cF^lsnuDaC04;mmb@=FtEj_^{g9 zez_kJ+AnvV`*ZxAN@()kE0p)HkO4n)WPEJq%ExGTKR_g8^YWO8@$8_%YJVTo8BY18 zYk}!8m4pZbzpT!0zZ__4zZ|yXZ%>6z-~CUapEVd0j9WB^mT%#)oHRc@&~AHxez6L* zNw@L#!U4Fs)wGqsC;mhbum(Zk9abJzAWSZ9KTa+~EFs{&b#OLKP><2{B!RE#Wk9PX zaz&ToJqOD&LGBUz@q8ZUS;#PiU-&1U;y4~XU8GWm0J)~f)l06;kOv`Vu~uL`n|h%p zA)^pq2oEF2*0xd5a}dhKnB9UrD3pdbQD$ouwEKNAs5HI=>4fkLBk-72x5Dn1>Awr- zw;@K}DYBIT;=T@%TVyps3kp9*P_}N!4hX;SE<9~69z3{+bmKe|CxF2ovfc#e7DSdG zj8n*WAU}r~sVWO~y$8}?VZARsE(=Q!Rm~wjS`AEbp`7A8cxY~z;_m?MHqFFx$ZpEO zF=bGnR~)}UmRZK+?D?dw1z|Nrw1HtSrAg4{#v!sedo2~W8|HRMb1RG>1j&6e`53&1 zsfRYngme&}w{)IH@T2I+LC}JhO~--pmCWyd$ZsN@v7VW}P0RUa|A2pc$XNL5wuJ~G z{*BX$@`o3hZHilL+a3z?dG^-MlZ!YuTVROptH-h1nSZ&p9onF-^(&zdNqdfIKPA53P&OZ*9Dz$(!=Ivdoe6H()zMfM{pJSGad z0JfNhE$&8s$z&@r&|2ATxLA8Mi-jpqxEpb0p4Kph3P%utGb_Bf={&Q`Y{ezE1Z`y}a(O6w)n)iv)DA#~q|lsoJ_I!&kGha-^) z64j!I3UbH!R(#>4ckLwPH1w zEjsB)Y9di#`BE_(sk`WnQJpAN+_^49uR1OpAJ61V3AcY;oC5aKW8G{x8Y`pS8}hL| z2O`5gJ^dRa{r%DYXkVna;MR)HmaJ2BD!CNQL?tz`rR)^lT&+;9lp?*^Y&sd~-J6Z{ zW-=AWsk(_`I#QT% z9oD!en&n08oR4SI+ z5Z}=2v0rn8?aEe!k=y?g^9Y+6TcD6?A5Mt_U2*Hag98^g6 zHTmVY8Sn{Z(`%IcV+zv>k19N_@U+4&DLk+6>k2OsqK@w=o4yUX@Lmdp*OmWG<^P$& zUn~5r!uJTVr5`B!Lxnb$mFnzJxIp1jLgd{@h&-DW?ohZ#A$?-g_)&#PLX116>}M5z zkq~iSR(Mh2Hx+(g;g1wvS9n9=Z9>%l3uXUG;U5T*|1SzZB1HZ$gz|MNypIsP2bA5T zaFfD^6b=(Y_AC34!ZGE~5F*Yo<*zBEUkk^VNCzQ&D+qC(Rw?XL_$h^(6h1--egud& z93z|1RrpnfELuHLa1%+OTk&v0Yp(N*%cAma7fn{HELw5$(X^ASWyf>HObK05Pb8BS zXHr}FQYxRTx^vixN}`x`;PM7kirIT8`CQS_{m8FXa*s`o{)a$CLL)gZ~(U9M_%jYxPKjPW0d7Y)42@ zP4h-!H`a%1SDs0#kLsct2@4QC1}gJm!IzSvn(liJw$`a@6?j7p4y~R-Ut``5nyK6GU{0)$DLzO(@Q!IT(p|UgE~DmulH%WqxT6}oaHdb$0? z?B~H99Uq&yz5GfeI{x;1b8~Z-U%xy%^W*kg{+U~H=5}bzkwUUH)wn$~E02!N4b3$| z$`+13WBvX3V-qKSWC;42x!vjNemeUFzYwO71_zJ5ho*O1X< zc5MRqjo?d!ka+?cf7JK|q20IvVf%;Cg!ZE`d`4&^6idkX0_IwPd>qYFB(_20+kr-O zD1Fd83r5N>Lh_BK!59t9cW4{x_%!HaAa4L)LsdRRxNg^kujR{7(A{sLc(bWAb0B?@ zmX8DWK>IE*0Ca}$11B7lXgk;7AXKYS*VE)A8lN(WKTonPqQdowz#}j_e#X+IH;oRjxTbL{aa0gSwcSuU_(~t4l(*g=szj?tau@0u8rga0m_e zRqy~B3;soqVU{YkNcVyB9+*__&~4R z+MSO}=mPhue!;!s6Y?VXkWcz!k%(hUgRtrxQi9&ay<1G-`sF~8Ru8)|f)uHD0&Gpn zJ@L)Gk}>4tOJql2c=?5Hju2ZS?}^1D{+^XR6t{Qb5?SVPgw@;v78k_AJO(0e5*>Fc zu1JhR@9~8(4Irw{c1#lEUAhX%GtOmqI>^Tp5%%vwe-^*OTDkTv^jS&v@ckPrzqpK3|nPEAYK%5-2mNHg$?xk2HK8CIAw!^g}Pkez`o zW(V;FSe-SKARpXn%2(`U!i)zFDB}XGq$y{7K7=&!$icxw8M~NH7c4uQsauuIl(p-O zsFyBS6SkmAz-DO7u9Yf<(ZOAZa^xSC59*d6^$&sBBdVb`eoHKF3SeSz#ATby2QX3W-LgUMf_q ze1aFw#KdH|nz7RZ8|hD_f*^HtVjAI3INrp9ZneLgtmc&L!PHAMFQ_ zBEnbUs)nI@CfJiZqCGq|F(3RuGkC^W_gHGDZkpaP=$^ScBj&4(Y}sN@Z%m_U*Yl}U zLeI%!ljh99Bvq_VS*c2?V3kvQGr7}9Gquw?W0kAZQ<#y|jto}u^uuGRdbLr@S*g)# z%{oxZsx6buO;7*d4!i?br|nd(R;|}lIs=dY6uio9?b&$N(S88r-kuXq8l zvhbTFMq;5)`gXLM`+fooA=W{(71jOTHubxo@_)*hF(02Dd2QtN5oJt27{B=`Z`vMk zd_lFKVEAS+#9!u`42Xp2*Od5?QH$o7cLy#sJ`z}5 zz8|!kH}!j!)@k_AcytkedJ)f;u=}iG|K}Fz=a<+$0;BVXr73Fe^5&6Re6_(;-w*Q_ z&AiOLi~i%$aYvdzj@p|RI3EeTs`za3VRASRK1@uWh>76L^LGa4O=4L(h!8H*xPpj# ze+@B!_csxCNsZiJ#=mL&m&Q19r+$UT2Q(hkcuM10jh8e&qwzWs z^@p0jsrffF{#ncaLBuinr^ffSJdDRD<*gc5YV6UtmI&KEjYAqgN<`cljWvxIwEij) zexKEdr4FpQ}#stKtl56(=TZc!wbH|FQ6=9JY_(oU-uutM_4s=}=`Q z+A!*{;)Hk`=QIIYok1Xur8=MY0O=3QqY8hddJAu(bRA99oQ=ni^lkfMqS`UnYKTpwBRE=|=e>=Gn&adnS@ z_r}-W=Imd_N4YzH4bW~Mkm61FdzpkTuI^*tz5WvLw-++{;}^;G_XKG6;ry^XtM3Pg zb9B@{gX*=r4(ES#jkJ#XYm4lj!^aK3gPMgltS@SGr}kU0d$MWe#7FjPsNOt^$bOAynca(-Jsu0hLI!-4@EH0sh^9`I=ipAV6kVRg zICEd9NvG~3&T*FIDGhSlfk^nY*LRDo6cM_9Ca{}?03F|dV0GH*TCZcCvdO#eslv~4 z=T>lv&r}8>WhvHqVk(Ir5}Z*W18~Bkpc2C}9?lYurY6*ssy$r!C`;AGo9p)$7euHX z4>h^|*W1s`{+F7o?BTBH{D`!VyV3LXIQZ}0d(Aa9sJK`2kv>y9`nopUf_$4~LNQ8x zoelRz{+wjOa4H{|CgpDuBOQ}eze+mQ-n^A8{E}*_(4pq2I3w+HOY#GCpu=!~^A=-L diff --git a/source/CoreLib/bin/string.o b/source/CoreLib/bin/string.o deleted file mode 100644 index 482fce0ad4b555babe51f8a5a91c4429992ea669..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 4400 zcmb_fU2Ggj9iQ3T-8=iv=d;hBv0I<3#MlJi#m2aaW4Cr(CoyT#5-TB1xY+lx_d(Bh z*S)=vgpU-tpIjoyLmw)cf`mY=D53=k5LAG015~I8Bp%8O5)y?<i+4>XdYtv`p(zV+_y+qbt~ zjU0Nz?r4~u-_ZwdSpU3mF}dTq|4qe>G*&{;YRR1+YK$3->lD8Iml#Hg3ete~2^XL@ zidcXU`+nVj2x6}LuM-4}321mow+SNp%Mga*7&_jELD%%a-B5&y(M-b+;Ge?qB=Pgm z_>N*=okH(7$d>ajLh^jm;G<+dTh3sfmI>my?X9zUol;8qapyrzYIf8)yCWKLxy6iB6GTa+_8DkF0 zE;87D9bAAaN1LJDWIe^~Wybf8QHI)0of)*|Ve^mB&Vovy^X&+BSU4@YPQAiuc$A#F z(L?BcAI3n2%%HkQ!V{neK;4PXw@-rWr+F#Fe&9azfgF!>E4`b%Vo)`8Bq+sF+|Z@VrK=a%nf z!QeeXA7<1Hwi=xo#GVm>nvV%E;`~^2Zj>Jm9tvioUA)^|9Jo5jVPMAjy@S5++^9yn za(Fd5J<8_?vr$s|J6Uj4r#JzF`JkH_)KHT)gH1(=Xz$|t!qK2_WN3t9(&-8I!Ei1} z!N@Ok7%Vc^xGx+Gx^jvfmeUHua(FtZrtJJrMS~+}a*7CDz>OkOZMt=Jc&0rVoW^t7 z9YIwnho~%1fUzDdL;A0Z74+^B^ndpVme6;ceVSi`V}Eneu3})u>+Q-0MP)@HU%$$kZb8=M(pj((FHz6GQ0aihn)2ee@>7$G2k$ea>vy~k)XBZhGvkTBXI z>o*S@VZu19KW=a{I&V%3+iw`dgx@z$iWt3dgP+J5kvohj^GPT;V)p{?JZJE_rXkl_ z@v61%u=Vq&X4f3MSk5octUQ<@{)7}1FRyGeSI4qersQ0yTI1z{Q0F z>>8_7Ej#5@>)iPg)sV!mu;V-$fog<_4BD&>5vDW|KeR;bv{ zZqfRBu2e}mQ_}}qA;?sOIduSQ}L1#6I z-3A}T8wKlax(Xs&si#X8^OnG^jAx!*m2fv8o~c$@qEOki66IpvDkYAmG7lr$#C_H! zt5m6OVqu9RDeU9J53D6>mAaj=63Z3ay1$tIzxY+EP9kGhYPCeEm`>y~nM85+;OwMT z$|c;2CyM1vsh+jui4h5Va+hR*)tqeB%Eb$e9a~S?^;1AHi? z>rdgyqQ{atHM+vtQaJFqcBI2ty#)(bHxIFTVKnteU40C?kD;r#QB%LP<$LJXj)*Z1 z{iEpWrPs7M@`P_o-)P@i`soryTf)Uixx9$3-l|R8lkR*_?P_#EsHU^O-c~f>?yoxH z4X+x!|2;fzVNdflKeSw-&#h3?!iTER>zNwWt{YdCx0b|z0CH73;^{@KYDN4Cz^oFBn2vFX35<7bF%WRwOJw4 zgy=&O-%p5nrwL&s8 z4@sPpc&|iyx07ECNVzXc+>rQ~#Fr$pccp|A^m#FLl*qq-&rkb+bhJa{g z_j}mkZ9u7jRi4#1x|kf(%j@v jc4SYqI#VFoi}=&45+NJKq1J`&wVT1b-xeBoPz6D4^ROQv=R~$Ra=R^Q6Z3!B7u+qA@Kr;z90eLH+ROq z_5<+1k!HU0H|Lx=b7#E1y>jW3Qc7V+iiFsagt+fSmZJ&|iz!hMt9O6DwUXId&ECy# zt>*7uNp7u9-Mx}|@txORwuG>SOwu`9M4S@2aZaH95eO@3zX5h^3RCif=@S4eneGrW zHfCXElT%o1<&zg7<>oMDUci*Jl9@#qMkrXRFJa!qxPu{|fIhK=NsKFN+Wsfi@^#GL z-gbDF4)*hyGLvs(z6SXxz;`fI2r)Vc17ZCRGK2jZ_?vB;{U%sv^ac!1V|+*hFv>j- zNhptO{&i?CV9a2AgdS^{63Qdbimh=+m1>F98pNcU7}AodO+bqLgi@n3zoZNIo%tKM zY$Bch0Ky~}i4m$2Be$WrgYk6?No#`E1h=QAXj_Tbpk(47V7!T;Tty*A-|Qs4lT)tW z5{WS-WJIzCU5Wu8QlYcyzk}Zof0Dd!;lTHeL-i{R>z)wP0T`K*1sKF>Of$yn@DvWR zET@6#D6`EnnM_?EFZMGSd-Oclf@U$~{WL=%^xOep9;z%x`jAp)(hCZqlD4>5IEp3K zqr!2XbQ0K9f;#MJTsWm9IlC;MnoZY}qWyCt2d-uzf>#c^j5H+3S9y>t2G0qo^CG=<$x zLQFxyI2*o(AIK`bTbz z!0(42o|Ffz^Wbk|Sm4L)AAu9^a{2|Q2b}(dA#Evam1sI8?S=M|Jy%|`k1W~Jvu9FI zrX+%O`+mEqCeIH=!)<%M7i?IO5qP%e5m1ie|4i?qL4a62B`_*eT5q7*m zl%~}mHoC4je|fdI{P^S5CyLc-xmsQ*&iBHh@1AbEz8iQ=i1nb^IlbZfp*QSp1pVTC zyWMIO=bvjA=hxQ**Tw$*7OUSW#Cv6>r}n>hyQm`8(Y4E;(vn)RQ+K(!u^}p*e$TD= zUfbw_z5vK}-=k`{2e{1oZt#1ncKp-D~>x>bxok=2;`!uo^i6`a}BDQ~o2*0vM_M7su z#%DBsTH|$%{5?ZIoVh|@h_ymZxHVCt_O9$?e0=_J>NA;kk7DG*Oc7s_xLJBN!?CuJ*f9w z6#YNa9Q@FF!Tyo>Tix6P%4mV25@!0L#fsRcIMGIW41?eHfAdr4!3CNa@AD=ZcoUEJ zbOhrJ25AYx6&NSL^OfLWK6M{}hTcc4@0lP_8dlvC;{+TcfO*@fHh!Op@zmdgUy+O^ ztkJ}zR!U-Yru*h!q6q7$=G_3J>+`&v7hA4Hw9KafFIAu5aW>8r?}srk@x$`5>3YM E-;p%>LI3~& -- 2.39.5 From 81f7351fe6d243770731d07bffa71c09b73d9800 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 20 Feb 2023 01:03:46 +0100 Subject: [PATCH 099/115] Created a few shell scripts to update and create an build of the Kernel/Operating System. A python script can be run to run the scripts in the correct order and immediatly try the build. --- kernel/Makefile | 1 - scripts/build.py | 23 +++++++++---------- ...eate-filesystem.sh => create_harddrive.sh} | 0 scripts/create_iso.sh | 5 ++++ scripts/create_symbol_lookup.sh | 3 +++ scripts/hooks/pre-commit.hook.sh | 3 --- scripts/run_qemu.sh | 12 ++++++++++ scripts/run_virtualbox.sh | 2 ++ scripts/test.sh | 5 ---- scripts/update_harddrive.sh | 11 +++++++++ 10 files changed, 44 insertions(+), 21 deletions(-) rename scripts/{create-filesystem.sh => create_harddrive.sh} (100%) create mode 100755 scripts/create_iso.sh create mode 100755 scripts/create_symbol_lookup.sh create mode 100755 scripts/run_qemu.sh create mode 100755 scripts/run_virtualbox.sh delete mode 100755 scripts/test.sh create mode 100755 scripts/update_harddrive.sh diff --git a/kernel/Makefile b/kernel/Makefile index 96ccbb1..97e6d43 100644 --- a/kernel/Makefile +++ b/kernel/Makefile @@ -1,4 +1,3 @@ -EMULATOR = qemu-system-i386 AS = ${HOME}/opt/cross/bin/i686-elf-as CC = ${HOME}/opt/cross/bin/i686-elf-gcc CPP = ${HOME}/opt/cross/bin/i686-elf-g++ diff --git a/scripts/build.py b/scripts/build.py index cd06dc4..8183b1a 100755 --- a/scripts/build.py +++ b/scripts/build.py @@ -2,24 +2,23 @@ import os import subprocess - -print("Building BarinkOS") - +print("Give BarinkOS A Test Run") # list and run build scripts print("Running build-scripts") os.chdir("scripts") - scripts=os.listdir() currentScript=os.path.basename(__file__) -if currentScript in scripts: - scripts.remove(currentScript) +os.chdir("../CoreLib") +print("Building CoreLib") +subprocess.call("make") +os.chdir("../kernel") +print("Building kernel") +subprocess.call("make") -for script in scripts: - print(os.getcwd()) - print("Running:" + script) - subprocess.call(script, cwd=os.getcwd()) - -os.chdir("..") \ No newline at end of file +os.chdir("..") +subprocess.call("scripts/update_harddrive.sh", cwd=os.getcwd()) +subprocess.call("scripts/create_symbol_lookup.sh", cwd=os.getcwd()) +subprocess.call("scripts/run_qemu.sh", cwd=os.getcwd()) \ No newline at end of file diff --git a/scripts/create-filesystem.sh b/scripts/create_harddrive.sh similarity index 100% rename from scripts/create-filesystem.sh rename to scripts/create_harddrive.sh diff --git a/scripts/create_iso.sh b/scripts/create_iso.sh new file mode 100755 index 0000000..356fdf3 --- /dev/null +++ b/scripts/create_iso.sh @@ -0,0 +1,5 @@ +#!/bin/bash +mkdir -p root/boot/grub +cp build/kernel/myos.bin root/boot/myos.bin +cp kernel/grub.cfg root/boot/grub/grub.cfg +grub-mkrescue -o barinkOS.iso root \ No newline at end of file diff --git a/scripts/create_symbol_lookup.sh b/scripts/create_symbol_lookup.sh new file mode 100755 index 0000000..a150d4a --- /dev/null +++ b/scripts/create_symbol_lookup.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +objcopy --only-keep-debug build/kernel/myos.bin kernel.sym \ No newline at end of file diff --git a/scripts/hooks/pre-commit.hook.sh b/scripts/hooks/pre-commit.hook.sh index 8a905bf..5bad261 100644 --- a/scripts/hooks/pre-commit.hook.sh +++ b/scripts/hooks/pre-commit.hook.sh @@ -1,5 +1,2 @@ #!/bin/bash - - # Run clang-tidy - diff --git a/scripts/run_qemu.sh b/scripts/run_qemu.sh new file mode 100755 index 0000000..072a4bd --- /dev/null +++ b/scripts/run_qemu.sh @@ -0,0 +1,12 @@ +#!/bin/bash + +# Run from harddisk +qemu-system-i386 -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo + +# Run disk version +# qemu-system-i386 -cdrom barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -s -d int -no-shutdown -no-reboot + +# Run the raw kernel image +# qemu-system-i386 -kernel build/kernel/myos.bin -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-shutdown -no-reboot + + diff --git a/scripts/run_virtualbox.sh b/scripts/run_virtualbox.sh new file mode 100755 index 0000000..db37ed2 --- /dev/null +++ b/scripts/run_virtualbox.sh @@ -0,0 +1,2 @@ +#!/bin/bash +virtualboxvm --startvm "BarinkOS_test" \ No newline at end of file diff --git a/scripts/test.sh b/scripts/test.sh deleted file mode 100755 index cb84bbe..0000000 --- a/scripts/test.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash -start=`date +%s` -end=`date +%s` -echo That took $((end-start)) seconds -date +"%c" -d195440409 diff --git a/scripts/update_harddrive.sh b/scripts/update_harddrive.sh new file mode 100755 index 0000000..8295420 --- /dev/null +++ b/scripts/update_harddrive.sh @@ -0,0 +1,11 @@ +#!/bin/bash +echo "Mount harddrive image as block device" +sudo losetup /dev/loop9 disk.img +sudo mount /dev/loop9 /mnt + +echo "Copy over kernel binary" +sudo cp build/kernel/myos.bin /mnt/boot/myos.bin + +echo "unmount image" +sudo umount /mnt +sudo losetup -d /dev/loop9 \ No newline at end of file -- 2.39.5 From ef2bba5c1cd8ae5837148409211f27007a0fbb37 Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 21 Feb 2023 14:36:20 +0100 Subject: [PATCH 100/115] Started fleshing out the storage API --- CoreLib/Memory.cpp | 40 ++++ CoreLib/Memory.h | 4 +- kernel/Makefile | 20 +- kernel/acpi/acpi.cpp | 35 +++ kernel/{drivers => }/acpi/acpi.h | 2 +- kernel/{drivers => }/acpi/rsdp.cpp | 25 +- kernel/{drivers => }/acpi/rsdp.h | 18 +- kernel/devices/BlockDevice.h | 11 + kernel/devices/CharacterDevice.h | 11 + kernel/drivers/acpi/acpi.cpp | 15 -- kernel/drivers/ata/ataDevice.h | 27 --- kernel/drivers/pic/pic.h | 6 +- kernel/drivers/pit/pit.h | 4 +- kernel/filesystem/FAT/DirectoryEntry.h | 28 ++- .../{vfs/VFS.cpp => filesystem/FAT/FAT.cpp} | 202 ++-------------- kernel/filesystem/FAT/FAT.h | 41 ++++ kernel/{drivers => }/io/io.cpp | 0 kernel/{drivers => }/io/io.h | 0 kernel/kernel.cpp | 19 +- kernel/linker.ld | 3 + kernel/partitiontable/mbr/MasterBootRecord.h | 33 ++- kernel/{drivers => }/pci/pci.cpp | 0 kernel/{drivers => }/pci/pci.h | 2 +- kernel/{drivers => }/pci/pciDevice.cpp | 0 kernel/{drivers => }/pci/pciDevice.h | 0 kernel/prekernel/prekernel.cpp | 4 +- kernel/serial.h | 2 +- .../ata => storage/ata pio}/ataDevice.cpp | 223 +++++++++--------- kernel/storage/ata pio/ataDevice.h | 38 +++ .../atapi/atapiDevice.cpp | 0 .../{drivers => storage}/atapi/atapiDevice.h | 2 +- kernel/{drivers => storage}/ide/ide.h | 6 +- kernel/{drivers => storage}/ide/ideCommands.h | 0 .../ide/sampleIDE.definitions.h | 0 kernel/{drivers => storage}/ide/sampleIDE.h | 18 +- kernel/storage/vfs/FileSystem.cpp | 41 ++++ kernel/storage/vfs/FileSystem.h | 18 ++ kernel/storage/vfs/Inode.cpp | 5 + kernel/storage/vfs/Inode.h | 24 ++ kernel/storage/vfs/StorageTypes.h | 32 +++ kernel/storage/vfs/VFS.cpp | 54 +++++ kernel/storage/vfs/VFS.h | 17 ++ .../supervisorterminal/superVisorTerminal.cpp | 3 +- kernel/terminal/kterm.h | 4 +- kernel/time.h | 2 +- kernel/timer.h | 2 +- kernel/vfs/VFS.h | 80 ------- run.sh | 12 + scripts/update_harddrive.sh | 3 + 49 files changed, 661 insertions(+), 475 deletions(-) create mode 100644 kernel/acpi/acpi.cpp rename kernel/{drivers => }/acpi/acpi.h (85%) rename kernel/{drivers => }/acpi/rsdp.cpp (56%) rename kernel/{drivers => }/acpi/rsdp.h (69%) create mode 100644 kernel/devices/BlockDevice.h create mode 100644 kernel/devices/CharacterDevice.h delete mode 100644 kernel/drivers/acpi/acpi.cpp delete mode 100644 kernel/drivers/ata/ataDevice.h rename kernel/{vfs/VFS.cpp => filesystem/FAT/FAT.cpp} (62%) create mode 100644 kernel/filesystem/FAT/FAT.h rename kernel/{drivers => }/io/io.cpp (100%) rename kernel/{drivers => }/io/io.h (100%) rename kernel/{drivers => }/pci/pci.cpp (100%) rename kernel/{drivers => }/pci/pci.h (98%) rename kernel/{drivers => }/pci/pciDevice.cpp (100%) rename kernel/{drivers => }/pci/pciDevice.h (100%) rename kernel/{drivers/ata => storage/ata pio}/ataDevice.cpp (78%) create mode 100644 kernel/storage/ata pio/ataDevice.h rename kernel/{drivers => storage}/atapi/atapiDevice.cpp (100%) rename kernel/{drivers => storage}/atapi/atapiDevice.h (95%) rename kernel/{drivers => storage}/ide/ide.h (96%) rename kernel/{drivers => storage}/ide/ideCommands.h (100%) rename kernel/{drivers => storage}/ide/sampleIDE.definitions.h (100%) rename kernel/{drivers => storage}/ide/sampleIDE.h (96%) create mode 100644 kernel/storage/vfs/FileSystem.cpp create mode 100644 kernel/storage/vfs/FileSystem.h create mode 100644 kernel/storage/vfs/Inode.cpp create mode 100644 kernel/storage/vfs/Inode.h create mode 100644 kernel/storage/vfs/StorageTypes.h create mode 100644 kernel/storage/vfs/VFS.cpp create mode 100644 kernel/storage/vfs/VFS.h delete mode 100644 kernel/vfs/VFS.h create mode 100755 run.sh diff --git a/CoreLib/Memory.cpp b/CoreLib/Memory.cpp index fce2e66..830a346 100644 --- a/CoreLib/Memory.cpp +++ b/CoreLib/Memory.cpp @@ -55,4 +55,44 @@ int strncmp ( const char* str1, const char* str2, size_t num ){ } return 0; +} + +char* strchr(const char* s , int c){ + while(*s) { + if(*s == c) return const_cast(s); + s++; + } + return NULL; +} +char* strtok(char* str, const char* delim , char**saveptr){ + char *begin; + if(str) { + begin = str; + } + else if (*saveptr) { + begin = *saveptr; + } + else { + return NULL; + } + + while(strchr(delim, begin[0])) { + begin++; + } + + + char *next = NULL; + for(int i = 0; i < strlen(delim); i++) { + char *temp = strchr(begin, delim[i]); + if(temp < next || next == NULL) { + next = temp; + } + } + if(!next) { + *saveptr = NULL; + return begin; + } + *next = 0; + *saveptr=next+1; + return begin; } \ No newline at end of file diff --git a/CoreLib/Memory.h b/CoreLib/Memory.h index e31a5dc..a4cc9d5 100644 --- a/CoreLib/Memory.h +++ b/CoreLib/Memory.h @@ -9,4 +9,6 @@ int memcmp( const void* ptr1, const void* ptr2, size_t num); size_t strlen(const char* str); -int strncmp ( const char* str1, const char* str2, size_t num ); \ No newline at end of file +int strncmp ( const char* str1, const char* str2, size_t num ); + +char* strtok(char* str, const char* delim , char**saveptr); \ No newline at end of file diff --git a/kernel/Makefile b/kernel/Makefile index 97e6d43..923680f 100644 --- a/kernel/Makefile +++ b/kernel/Makefile @@ -40,6 +40,10 @@ INTERNAL_OBJS = $(CRTI_OBJ) $(OFILES) $(CRTN_OBJ) all: build +clean: + rm $(OBJ_DIR)/* -r + + build: $(OBJ_LINK_LIST) $(CPP) -T linker.ld -o $(BUILD_DIR)/myos.bin -ffreestanding -ggdb -Og -nostdlib $(OBJ_LINK_LIST) -lgcc -L ../build/CoreLib -lCoreLib @@ -51,7 +55,7 @@ $(OBJ_DIR)/kterm.o: $(CPP) -c terminal/kterm.cpp -o $(OBJ_DIR)/kterm.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/io.o: - $(CPP) -c drivers/io/io.cpp -o $(OBJ_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c io/io.cpp -o $(OBJ_DIR)/io.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/idt.o: $(CPP) -c interrupts/idt.cpp -o $(OBJ_DIR)/idt.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -66,28 +70,28 @@ $(OBJ_DIR)/PhysicalMemoryManager.o: $(CPP) -c memory/PhysicalMemoryManager.cpp -o $(OBJ_DIR)/PhysicalMemoryManager.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/pci.o: - $(CPP) -c drivers/pci/pci.cpp -o $(OBJ_DIR)/pci.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c pci/pci.cpp -o $(OBJ_DIR)/pci.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/pcidevice.o: - $(CPP) -c drivers/pci/pciDevice.cpp -o $(OBJ_DIR)/pcidevice.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c pci/pciDevice.cpp -o $(OBJ_DIR)/pcidevice.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/atapiDevice.o: - $(CPP) -c drivers/atapi/atapiDevice.cpp -o $(OBJ_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c storage/atapi/atapiDevice.cpp -o $(OBJ_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/ataDevice.o: - $(CPP) -c drivers/ata/ataDevice.cpp -o $(OBJ_DIR)/ataDevice.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c "storage/ata pio/ataDevice.cpp" -o $(OBJ_DIR)/ataDevice.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/rsdp.o: - $(CPP) -c drivers/acpi/rsdp.cpp -o $(OBJ_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c acpi/rsdp.cpp -o $(OBJ_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/acpi.o: - $(CPP) -c drivers/acpi/acpi.cpp -o $(OBJ_DIR)/acpi.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c acpi/acpi.cpp -o $(OBJ_DIR)/acpi.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/pit.o: $(CPP) -c drivers/pit/pit.cpp -o $(OBJ_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/VFS.o: - $(CPP) -c vfs/VFS.cpp -o $(OBJ_DIR)/VFS.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c storage/vfs/VFS.cpp -o $(OBJ_DIR)/VFS.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/keyboard.o: $(CPP) -c drivers/ps-2/keyboard.cpp -o $(OBJ_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti diff --git a/kernel/acpi/acpi.cpp b/kernel/acpi/acpi.cpp new file mode 100644 index 0000000..e904ae6 --- /dev/null +++ b/kernel/acpi/acpi.cpp @@ -0,0 +1,35 @@ +#include "acpi.h" +RSDPDescriptor* ACPI::rsd_ptr; +RSDT* ACPI::rsd_table; + + + +void ACPI::initialize(){ + + // Find the Root System Description Pointer + ACPI::rsd_ptr = FindRSD(); + + // is it valid + int sum = 0; + for (int i =0; i < 20 ; i++) { + sum += ((char*)rsd_ptr)[i]; + } + + printf(" 0x%x sum\n", sum); + return; + + // Get the Root System Description Table + RSDT* rootSystemDescriptionTable = getRSDT((RSDPDescriptor *) rsd_ptr); + + auto tableHeader = &rootSystemDescriptionTable->h; + + // do checksum + sum = 0; + + for(int i = 0; i < tableHeader->Length; i ++) { + sum += ((char*) tableHeader)[i]; + } + + if( sum != 0) + printf("Table invalid!"); +} \ No newline at end of file diff --git a/kernel/drivers/acpi/acpi.h b/kernel/acpi/acpi.h similarity index 85% rename from kernel/drivers/acpi/acpi.h rename to kernel/acpi/acpi.h index 66fe8d9..c2293d0 100644 --- a/kernel/drivers/acpi/acpi.h +++ b/kernel/acpi/acpi.h @@ -8,6 +8,6 @@ class ACPI { // doing more systems initialization private: - static RSDPTR* rsd_ptr; + static RSDPDescriptor* rsd_ptr; static RSDT* rsd_table; }; \ No newline at end of file diff --git a/kernel/drivers/acpi/rsdp.cpp b/kernel/acpi/rsdp.cpp similarity index 56% rename from kernel/drivers/acpi/rsdp.cpp rename to kernel/acpi/rsdp.cpp index 910fadb..f4408c2 100644 --- a/kernel/drivers/acpi/rsdp.cpp +++ b/kernel/acpi/rsdp.cpp @@ -1,6 +1,8 @@ #include "rsdp.h" +#include "../memory/VirtualMemoryManager.h" -void printRSD(RSDPTR* rsd){ + +void printRSD(RSDPDescriptor* rsd){ printf("Signature: "); for(int i = 0; i < 8; i++){ kterm_put(rsd->signature[i]); @@ -17,29 +19,22 @@ void printRSD(RSDPTR* rsd){ printf("RSDT Address: 0x%x\n", rsd->RsdtAddress ); } -RSDPTR* FindRSD(){ - char* memory_byte = (char*) 0xC00f2e14; +RSDPDescriptor* FindRSD(){ + char* memory_byte = (char*) 0x000f2e14; const void* string = "RSD PTR "; - for( ; (uint32_t) memory_byte < 0xC0100000; memory_byte+=10){ + for( ; (uint32_t) memory_byte < 0x00100000; memory_byte+=10){ if( memcmp(memory_byte , string , 8 ) == 0 ) { printf("RSD PTR found at 0x%x !\n", memory_byte); break; } } - - return (RSDPTR*) memory_byte; + return (RSDPDescriptor*) memory_byte; } -RSDT* getRSDT(RSDPTR* rsd){ +RSDT* getRSDT(RSDPDescriptor* rsd){ + printf("rsdt Address: 0x%x\n", rsd->RsdtAddress); + return (RSDT*)rsd->RsdtAddress ; - RSDT* rsdt = (RSDT*) rsd->RsdtAddress; - - printf("OEMID: "); - for(int i = 0; i < 6; i++){ - kterm_put(rsdt->header.OEMID[i]); - } - kterm_put('\n'); - return rsdt; } \ No newline at end of file diff --git a/kernel/drivers/acpi/rsdp.h b/kernel/acpi/rsdp.h similarity index 69% rename from kernel/drivers/acpi/rsdp.h rename to kernel/acpi/rsdp.h index 7d7aecb..4ae6899 100644 --- a/kernel/drivers/acpi/rsdp.h +++ b/kernel/acpi/rsdp.h @@ -1,9 +1,9 @@ #pragma once -#include -#include "./../../terminal/kterm.h" +#include "../terminal/kterm.h" #include +#include -struct RSDPTR { +struct RSDPDescriptor { char signature[8]; uint8_t Checksum ; char OEMID [6]; @@ -14,22 +14,22 @@ struct RSDPTR { struct ACPISDTHeader{ char Signature[4]; uint32_t Length; + uint8_t Revision; uint8_t CheckSum; char OEMID[6]; char OEMTableID[8]; uint32_t OEMRevision; uint32_t CreatorID; uint32_t CreatorRevision; -}__attribute__((packed)); +}; struct RSDT{ - struct ACPISDTHeader header; + struct ACPISDTHeader h; uint32_t PointerToSDT[]; // Length of array : (header.Length - sizeof(header))/ 4 }__attribute__((packed)); +RSDPDescriptor* FindRSD(); -RSDPTR* FindRSD(); +void printRSD(RSDPDescriptor* rsd); -void printRSD(RSDPTR* rsd); - -RSDT* getRSDT(RSDPTR* rsd); \ No newline at end of file +RSDT* getRSDT(RSDPDescriptor* rsd); \ No newline at end of file diff --git a/kernel/devices/BlockDevice.h b/kernel/devices/BlockDevice.h new file mode 100644 index 0000000..ed412fe --- /dev/null +++ b/kernel/devices/BlockDevice.h @@ -0,0 +1,11 @@ +// +// Created by nigel on 21/02/23. +// +#pragma once + +class BlockDevice { + virtual char* Read()=0; + virtual void Write() =0; +}; + + diff --git a/kernel/devices/CharacterDevice.h b/kernel/devices/CharacterDevice.h new file mode 100644 index 0000000..3afc094 --- /dev/null +++ b/kernel/devices/CharacterDevice.h @@ -0,0 +1,11 @@ +// +// Created by nigel on 21/02/23. +// +#pragma once + +class CharacterDevice { + virtual char Read()=0; + virtual void Write()=0; +}; + + diff --git a/kernel/drivers/acpi/acpi.cpp b/kernel/drivers/acpi/acpi.cpp deleted file mode 100644 index cf73c27..0000000 --- a/kernel/drivers/acpi/acpi.cpp +++ /dev/null @@ -1,15 +0,0 @@ -#include "acpi.h" -RSDPTR* ACPI::rsd_ptr; -RSDT* ACPI::rsd_table; - - - -void ACPI::initialize(){ - - // Find the Root System Description Pointer - ACPI::rsd_ptr = FindRSD(); - printRSD(rsd_ptr); - - // Get the Root System Description Table - ACPI::rsd_table = getRSDT((RSDPTR*)((uint32_t)rsd_ptr + 0xC00000000)); -} \ No newline at end of file diff --git a/kernel/drivers/ata/ataDevice.h b/kernel/drivers/ata/ataDevice.h deleted file mode 100644 index 30e75dc..0000000 --- a/kernel/drivers/ata/ataDevice.h +++ /dev/null @@ -1,27 +0,0 @@ -#pragma once -#include -#include "../io/io.h" -#include "../ide/ideCommands.h" -#include "../ide/sampleIDE.definitions.h" - -#include "../../terminal/kterm.h" - -/* -* This first driver wil make use of IO ports. -* Doing so means reading or writing from disk is going -* to be very cpu intensive. -*/ - -enum DEVICE_DRIVE{ - MASTER = 0xA0, - SLAVE = 0xB0 -}; - -namespace ATA_DEVICE{ - void Identify(uint16_t, DEVICE_DRIVE); - void Read (uint16_t, DEVICE_DRIVE, uint32_t, uint16_t*); - void Write(uint16_t, DEVICE_DRIVE); - void Soft_Reset(uint8_t ,DEVICE_DRIVE ); -}; - - diff --git a/kernel/drivers/pic/pic.h b/kernel/drivers/pic/pic.h index 6788013..aeb6e30 100644 --- a/kernel/drivers/pic/pic.h +++ b/kernel/drivers/pic/pic.h @@ -1,5 +1,7 @@ -#pragma once -#include "../io/io.h" +#pragma once + +#include +#include "../../io/io.h" #define PIC1 0x20 /* IO base address for master PIC */ #define PIC2 0xA0 /* IO base address for slave PIC */ diff --git a/kernel/drivers/pit/pit.h b/kernel/drivers/pit/pit.h index ad9235d..cde7444 100644 --- a/kernel/drivers/pit/pit.h +++ b/kernel/drivers/pit/pit.h @@ -1,6 +1,6 @@ #pragma once -#include -#include "../io/io.h" +#include +#include "../../io/io.h" #define PIT_DATA_0 0x40 #define PIT_DATA_1 0x41 #define PIT_DATA_2 0x42 diff --git a/kernel/filesystem/FAT/DirectoryEntry.h b/kernel/filesystem/FAT/DirectoryEntry.h index c3e48ec..bbc3a9a 100644 --- a/kernel/filesystem/FAT/DirectoryEntry.h +++ b/kernel/filesystem/FAT/DirectoryEntry.h @@ -1,14 +1,14 @@ #pragma once -#include +#include struct DirectoryEntry { uint8_t filename [8]; uint8_t Extension [3]; uint8_t attribute; uint8_t Reserved; - uint8_t creation; - uint16_t CreationTime; - uint16_t CreationDate; + uint8_t creation; // Creation in tenths of a second + uint16_t CreationTime; // Time Created NOTE: Multiply the seconds by 2 + uint16_t CreationDate; // Date Created uint16_t LastAccessDate; uint16_t ReservedFAT32; uint16_t LastWriteTime; @@ -16,4 +16,22 @@ struct DirectoryEntry { uint16_t StartingCluster; uint32_t FilesizeInBytes; -}__attribute__((packed)); \ No newline at end of file +}__attribute__((packed)); + + + +typedef struct _DIRECTORY{ + uint8_t Filename[8]; + uint8_t Ext[3]; + uint8_t Attrib; + uint8_t Reserved; + uint8_t TimeCreatedMs; + uint16_t TimeCreated; + uint16_t DateCreated; + uint16_t DateLastAccessed; + uint16_t FirstClusterHiBytes; + uint16_t LastModTime; + uint16_t LastModDate; + uint16_t FirstCluster; + uint32_t FileSize; +}__attribute__((packed)) DIRECTORY, *PDIRECTORY; \ No newline at end of file diff --git a/kernel/vfs/VFS.cpp b/kernel/filesystem/FAT/FAT.cpp similarity index 62% rename from kernel/vfs/VFS.cpp rename to kernel/filesystem/FAT/FAT.cpp index 9fe8d3f..3f48492 100644 --- a/kernel/vfs/VFS.cpp +++ b/kernel/filesystem/FAT/FAT.cpp @@ -1,109 +1,31 @@ -#include "VFS.h" -#include "../filesystem/FAT/BiosParameterBlock.h" -#include "../drivers/ide/ide.h" -#include "../drivers/ata/ataDevice.h" -#include "../partitiontable/mbr/MasterBootRecord.h" -#include "../memory/KernelHeap.h" -#include "../../CoreLib/Memory.h" -#include "../filesystem/FAT/DirectoryEntry.h" +// +// Created by nigel on 21/02/23. +// -MOUNT_INFO mountInfo; +#include "FAT.h" -PFILESYSTEM _filesystems[DEVICE_MAX]; - -FILE volOpenFile(const char* fname) -{ - if(fname){ - unsigned char device = 'a'; - - char* filename = (char*) fname; - - if(fname[1]== ':'){ - device = fname[0]; - filename += 2; // strip the volume component from the path - } - - if(_filesystems[device - 'a']){ - FILE file = _filesystems[device-'a']->Open(filename); - file.device = device; - return file; - } - } - - FILE file; - file.flags = FS_INVALID; - return file; -} - -extern void volReadFile(PFILE file, unsigned char* Buffer, unsigned int length) +void FAT::Read() { } -extern void volCloseFile(PFILE file) + +void FAT::Open() { - if( file->device < DEVICE_MAX){ - // _filesystems[file->device]->Close(file); - } -} - -extern void volRegisterFilesystem(PFILESYSTEM fsys , unsigned int deviceID){ - if(deviceID < DEVICE_MAX) - if(fsys) - _filesystems[deviceID] = fsys; -} - -extern void volUnregisterFilesystem(PFILESYSTEM){ } -extern void volUnregisterFileSystemByID(unsigned int deviceID){ +void FAT::Write() +{ } -enum BUS_PORT { - Primary = 0x1f0, - Secondary = 0x170 -}; +void ParseDateInteger(unsigned int date){ + printf("Date (hex) 0x%x\n", date); + unsigned int year = (date >> 9 )+ 1980; + unsigned int month = (date & 0xf0 ) >> 4; + unsigned int day = date & 0xf ; + printf("Date: (D,M,Y) %d, %d ,%d\n", day , month, year ); -bool driveAvailable(){ - int devNumber = 0; - for ( auto device : ide_devices){ - if(!device.Reserved) - continue; - devNumber++; - } - - - // FIXME: If no drive is connected we continue trying to read from - // a not connected drive! - ATA_DEVICE::Identify((uint16_t) BUS_PORT::Primary, DEVICE_DRIVE::MASTER); - return true; -} - -MBR* getPartitions(bool DEBUG = false){ - const int C = 0; - const int H = 0; - const int HPC = 16; - const int SPT = 63; - - int S =1; - uint32_t LBA = (C*HPC+H) * SPT + (S-1); - MBR* mbr =(MBR*) malloc(sizeof (MBR)); - - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, (uint16_t*)mbr); - - if(DEBUG){ - printf("BootSector: 0x%x\n", mbr->ValidBootsector ); - for( int i = 0 ; i < 4 ; i ++){ - PartitionTableEntry PT = mbr->TableEntries[i]; - - printf("Partition %d [ %d sectors, PartitionType: 0x%x, 0x%x, \nLBA Start: 0x%x ]\n" , - i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); - } - - } - - return mbr; } BiosParameterBlock* getBPB(MBR* mbr, bool DEBUG =false ){ @@ -142,6 +64,7 @@ uint16_t* ReadFAT (BiosParameterBlock& bpb , MBR& mbr, bool DEBUG = false ) { return FAT; } + void readFile(uint32_t DataRegion, DirectoryEntry* entry, uint16_t FATentry, BiosParameterBlock& bpb ){ printf("Show contents"); @@ -161,6 +84,7 @@ void readFile(uint32_t DataRegion, DirectoryEntry* entry, uint16_t FATentry, Bio } kterm_put('\n'); } + void listFilesInRoot(MBR& mbr, BiosParameterBlock& bpb ){ auto FATAddress = mbr.TableEntries[0].LBA_partition_start + bpb.ReservedSectors; uint32_t RootDirectoryRegion = FATAddress + ( bpb.NumberOfFileAllocationTables * bpb.NumberOfSectorsPerFAT ); @@ -178,8 +102,12 @@ void listFilesInRoot(MBR& mbr, BiosParameterBlock& bpb ){ if (entry->filename[0] == (uint8_t) 0x00) continue; // There are no more entries in this directory or the entry is free - if ((entry->attribute & 0x01) == 0x01 || (entry->attribute & 0x20) == 0x20) - continue; // Skip listing if hidden or Achieve flag is set + if (entry->attribute & ATTRIBUTES::ATT_HIDDEN) + continue; + if(entry->attribute & ATTRIBUTES::ATTR_SYSTEM) + continue; + if(entry->attribute & ATTRIBUTES::ATTR_VOLUME_ID) + continue; // Print the filename; for (char n: entry->filename) { @@ -196,7 +124,7 @@ void listFilesInRoot(MBR& mbr, BiosParameterBlock& bpb ){ printf("Attribute: %x \n", entry->attribute); printf("FileSize: %d Bytes\n", entry->FilesizeInBytes); - if (entry->FilesizeInBytes != 0x0 && (entry->attribute == 0x08)) { + if (entry->FilesizeInBytes != 0x0 && (entry->attribute != 0x10)) { readFile(DataRegion,entry, FAT[i], bpb); } @@ -205,8 +133,6 @@ void listFilesInRoot(MBR& mbr, BiosParameterBlock& bpb ){ } - -/* FILE fsysFatDirectory (const char* DirectoryName){ FILE file; unsigned char* buf; @@ -248,7 +174,7 @@ FILE fsysFatDirectory (const char* DirectoryName){ return file; } - */ + void fsysFATRead(PFILE file, unsigned char* buffer, unsigned int length){ if(file){ @@ -294,7 +220,7 @@ void fsysFATRead(PFILE file, unsigned char* buffer, unsigned int length){ } } -/* + FILE fsysFatOpenSubDir(FILE kFile, const char* filename){ FILE file; @@ -339,79 +265,3 @@ FILE fsysFatOpenSubDir(FILE kFile, const char* filename){ file.flags = FS_INVALID; return file; } -*/ - -void FileSystem::initialize() -{ - MBR* mbr = getPartitions(); - BiosParameterBlock* bootsector = getBPB(mbr); - listFilesInRoot(*mbr, *bootsector); - - free(mbr); - free(bootsector); -/* - mountInfo.numSectors = bootsector->NumberOfSectorsPerFAT; - mountInfo.fatOffset = 1; - mountInfo.fatSize = bootsector->NumberOfSectorsPerFAT; - mountInfo.fatEntrySize = 8; - mountInfo.numRootEntries = bootsector->NumberOfDirectoryEntries; - mountInfo.rootOffset = (bootsector->NumberOfFileAllocationTables * bootsector->NumberOfSectorsPerFAT) + 1; - mountInfo.rootSize = (bootsector->NumberOfDirectoryEntries * 32) / bootsector->BytesPerSector; -*/ - - -} - -char* FindNextEntryName (char* path ) -{ - int length = strlen(path); - - char* name = path; - int i = 0; - - if( name[0] == '/') - i++; - - while ( name[i] != '/' && i <= length) - i++; - - char* s = (char*) malloc(i + 1 * sizeof(char)); - for ( int a = 0; a < i; a++) - s[a] = path[a]; - - s[i + 1] = '\0'; - - return s; - -} - - - -void FileSystem::ResolvePath(Path &path) -{ - // See reference material (1) https://man7.org/linux/man-pages/man7/path_resolution.7.html - - char* string_path = path.str(); - void* cpy = string_path; - - bool isAbsolutePath = string_path[0] == '/'; - if(isAbsolutePath) - { - // strip the first slash - string_path++; - } - - char* entry_name = FindNextEntryName(string_path); - printf("Look for entry with name: %s\n", entry_name); - int skip = strlen(entry_name); - free(entry_name); - - - entry_name = FindNextEntryName(string_path + skip); - printf("Look for entry with name: %s\n", entry_name); - skip = strlen(entry_name); - free(entry_name); - - free(cpy); - -} \ No newline at end of file diff --git a/kernel/filesystem/FAT/FAT.h b/kernel/filesystem/FAT/FAT.h new file mode 100644 index 0000000..5aeb10b --- /dev/null +++ b/kernel/filesystem/FAT/FAT.h @@ -0,0 +1,41 @@ +// +// Created by nigel on 21/02/23. +// +#pragma once +#include "ExtendBootRecord.h" +#include "BiosParameterBlock.h" +#include "DirectoryEntry.h" + + +// Date Format +// [0..4] Day +// [5..8] Month +// [9..15] Year + +// Time Format +// [0..4] Seconds +// [5..10] Minute +// [11..15] Hour + + +class FAT { +public: + void Open(); + void Read(); + void Write(); +private: + enum struct TYPE{ + FAT, + FAT16, + FAT32, + VFAT + }; + enum ATTRIBUTES { + ATTR_READ_ONLY = 0x01, + ATT_HIDDEN = 0x02, + ATTR_SYSTEM = 0x04, + ATTR_VOLUME_ID = 0x08, + ATTR_DIRECTORY = 0x10, + ATTR_ARCHIVE = 0x20 + }; +}; diff --git a/kernel/drivers/io/io.cpp b/kernel/io/io.cpp similarity index 100% rename from kernel/drivers/io/io.cpp rename to kernel/io/io.cpp diff --git a/kernel/drivers/io/io.h b/kernel/io/io.h similarity index 100% rename from kernel/drivers/io/io.h rename to kernel/io/io.h diff --git a/kernel/kernel.cpp b/kernel/kernel.cpp index 9440716..b91b517 100644 --- a/kernel/kernel.cpp +++ b/kernel/kernel.cpp @@ -7,14 +7,15 @@ #include "memory/TaskStateSegment.h" #include "supervisorterminal/superVisorTerminal.h" #include "drivers/vga/VBE.h" -#include "drivers/pci/pci.h" +#include "pci/pci.h" #include "drivers/pit/pit.h" -#include "drivers/acpi/acpi.h" +#include "acpi/acpi.h" #include "i386/processor.h" #include "terminal/kterm.h" #include "interrupts/idt.h" #include "serial.h" -#include "vfs/VFS.h" +#include "storage/vfs/VFS.h" +#include "../CoreLib/Memory.h" extern "C" void LoadGlobalDescriptorTable(); extern "C" void jump_usermode(); @@ -25,6 +26,7 @@ extern "C" void kernel () init_serial(); kterm_init(); + setup_tss(); initGDT(); initidt(); @@ -37,16 +39,13 @@ extern "C" void kernel () initHeap(); pit_initialise(); - // ACPI::initialize(); // FIXME: improper reading of bios memory - PCI::Scan(); + ACPI::initialize(); + + //PCI::Scan(); processor::initialize(); processor::enable_protectedMode(); - FileSystem::initialize(); - - // Testing my path resolution functions - Path test = Path("/boot/myos.bin"); - FileSystem::ResolvePath(test); + VirtualFileSystem::initialize(); #ifdef USERMODE_RELEASE diff --git a/kernel/linker.ld b/kernel/linker.ld index f15ca57..666bc28 100644 --- a/kernel/linker.ld +++ b/kernel/linker.ld @@ -25,6 +25,7 @@ SECTIONS .rodata ALIGN (4K) : AT (ADDR (.rodata) - 0xC0000000) { *(.rodata) + *(.symtab) } .data ALIGN (4K) : AT (ADDR (.data) - 0xC0000000) { @@ -36,6 +37,8 @@ SECTIONS *(.bss) *(.bootstrap_stack) } + + _kernel_end = .; kernel_end = .; /* For legacy reasons */ } diff --git a/kernel/partitiontable/mbr/MasterBootRecord.h b/kernel/partitiontable/mbr/MasterBootRecord.h index a8d7aea..76f8c80 100644 --- a/kernel/partitiontable/mbr/MasterBootRecord.h +++ b/kernel/partitiontable/mbr/MasterBootRecord.h @@ -1,6 +1,8 @@ #pragma once -#include +#include #include "PartitionTableEntry.h" +#include "../../memory/KernelHeap.h" +#include "../../storage/ata pio/ataDevice.h" struct MBR { uint8_t code [440]; @@ -8,4 +10,31 @@ struct MBR { uint16_t Reserved; PartitionTableEntry TableEntries[4]; uint16_t ValidBootsector; -}__attribute__((packed)); \ No newline at end of file +}__attribute__((packed)); + + +MBR* getPartitions( bool DEBUG = false){ + const int C = 0; + const int H = 0; + const int HPC = 16; + const int SPT = 63; + + int S =1; + uint32_t LBA = (C*HPC+H) * SPT + (S-1); + MBR* mbr =(MBR*) malloc(sizeof (MBR)); + + ATAPIO::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, (uint16_t*)mbr); + + if(DEBUG){ + printf("BootSector: 0x%x\n", mbr->ValidBootsector ); + for( int i = 0 ; i < 4 ; i ++){ + PartitionTableEntry PT = mbr->TableEntries[i]; + + printf("Partition %d [ %d sectors, PartitionType: 0x%x, 0x%x, \nLBA Start: 0x%x ]\n" , + i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); + } + + } + + return mbr; +} diff --git a/kernel/drivers/pci/pci.cpp b/kernel/pci/pci.cpp similarity index 100% rename from kernel/drivers/pci/pci.cpp rename to kernel/pci/pci.cpp diff --git a/kernel/drivers/pci/pci.h b/kernel/pci/pci.h similarity index 98% rename from kernel/drivers/pci/pci.h rename to kernel/pci/pci.h index e46a77e..d09138f 100644 --- a/kernel/drivers/pci/pci.h +++ b/kernel/pci/pci.h @@ -1,7 +1,7 @@ #pragma once #include #include "../io/io.h" -#include "../../terminal/kterm.h" +#include "../terminal/kterm.h" #include "pciDevice.h" // Configuration Space Access Mechanism #1 diff --git a/kernel/drivers/pci/pciDevice.cpp b/kernel/pci/pciDevice.cpp similarity index 100% rename from kernel/drivers/pci/pciDevice.cpp rename to kernel/pci/pciDevice.cpp diff --git a/kernel/drivers/pci/pciDevice.h b/kernel/pci/pciDevice.h similarity index 100% rename from kernel/drivers/pci/pciDevice.h rename to kernel/pci/pciDevice.h diff --git a/kernel/prekernel/prekernel.cpp b/kernel/prekernel/prekernel.cpp index 53c34d3..0934212 100644 --- a/kernel/prekernel/prekernel.cpp +++ b/kernel/prekernel/prekernel.cpp @@ -6,7 +6,7 @@ #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) #define VADDR_TO_PADDR(vaddr) (vaddr - 0xC0000000) #define PADDR_TO_VADDR(paddr) (paddr + 0xC0000000) - +multiboot_info_t* global_mbi; extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) { @@ -21,8 +21,8 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) } mbi = PADDR_TO_VADDR(mbi); + global_mbi = mbi; - // Setup the physical memory manager immmediatly // Doing so saves the complications of doing it later when // paging is enabled diff --git a/kernel/serial.h b/kernel/serial.h index ca72be9..1ede93e 100644 --- a/kernel/serial.h +++ b/kernel/serial.h @@ -1,7 +1,7 @@ #pragma once #include "terminal/kterm.h" -#include "drivers/io/io.h" +#include "io/io.h" #define PORT 0x3f8 static int init_serial() { diff --git a/kernel/drivers/ata/ataDevice.cpp b/kernel/storage/ata pio/ataDevice.cpp similarity index 78% rename from kernel/drivers/ata/ataDevice.cpp rename to kernel/storage/ata pio/ataDevice.cpp index bde914a..b38773c 100644 --- a/kernel/drivers/ata/ataDevice.cpp +++ b/kernel/storage/ata pio/ataDevice.cpp @@ -1,112 +1,9 @@ #include "ataDevice.h" -#define IS_BIT_SET(x, bit) ((x >> bit & 0x1) == 1) +#include "../../io/io.h" -void ATA_DEVICE::Soft_Reset(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive){ - printf("Soft reseting drive...\n"); - outb(channels[DEVICE_CHANNEL].base + 7 , 0x4); - // wait a bit.. - for(int i = 0 ; i < 1000000; i++){ - asm volatile("NOP"); - } - outb(channels[DEVICE_CHANNEL].base + 7 , 0x0); +#define IS_BIT_SET(x, bit) ((x >> bit & 0x1) == 1) -} - -void ATA_DEVICE::Identify(uint16_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ - // lets ignore which port we actually want to check for now ! - - /* - THE STEPS INVOLVED - - 1. Select the target drive by sending master (0x0A) or slave (0x0B) to the - drive select IO port - - 2. Set the Sectorcount, LBAlo, LBAmid and LBAhi IO ports to 0 - - 3. Send the identify command (0xEC) to the command IO port - - 4. Read the status port - 4.2 If the value is 0x0 the drive does not exist - 4.3 If it has any other value continue - 5. poll the status port until bit 7 is clear. - 6. Check if the LBAmid and LBAhi ports are non-zero - 6.2. If non-zero stop polling this is not an ATA device - 6.3 If zero continue - - 7. poll status port until bit 3 is set or bit 0 is set - - 8. if err is clear, read the data from the data port - - - */ - - - //printf("channel selected: 0x%x", DEVICE_CHANNEL); - // Assuming Master here - // Select the target drive - outb(DEVICE_CHANNEL | 6, drive); // on the primary bus select the master drive - outb(DEVICE_CHANNEL | 6 , 0x0); // write 0 to the controlport for some reason - - outb(DEVICE_CHANNEL | 6, drive); - uint8_t status = inb(DEVICE_CHANNEL | 7 ); - if(status == 0x00){ - printf("No drive\n"); - return; - } - // send the identify command; - outb(DEVICE_CHANNEL | 7, 0xEC); - - - // set the sectorCount, LBAlo, LBAmid, LBA,hi IO ports to 0 - outb(DEVICE_CHANNEL | 2, 0); - - outb(DEVICE_CHANNEL | 3, 0); - - outb(DEVICE_CHANNEL | 4, 0); - - outb(DEVICE_CHANNEL | 5, 0); - - // send the identify command ; - //printf("command sent!\n"); - outb(DEVICE_CHANNEL | 7 , 0xEC); - - // read the status port - uint8_t status2 = inb(DEVICE_CHANNEL | 7); - if( status2 == 0x00){ - printf("No drive\n"); - return; - } - - //printf("Waiting until ready...\n"); - while(((status2 & 0x80 == 0x80) - && (status2 & 0x01) != 0x01) - ) status2 = inb(DEVICE_CHANNEL | 7); - - if( status2 & 0x01){ - printf("Error!\n"); - return ; - } - - uint16_t deviceIdentify [256] = {0}; - - for ( int i = 0; i < 256; i++){ - uint16_t data; - asm volatile ("inw %1, %0" : "=a"(data): "Nd"(DEVICE_CHANNEL)); - - deviceIdentify[i] = data; - } - - - printf("Model-label (ASCII hex): "); - for(int i = 27; i < 47; i++){ - kterm_put((char)(deviceIdentify[i] >> 8)); - kterm_put((char)(deviceIdentify[i] & 0x00FF)); - } - kterm_put('\n'); - -} - -void ATA_DEVICE::Read(uint16_t DEVICE_CHANNEL, DEVICE_DRIVE drive, uint32_t LBA, uint16_t* buffer) { +void ATAPIO::Read(uint16_t DEVICE_CHANNEL, DEVICE_DRIVE drive, uint32_t LBA, uint16_t* buffer) { /* Assume you have a sectorcount byte and a 28 bit LBA value. A sectorcount of 0 means 256 sectors = 128K. @@ -188,6 +85,116 @@ void ATA_DEVICE::Read(uint16_t DEVICE_CHANNEL, DEVICE_DRIVE drive, uint32_t LBA } -void ATA_DEVICE::Write(uint16_t DEVICE_CHANNEL, DEVICE_DRIVE drive) { +void ATAPIO::Write(uint16_t data, DEVICE_DRIVE dev){ + printf("Not implemented\n"); -} \ No newline at end of file + +} + +void ATAPIO::Identify(uint16_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ + // lets ignore which port we actually want to check for now ! + + /* + THE STEPS INVOLVED + + 1. Select the target drive by sending master (0x0A) or slave (0x0B) to the + drive select IO port + + 2. Set the Sectorcount, LBAlo, LBAmid and LBAhi IO ports to 0 + + 3. Send the identify command (0xEC) to the command IO port + + 4. Read the status port + 4.2 If the value is 0x0 the drive does not exist + 4.3 If it has any other value continue + 5. poll the status port until bit 7 is clear. + 6. Check if the LBAmid and LBAhi ports are non-zero + 6.2. If non-zero stop polling this is not an ATA device + 6.3 If zero continue + + 7. poll status port until bit 3 is set or bit 0 is set + + 8. if err is clear, read the data from the data port + + + */ + + + //printf("channel selected: 0x%x", DEVICE_CHANNEL); + // Assuming Master here + // Select the target drive + outb(DEVICE_CHANNEL | 6, drive); // on the primary bus select the master drive + outb(DEVICE_CHANNEL | 6 , 0x0); // write 0 to the controlport for some reason + + outb(DEVICE_CHANNEL | 6, drive); + uint8_t status = inb(DEVICE_CHANNEL | 7 ); + if(status == 0x00){ + printf("No drive\n"); + return; + } + // send the identify command; + outb(DEVICE_CHANNEL | 7, 0xEC); + + + // set the sectorCount, LBAlo, LBAmid, LBA,hi IO ports to 0 + outb(DEVICE_CHANNEL | 2, 0); + + outb(DEVICE_CHANNEL | 3, 0); + + outb(DEVICE_CHANNEL | 4, 0); + + outb(DEVICE_CHANNEL | 5, 0); + + // send the identify command ; + //printf("command sent!\n"); + outb(DEVICE_CHANNEL | 7 , 0xEC); + + // read the status port + uint8_t status2 = inb(DEVICE_CHANNEL | 7); + if( status2 == 0x00){ + printf("No drive\n"); + return; + } + + //printf("Waiting until ready...\n"); + while(((status2 & 0x80 == 0x80) + && (status2 & 0x01) != 0x01) + ) status2 = inb(DEVICE_CHANNEL | 7); + + if( status2 & 0x01){ + printf("Error!\n"); + return ; + } + + uint16_t deviceIdentify [256] = {0}; + + for ( int i = 0; i < 256; i++){ + uint16_t data; + asm volatile ("inw %1, %0" : "=a"(data): "Nd"(DEVICE_CHANNEL)); + + deviceIdentify[i] = data; + } + + + printf("Model-label (ASCII hex): "); + for(int i = 27; i < 47; i++){ + kterm_put((char)(deviceIdentify[i] >> 8)); + kterm_put((char)(deviceIdentify[i] & 0x00FF)); + } + kterm_put('\n'); + +} + +void ATAPIO::Soft_Reset(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive){ + printf("Soft reseting drive...\n"); + // outb(channels[DEVICE_CHANNEL].base + 7 , 0x4); + // wait a bit.. + for(int i = 0 ; i < 1000000; i++){ + asm volatile("NOP"); + } + //outb(channels[DEVICE_CHANNEL].base + 7 , 0x0); + +} + + + diff --git a/kernel/storage/ata pio/ataDevice.h b/kernel/storage/ata pio/ataDevice.h new file mode 100644 index 0000000..f5fb255 --- /dev/null +++ b/kernel/storage/ata pio/ataDevice.h @@ -0,0 +1,38 @@ +#pragma once +#include +#include "../ide/ideCommands.h" +#include "../ide/sampleIDE.definitions.h" +#include "../../devices/BlockDevice.h" + + +#include "../../terminal/kterm.h" + +/* +* This first driver wil make use of IO ports. +* Doing so means reading or writing from disk is going +* to be very cpu intensive. +*/ + +enum DEVICE_DRIVE{ + MASTER = 0xA0, + SLAVE = 0xB0 +}; + + +enum BUS_PORT { + Primary = 0x1f0, + Secondary = 0x170 +}; + + + +class ATAPIO +{ +public: + static void Identify(uint16_t, DEVICE_DRIVE); + static void Read (uint16_t, DEVICE_DRIVE, uint32_t, uint16_t*); + static void Write(uint16_t, DEVICE_DRIVE); + static void Soft_Reset(uint8_t ,DEVICE_DRIVE ); +}; + + diff --git a/kernel/drivers/atapi/atapiDevice.cpp b/kernel/storage/atapi/atapiDevice.cpp similarity index 100% rename from kernel/drivers/atapi/atapiDevice.cpp rename to kernel/storage/atapi/atapiDevice.cpp diff --git a/kernel/drivers/atapi/atapiDevice.h b/kernel/storage/atapi/atapiDevice.h similarity index 95% rename from kernel/drivers/atapi/atapiDevice.h rename to kernel/storage/atapi/atapiDevice.h index ba480b9..0a3dd14 100644 --- a/kernel/drivers/atapi/atapiDevice.h +++ b/kernel/storage/atapi/atapiDevice.h @@ -1,6 +1,6 @@ #pragma once #include -#include "../io/io.h" +#include "../../io/io.h" #include "../ide/ideCommands.h" #include "../ide/sampleIDE.definitions.h" diff --git a/kernel/drivers/ide/ide.h b/kernel/storage/ide/ide.h similarity index 96% rename from kernel/drivers/ide/ide.h rename to kernel/storage/ide/ide.h index 1a1310d..1248f44 100644 --- a/kernel/drivers/ide/ide.h +++ b/kernel/storage/ide/ide.h @@ -1,10 +1,10 @@ #pragma once -#include -#include "../pci/pciDevice.h" -#include "../pci/pci.h" +#include #include "../../terminal/kterm.h" #include "ideCommands.h" #include "sampleIDE.h" +#include "../../pci/pciDevice.h" +#include "../../pci/pci.h" #define IS_BIT_SET(x, bit) ((x >> bit & 0x1) == 1) diff --git a/kernel/drivers/ide/ideCommands.h b/kernel/storage/ide/ideCommands.h similarity index 100% rename from kernel/drivers/ide/ideCommands.h rename to kernel/storage/ide/ideCommands.h diff --git a/kernel/drivers/ide/sampleIDE.definitions.h b/kernel/storage/ide/sampleIDE.definitions.h similarity index 100% rename from kernel/drivers/ide/sampleIDE.definitions.h rename to kernel/storage/ide/sampleIDE.definitions.h diff --git a/kernel/drivers/ide/sampleIDE.h b/kernel/storage/ide/sampleIDE.h similarity index 96% rename from kernel/drivers/ide/sampleIDE.h rename to kernel/storage/ide/sampleIDE.h index 5be1cf9..7322ccd 100644 --- a/kernel/drivers/ide/sampleIDE.h +++ b/kernel/storage/ide/sampleIDE.h @@ -1,5 +1,5 @@ #pragma once -#include +#include #include "../../terminal/kterm.h" #include "sampleIDE.definitions.h" #include "ideCommands.h" @@ -239,4 +239,20 @@ inline void Detect_IO_Ports(uint32_t BAR0, uint32_t BAR1,uint32_t BAR2, uint32_t channels[ATA_PRIMARY ].bmide = (BAR4 & (~1)) + 0; // Bus Master IDE channels[ATA_SECONDARY].bmide = (BAR4 & (~1)) + 8; // Bus Master IDE +} + + +bool driveAvailable(){ + int devNumber = 0; + for ( auto device : ide_devices){ + if(!device.Reserved) + continue; + devNumber++; + } + + + // FIXME: If no drive is connected we continue trying to read from + // a not connected drive! + //ATAPIO::Identify((uint16_t) BUS_PORT::Primary, DEVICE_DRIVE::MASTER); + return true; } \ No newline at end of file diff --git a/kernel/storage/vfs/FileSystem.cpp b/kernel/storage/vfs/FileSystem.cpp new file mode 100644 index 0000000..fe92789 --- /dev/null +++ b/kernel/storage/vfs/FileSystem.cpp @@ -0,0 +1,41 @@ +// +// Created by nigel on 21/02/23. +// +#include "FileSystem.h" + +void FileSystem::WriteFile(int file, unsigned char* buffer, unsigned int length) { + +} + +void FileSystem::ReadFile(int file, unsigned char* buffer, unsigned int length) { + +} + +FILE FileSystem::OpenFile(const char* fname){ + if(fname){ + unsigned char device = 'a'; + char* filename = (char*) fname; + + if(fname[1]== ':'){ + device = fname[0]; + filename += 2; // strip the volume component from the path + } + + if(_filesystems[device - 'a']){ + FILE file = _filesystems[device-'a']->Open(filename); + file.device = device; + return file; + } + } + FILE file; + file.flags = FS_INVALID; + return file; +} + +void FileSystem::CloseFile(PFILE file) { + if(file->device < DEVICE_MAX){ + // _filesystems[file->device]->Close(file); + } +} + + diff --git a/kernel/storage/vfs/FileSystem.h b/kernel/storage/vfs/FileSystem.h new file mode 100644 index 0000000..939eab9 --- /dev/null +++ b/kernel/storage/vfs/FileSystem.h @@ -0,0 +1,18 @@ +// +// Created by nigel on 21/02/23. +// +#pragma once +#include "StorageTypes.h" + +class FileSystem { +public: + static void WriteFile(PFILE file, unsigned char* beffer, unsigned int length); + static void ReadFile(PFILE file, unsigned char* buffer, unsigned int length); + static FILE OpenFile(const char* fname); + static void CloseFile(PFILE file); + + +}; + + + diff --git a/kernel/storage/vfs/Inode.cpp b/kernel/storage/vfs/Inode.cpp new file mode 100644 index 0000000..a01eebb --- /dev/null +++ b/kernel/storage/vfs/Inode.cpp @@ -0,0 +1,5 @@ +// +// Created by nigel on 21/02/23. +// + +#include "Inode.h" diff --git a/kernel/storage/vfs/Inode.h b/kernel/storage/vfs/Inode.h new file mode 100644 index 0000000..59d7ee5 --- /dev/null +++ b/kernel/storage/vfs/Inode.h @@ -0,0 +1,24 @@ +// +// Created by nigel on 21/02/23. +// +#pragma once +enum struct NODE_TYPE { + FILESYSTEM, + FILE, + DIRECTORY +}; + +enum struct PERMISSIONS { + READ, + WRITE, + EXECUTE +}; + +struct Inode { + NODE_TYPE type; + PERMISSIONS permissions; + Inode* Parent; + Inode* sibling; +}; + + diff --git a/kernel/storage/vfs/StorageTypes.h b/kernel/storage/vfs/StorageTypes.h new file mode 100644 index 0000000..91e1e07 --- /dev/null +++ b/kernel/storage/vfs/StorageTypes.h @@ -0,0 +1,32 @@ +// +// Created by nigel on 21/02/23. +// +#pragma once +#include + +enum FS_TYPES { + FS_FILE =0, + FS_DIRECTORY =1, + FS_INVALID=2 +}; + +typedef struct _FILE { + char name [32]; + uint32_t flags; + uint32_t filelength; + uint32_t id; + uint32_t eof; + uint32_t position; + uint32_t currentCluster; + uint32_t device; +}FILE, *PFILE; + +typedef struct _FILE_SYSTEM{ + char name[8]; + FILE (*Directory) (const char* Directoryname); + void (*Mount) (); + void (*Read) (PFILE file, unsigned char* buffer, unsigned int length); + void (Close) (PFILE); + FILE (*Open) (const char* filename); +}FILESYSTEM, *PFS; + diff --git a/kernel/storage/vfs/VFS.cpp b/kernel/storage/vfs/VFS.cpp new file mode 100644 index 0000000..6cdcf4d --- /dev/null +++ b/kernel/storage/vfs/VFS.cpp @@ -0,0 +1,54 @@ +#include "VFS.h" +#include +#include "../../memory/KernelHeap.h" +#include + +PFS VirtualFileSystem::_filesystems[VirtualFileSystem::DEVICE_MAX]; + +void VirtualFileSystem::initialize() +{ + +} + +void VirtualFileSystem::ResolvePath(Path &path) +{ + // See reference material (1) https://man7.org/linux/man-pages/man7/path_resolution.7.html + + char* string_path = path.str(); + void* cpy = string_path; + + bool isAbsolutePath = string_path[0] == '/'; + if(isAbsolutePath) + { + // strip the first slash + string_path++; + } + + char* tokstate = NULL; + char* nextdir = strtok(string_path, "/", &tokstate); + while (nextdir) + { + printf("First entry to look for: %s\n", nextdir); + nextdir = strtok(NULL, "/", &tokstate); + } + + free(cpy); +} + +void VirtualFileSystem::Mount(PFS filesystemDescriptor, unsigned int DeviceID) +{ + if(DeviceID < DEVICE_MAX) + if(filesystemDescriptor) + _filesystems[DeviceID] = filesystemDescriptor; +} + + +void VirtualFileSystem::Unmount(unsigned int DeviceID) { + if(DeviceID < DEVICE_MAX) + _filesystems[DeviceID] = nullptr; +} + + + + + diff --git a/kernel/storage/vfs/VFS.h b/kernel/storage/vfs/VFS.h new file mode 100644 index 0000000..095d7de --- /dev/null +++ b/kernel/storage/vfs/VFS.h @@ -0,0 +1,17 @@ +#pragma once +#include +#include "../../../CoreLib/Path.h" +#include "StorageTypes.h" + class VirtualFileSystem + { + public: + static void initialize(); + static void Mount(PFS fs, unsigned int DeviceID); + static void Unmount(unsigned int DeviceID); + static void ResolvePath(Path& path); + + private: + static const unsigned int DEVICE_MAX = 26; + static PFS _filesystems[DEVICE_MAX]; + + }; \ No newline at end of file diff --git a/kernel/supervisorterminal/superVisorTerminal.cpp b/kernel/supervisorterminal/superVisorTerminal.cpp index d574b65..f239593 100644 --- a/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/kernel/supervisorterminal/superVisorTerminal.cpp @@ -1,8 +1,9 @@ #include "superVisorTerminal.h" -#include "../drivers/ata/ataDevice.h" +#include "../storage/ata pio/ataDevice.h" #include "../partitiontable/mbr/MasterBootRecord.h" #include "../filesystem/FAT/BiosParameterBlock.h" #include "../filesystem/FAT/DirectoryEntry.h" + bool isRunning = true; extern "C" void startSuperVisorTerminal() { diff --git a/kernel/terminal/kterm.h b/kernel/terminal/kterm.h index 3207a47..5d5a7a0 100644 --- a/kernel/terminal/kterm.h +++ b/kernel/terminal/kterm.h @@ -1,10 +1,10 @@ #pragma once -#include +#include #include #include #include "../drivers/vga/colors.h" -#include "../drivers/io/io.h" +#include "../io/io.h" #include void kterm_init(); diff --git a/kernel/time.h b/kernel/time.h index 9d0003a..c08d440 100644 --- a/kernel/time.h +++ b/kernel/time.h @@ -1,5 +1,5 @@ #pragma once -#include "drivers/io/io.h" +#include "io/io.h" #define CURRENT_YEAR 2021 diff --git a/kernel/timer.h b/kernel/timer.h index db8be78..9b877e1 100644 --- a/kernel/timer.h +++ b/kernel/timer.h @@ -1,6 +1,6 @@ #pragma once #include -#include +#include void init_timer (uint32_t frequency); \ No newline at end of file diff --git a/kernel/vfs/VFS.h b/kernel/vfs/VFS.h deleted file mode 100644 index b294244..0000000 --- a/kernel/vfs/VFS.h +++ /dev/null @@ -1,80 +0,0 @@ -#pragma once -#include -#include "../../CoreLib/Path.h" - -#define FS_FILE 0 -#define FS_DIRECTORY 1 -#define FS_INVALID 2 -#define DEVICE_MAX 26 - -typedef struct _FILE { - char name [32]; - uint32_t flags; - uint32_t filelength; - uint32_t id; - uint32_t eof; - uint32_t position; - uint32_t currentCluster; - uint32_t device; -}FILE, *PFILE; - -typedef struct _FILE_SYSTEM{ - char name[8]; - FILE (*Directory) (const char* Directoryname); - void (*Mount) (); - void (*Read) (PFILE file, unsigned char* buffer, unsigned int length); - void (Close) (PFILE); - FILE (*Open) (const char* filename); -}FILESYSTEM, *PFILESYSTEM; - -typedef struct _MOUNT_INFO{ - uint32_t numSectors; - uint32_t fatOffset; - uint32_t numRootEntries; - uint32_t rootOffset; - uint32_t rootSize; - uint32_t fatSize; - uint32_t fatEntrySize; -}MOUNT_INFO, *PMOUNT_INFO; - -typedef struct _DIRECTORY{ - uint8_t Filename[8]; - uint8_t Ext[3]; - uint8_t Attrib; - uint8_t Reserved; - uint8_t TimeCreatedMs; - uint16_t TimeCreated; - uint16_t DateCreated; - uint16_t DateLastAccessed; - uint16_t FirstClusterHiBytes; - uint16_t LastModTime; - uint16_t LastModDate; - uint16_t FirstCluster; - uint32_t FileSize; -}DIRECTORY, *PDIRECTORY; -// Date Format -// [0..4] Day -// [5..8] Month -// [9..15] Year - -// Time Format -// [0..4] Seconds -// [5..10] Minute -// [11..15] Hour -extern PFILESYSTEM _filesystems[DEVICE_MAX]; - - FILE volOpenFile(const char* fname); - - void volCloseFile(PFILE file); - void volRegisterFilesystem(PFILESYSTEM, unsigned int deviceID); - void volUnregisterFilesystem(PFILESYSTEM); - void volUnregisterFileSystemByID(unsigned int deviceID); - - - class FileSystem{ - public: - static void initialize(); - - static void ResolvePath(Path& path); - - }; \ No newline at end of file diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..a97e584 --- /dev/null +++ b/run.sh @@ -0,0 +1,12 @@ +#!/bin/bash + + +cd CoreLib +make +cd ../kernel +make clean +make +cd .. + +./scripts/update_harddrive.sh +./scripts/run_qemu.sh diff --git a/scripts/update_harddrive.sh b/scripts/update_harddrive.sh index 8295420..cc342c2 100755 --- a/scripts/update_harddrive.sh +++ b/scripts/update_harddrive.sh @@ -1,4 +1,7 @@ #!/bin/bash + +echo "running in cwd : " + echo $(pwd) echo "Mount harddrive image as block device" sudo losetup /dev/loop9 disk.img sudo mount /dev/loop9 /mnt -- 2.39.5 From 50bf952a49b88290075738a5c14ba0362c92551d Mon Sep 17 00:00:00 2001 From: Nigel Date: Tue, 21 Feb 2023 21:43:14 +0100 Subject: [PATCH 101/115] Basic idea's are created for the storage solution - Added boot device info parsing to the kernel - Added a pointer in the kernel to our pre-kernel BootInfo structure - Created a layout for the FAT driver - Created a layout for the virtual filesystem - Separated IDE driver from the basic atapio driver. This will ensure we are not using one or the other - The create_harddrive shell script will now actually build a harddrive image of the kernel - The virtual filesystem initializes and creates a filesystem structure for every FAT16 partition in the master boot record --- kernel/Makefile | 10 +- kernel/kernel.cpp | 28 +++- kernel/prekernel/prekernel.cpp | 6 +- .../ata pio/{ataDevice.cpp => ATAPIO.cpp} | 19 ++- .../storage/ata pio/{ataDevice.h => ATAPIO.h} | 8 +- .../filesystems}/EXT2/SuperBlock.h | 0 .../filesystems}/FAT/BiosParameterBlock.h | 0 .../filesystems}/FAT/DirectoryEntry.h | 0 .../filesystems}/FAT/ExtendBootRecord.h | 0 .../filesystems}/FAT/FAT.cpp | 77 +++++++++-- .../filesystems}/FAT/FAT.h | 16 ++- .../partitiontables}/mbr/MasterBootRecord.h | 13 +- .../mbr/PartitionTableEntry.h | 0 kernel/storage/vfs/StorageTypes.h | 12 +- kernel/storage/vfs/VFS.cpp | 54 -------- kernel/storage/vfs/vfs.cpp | 130 ++++++++++++++++++ kernel/storage/vfs/{VFS.h => vfs.h} | 7 +- .../supervisorterminal/superVisorTerminal.cpp | 8 +- scripts/create_harddrive.sh | 25 ++-- 19 files changed, 290 insertions(+), 123 deletions(-) rename kernel/storage/ata pio/{ataDevice.cpp => ATAPIO.cpp} (95%) rename kernel/storage/ata pio/{ataDevice.h => ATAPIO.h} (81%) rename kernel/{filesystem => storage/filesystems}/EXT2/SuperBlock.h (100%) rename kernel/{filesystem => storage/filesystems}/FAT/BiosParameterBlock.h (100%) rename kernel/{filesystem => storage/filesystems}/FAT/DirectoryEntry.h (100%) rename kernel/{filesystem => storage/filesystems}/FAT/ExtendBootRecord.h (100%) rename kernel/{filesystem => storage/filesystems}/FAT/FAT.cpp (80%) rename kernel/{filesystem => storage/filesystems}/FAT/FAT.h (63%) rename kernel/{partitiontable => storage/partitiontables}/mbr/MasterBootRecord.h (71%) rename kernel/{partitiontable => storage/partitiontables}/mbr/PartitionTableEntry.h (100%) delete mode 100644 kernel/storage/vfs/VFS.cpp create mode 100644 kernel/storage/vfs/vfs.cpp rename kernel/storage/vfs/{VFS.h => vfs.h} (58%) mode change 100644 => 100755 scripts/create_harddrive.sh diff --git a/kernel/Makefile b/kernel/Makefile index 923680f..4d333d1 100644 --- a/kernel/Makefile +++ b/kernel/Makefile @@ -33,7 +33,8 @@ OFILES = $(OBJ_DIR)/boot.o \ $(OBJ_DIR)/atapiDevice.o \ $(OBJ_DIR)/ataDevice.o \ $(OBJ_DIR)/rsdp.o \ - $(OBJ_DIR)/acpi.o + $(OBJ_DIR)/acpi.o \ + $(OBJ_DIR)/fat.o OBJ_LINK_LIST = $(CRTI_OBJ) $(CRTBEGIN_OBJ) $(OFILES) $(CRTEND_OBJ) $(CRTN_OBJ) INTERNAL_OBJS = $(CRTI_OBJ) $(OFILES) $(CRTN_OBJ) @@ -79,7 +80,7 @@ $(OBJ_DIR)/atapiDevice.o: $(CPP) -c storage/atapi/atapiDevice.cpp -o $(OBJ_DIR)/atapiDevice.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/ataDevice.o: - $(CPP) -c "storage/ata pio/ataDevice.cpp" -o $(OBJ_DIR)/ataDevice.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c "storage/ata pio/ATAPIO.cpp" -o $(OBJ_DIR)/ataDevice.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/rsdp.o: $(CPP) -c acpi/rsdp.cpp -o $(OBJ_DIR)/rsdp.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -91,7 +92,7 @@ $(OBJ_DIR)/pit.o: $(CPP) -c drivers/pit/pit.cpp -o $(OBJ_DIR)/pit.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/VFS.o: - $(CPP) -c storage/vfs/VFS.cpp -o $(OBJ_DIR)/VFS.o $(CFLAGS) -fno-exceptions -fno-rtti + $(CPP) -c storage/vfs/vfs.cpp -o $(OBJ_DIR)/VFS.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/keyboard.o: $(CPP) -c drivers/ps-2/keyboard.cpp -o $(OBJ_DIR)/keyboard.o $(CFLAGS) -fno-exceptions -fno-rtti @@ -117,6 +118,9 @@ $(OBJ_DIR)/prekernel.o: $(OBJ_DIR)/processor.o: $(CPP) -c i386/processor.cpp -o $(OBJ_DIR)/processor.o $(CFLAGS) -fno-exceptions -fno-rtti +$(OBJ_DIR)/fat.o: + $(CPP) -c storage/filesystems/FAT/FAT.cpp -o $(OBJ_DIR)/fat.o $(CFLAGS) -fno-exceptions -fno-rtti + # Assembly -> Object files $(OBJ_DIR)/boot.o: $(AS) boot/boot.s -o $(OBJ_DIR)/boot.o diff --git a/kernel/kernel.cpp b/kernel/kernel.cpp index b91b517..7609e71 100644 --- a/kernel/kernel.cpp +++ b/kernel/kernel.cpp @@ -14,11 +14,11 @@ #include "terminal/kterm.h" #include "interrupts/idt.h" #include "serial.h" -#include "storage/vfs/VFS.h" -#include "../CoreLib/Memory.h" +#include "storage/vfs/vfs.h" extern "C" void LoadGlobalDescriptorTable(); extern "C" void jump_usermode(); +extern BootInfoBlock* BIB; extern "C" void kernel () { @@ -26,7 +26,6 @@ extern "C" void kernel () init_serial(); kterm_init(); - setup_tss(); initGDT(); initidt(); @@ -41,12 +40,33 @@ extern "C" void kernel () pit_initialise(); ACPI::initialize(); - //PCI::Scan(); + PCI::Scan(); processor::initialize(); processor::enable_protectedMode(); + printf("Boot device: 0x%x\n", BIB->bootDeviceID); + unsigned int part3 = BIB->bootDeviceID & 0xFF; + unsigned int part2 = (BIB->bootDeviceID & 0xFF00) >> 8; + unsigned int part1 = (BIB->bootDeviceID & 0xFF0000) >> 16; + unsigned int drive = (BIB->bootDeviceID & 0xFF000000) >> 24; + if (drive == 0x80 ) + printf("booted from disk!\n"); + if(drive == 0x00) + printf("booted from floppy disk\n"); + + printf("Part1: %d, Part2: %d, Part3: %d\n", part1, part2 , part3); + VirtualFileSystem::initialize(); + // Try and open hello.txt file + VirtualFileSystem::OpenFile("a:hello.txt"); + + + + // Try and open grub.cfg file + VirtualFileSystem::OpenFile("a:boot/grub/grub.cfg"); + + #ifdef USERMODE_RELEASE // Lets jump into user mode diff --git a/kernel/prekernel/prekernel.cpp b/kernel/prekernel/prekernel.cpp index 0934212..e12bcf0 100644 --- a/kernel/prekernel/prekernel.cpp +++ b/kernel/prekernel/prekernel.cpp @@ -6,7 +6,7 @@ #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) #define VADDR_TO_PADDR(vaddr) (vaddr - 0xC0000000) #define PADDR_TO_VADDR(paddr) (paddr + 0xC0000000) -multiboot_info_t* global_mbi; +BootInfoBlock* BIB; extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) { @@ -21,7 +21,6 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) } mbi = PADDR_TO_VADDR(mbi); - global_mbi = mbi; // Setup the physical memory manager immmediatly // Doing so saves the complications of doing it later when @@ -82,13 +81,14 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) } // allocate a full block for the other boot info! - BootInfoBlock* BIB = (BootInfoBlock*) allocate_block(); + BIB = (BootInfoBlock*) allocate_block(); /* is boot device valid ? */ if (CHECK_FLAG (mbi->flags, 1)) { BIB->bootDeviceID = mbi->boot_device; + } else{ BIB->bootDeviceID = 0x11111111; } diff --git a/kernel/storage/ata pio/ataDevice.cpp b/kernel/storage/ata pio/ATAPIO.cpp similarity index 95% rename from kernel/storage/ata pio/ataDevice.cpp rename to kernel/storage/ata pio/ATAPIO.cpp index b38773c..57647f5 100644 --- a/kernel/storage/ata pio/ataDevice.cpp +++ b/kernel/storage/ata pio/ATAPIO.cpp @@ -1,4 +1,4 @@ -#include "ataDevice.h" +#include "ATAPIO.h" #include "../../io/io.h" #define IS_BIT_SET(x, bit) ((x >> bit & 0x1) == 1) @@ -91,7 +91,7 @@ void ATAPIO::Write(uint16_t data, DEVICE_DRIVE dev){ } -void ATAPIO::Identify(uint16_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ +bool ATAPIO::Identify(ATAPIO_PORT DEVICE_CHANNEL, DEVICE_DRIVE drive ){ // lets ignore which port we actually want to check for now ! /* @@ -125,12 +125,11 @@ void ATAPIO::Identify(uint16_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ // Select the target drive outb(DEVICE_CHANNEL | 6, drive); // on the primary bus select the master drive outb(DEVICE_CHANNEL | 6 , 0x0); // write 0 to the controlport for some reason - outb(DEVICE_CHANNEL | 6, drive); uint8_t status = inb(DEVICE_CHANNEL | 7 ); if(status == 0x00){ printf("No drive\n"); - return; + return false; } // send the identify command; outb(DEVICE_CHANNEL | 7, 0xEC); @@ -153,7 +152,7 @@ void ATAPIO::Identify(uint16_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ uint8_t status2 = inb(DEVICE_CHANNEL | 7); if( status2 == 0x00){ printf("No drive\n"); - return; + return false; } //printf("Waiting until ready...\n"); @@ -163,7 +162,7 @@ void ATAPIO::Identify(uint16_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ if( status2 & 0x01){ printf("Error!\n"); - return ; + return false; } uint16_t deviceIdentify [256] = {0}; @@ -182,17 +181,17 @@ void ATAPIO::Identify(uint16_t DEVICE_CHANNEL,DEVICE_DRIVE drive ){ kterm_put((char)(deviceIdentify[i] & 0x00FF)); } kterm_put('\n'); - + return true; } -void ATAPIO::Soft_Reset(uint8_t DEVICE_CHANNEL,DEVICE_DRIVE drive){ +void ATAPIO::Soft_Reset(ATAPIO_PORT DEVICE_CHANNEL, DEVICE_DRIVE drive){ printf("Soft reseting drive...\n"); - // outb(channels[DEVICE_CHANNEL].base + 7 , 0x4); + outb(DEVICE_CHANNEL + 7 , 0x4); // wait a bit.. for(int i = 0 ; i < 1000000; i++){ asm volatile("NOP"); } - //outb(channels[DEVICE_CHANNEL].base + 7 , 0x0); + outb(DEVICE_CHANNEL + 7 , 0x0); } diff --git a/kernel/storage/ata pio/ataDevice.h b/kernel/storage/ata pio/ATAPIO.h similarity index 81% rename from kernel/storage/ata pio/ataDevice.h rename to kernel/storage/ata pio/ATAPIO.h index f5fb255..5f3dab8 100644 --- a/kernel/storage/ata pio/ataDevice.h +++ b/kernel/storage/ata pio/ATAPIO.h @@ -3,8 +3,6 @@ #include "../ide/ideCommands.h" #include "../ide/sampleIDE.definitions.h" #include "../../devices/BlockDevice.h" - - #include "../../terminal/kterm.h" /* @@ -19,7 +17,7 @@ enum DEVICE_DRIVE{ }; -enum BUS_PORT { +enum ATAPIO_PORT { Primary = 0x1f0, Secondary = 0x170 }; @@ -29,10 +27,10 @@ enum BUS_PORT { class ATAPIO { public: - static void Identify(uint16_t, DEVICE_DRIVE); + static bool Identify(ATAPIO_PORT, DEVICE_DRIVE); static void Read (uint16_t, DEVICE_DRIVE, uint32_t, uint16_t*); static void Write(uint16_t, DEVICE_DRIVE); - static void Soft_Reset(uint8_t ,DEVICE_DRIVE ); + static void Soft_Reset(ATAPIO_PORT , DEVICE_DRIVE ); }; diff --git a/kernel/filesystem/EXT2/SuperBlock.h b/kernel/storage/filesystems/EXT2/SuperBlock.h similarity index 100% rename from kernel/filesystem/EXT2/SuperBlock.h rename to kernel/storage/filesystems/EXT2/SuperBlock.h diff --git a/kernel/filesystem/FAT/BiosParameterBlock.h b/kernel/storage/filesystems/FAT/BiosParameterBlock.h similarity index 100% rename from kernel/filesystem/FAT/BiosParameterBlock.h rename to kernel/storage/filesystems/FAT/BiosParameterBlock.h diff --git a/kernel/filesystem/FAT/DirectoryEntry.h b/kernel/storage/filesystems/FAT/DirectoryEntry.h similarity index 100% rename from kernel/filesystem/FAT/DirectoryEntry.h rename to kernel/storage/filesystems/FAT/DirectoryEntry.h diff --git a/kernel/filesystem/FAT/ExtendBootRecord.h b/kernel/storage/filesystems/FAT/ExtendBootRecord.h similarity index 100% rename from kernel/filesystem/FAT/ExtendBootRecord.h rename to kernel/storage/filesystems/FAT/ExtendBootRecord.h diff --git a/kernel/filesystem/FAT/FAT.cpp b/kernel/storage/filesystems/FAT/FAT.cpp similarity index 80% rename from kernel/filesystem/FAT/FAT.cpp rename to kernel/storage/filesystems/FAT/FAT.cpp index 3f48492..9161c6b 100644 --- a/kernel/filesystem/FAT/FAT.cpp +++ b/kernel/storage/filesystems/FAT/FAT.cpp @@ -1,20 +1,40 @@ // // Created by nigel on 21/02/23. // - #include "FAT.h" +#include "../../ata pio/ATAPIO.h" +#include "../../../memory/KernelHeap.h" +#include -void FAT::Read() +void FAT::Read(PFILE file, unsigned char* buffer , unsigned int length) { } -void FAT::Open() +FILE FAT::Open(char* filename) { + char* tokstate = NULL; + char* nextdir = strtok(filename, "/", &tokstate); + + while (nextdir) + { + + // Read the root directory + printf("First entry to look for: %s\n", nextdir); + + + + nextdir = strtok(NULL, "/", &tokstate); + } + + FILE file; + file.flags = FS_INVALID; + return file; + } -void FAT::Write() +void FAT::Write(PFILE file, unsigned char* buffer, unsigned int length) { } @@ -28,9 +48,17 @@ void ParseDateInteger(unsigned int date){ } -BiosParameterBlock* getBPB(MBR* mbr, bool DEBUG =false ){ + +BiosParameterBlock* getBPB(PTR_PARTITION partition, bool DEBUG =false ){ BiosParameterBlock* bpb = (BiosParameterBlock*) malloc(sizeof(BiosParameterBlock)); - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mbr->TableEntries[0].LBA_partition_start, (uint16_t*) bpb); + + ATAPIO_PORT port = (ATAPIO_PORT)(partition->Disk & 0x01FF); + DEVICE_DRIVE drive = (DEVICE_DRIVE)(partition->Disk >> 16); + + printf("ATAPIO_PORT: 0x%x DEVICE_DRIVE: 0x%x\n",port, drive); + printf("Partition Start Address (LBA): 0x%x\n", partition->StartAddress); + + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, partition->StartAddress, (uint16_t*) bpb); if(DEBUG) { @@ -44,15 +72,37 @@ BiosParameterBlock* getBPB(MBR* mbr, bool DEBUG =false ){ printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); } - - return bpb; } -uint16_t* ReadFAT (BiosParameterBlock& bpb , MBR& mbr, bool DEBUG = false ) { - uint32_t FATAddress = mbr.TableEntries[0].LBA_partition_start + bpb.ReservedSectors ; +bool FAT::Validate(PTR_PARTITION partition ) +{ + + auto* bootParams = getBPB(partition, true); + + if(bootParams->OEM_id) { + return true; + } + + return false; + +} + +void FAT::Info(_PARTITION *pPartition, PFS pSystem) { + pSystem->Read = FAT::Read; + pSystem->Write = FAT::Write; + pSystem->Open = FAT::Open; + + +} + +uint16_t* ReadFAT (BiosParameterBlock& bpb , PTR_PARTITION partition, bool DEBUG = false ) { + uint32_t FATAddress = partition->StartAddress + bpb.ReservedSectors ; uint16_t* FAT = (uint16_t*)malloc(sizeof (uint16_t) * 256); - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); + + ATAPIO_PORT port = (ATAPIO_PORT)(partition->Disk & 0x01FF); + DEVICE_DRIVE drive = (DEVICE_DRIVE)(partition->Disk >> 16); + ATAPIO::Read(port, drive, FATAddress, FAT ); // Show data in terminal if(DEBUG){ @@ -76,7 +126,7 @@ void readFile(uint32_t DataRegion, DirectoryEntry* entry, uint16_t FATentry, Bio uint16_t dataBlob[256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob); + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob); for (unsigned short n: dataBlob) { kterm_put(n & 0x00ff); @@ -84,7 +134,7 @@ void readFile(uint32_t DataRegion, DirectoryEntry* entry, uint16_t FATentry, Bio } kterm_put('\n'); } - +/* void listFilesInRoot(MBR& mbr, BiosParameterBlock& bpb ){ auto FATAddress = mbr.TableEntries[0].LBA_partition_start + bpb.ReservedSectors; uint32_t RootDirectoryRegion = FATAddress + ( bpb.NumberOfFileAllocationTables * bpb.NumberOfSectorsPerFAT ); @@ -265,3 +315,4 @@ FILE fsysFatOpenSubDir(FILE kFile, const char* filename){ file.flags = FS_INVALID; return file; } + */ diff --git a/kernel/filesystem/FAT/FAT.h b/kernel/storage/filesystems/FAT/FAT.h similarity index 63% rename from kernel/filesystem/FAT/FAT.h rename to kernel/storage/filesystems/FAT/FAT.h index 5aeb10b..bf8cce9 100644 --- a/kernel/filesystem/FAT/FAT.h +++ b/kernel/storage/filesystems/FAT/FAT.h @@ -5,7 +5,7 @@ #include "ExtendBootRecord.h" #include "BiosParameterBlock.h" #include "DirectoryEntry.h" - +#include "../../vfs/StorageTypes.h" // Date Format // [0..4] Day @@ -20,9 +20,17 @@ class FAT { public: - void Open(); - void Read(); - void Write(); + + + + static bool Validate(PTR_PARTITION partition ); + + static FILE Open(char* filename); + static void Read(PFILE file, unsigned char* buffer , unsigned int length); + static void Write(PFILE file, unsigned char* buffer, unsigned int length); + + static void Info(_PARTITION *pPartition, PFS pSystem); + private: enum struct TYPE{ FAT, diff --git a/kernel/partitiontable/mbr/MasterBootRecord.h b/kernel/storage/partitiontables/mbr/MasterBootRecord.h similarity index 71% rename from kernel/partitiontable/mbr/MasterBootRecord.h rename to kernel/storage/partitiontables/mbr/MasterBootRecord.h index 76f8c80..1cb207c 100644 --- a/kernel/partitiontable/mbr/MasterBootRecord.h +++ b/kernel/storage/partitiontables/mbr/MasterBootRecord.h @@ -1,19 +1,19 @@ #pragma once #include #include "PartitionTableEntry.h" -#include "../../memory/KernelHeap.h" -#include "../../storage/ata pio/ataDevice.h" +#include "../../../memory/KernelHeap.h" +#include "../../ata pio/ATAPIO.h" struct MBR { uint8_t code [440]; uint32_t uniqueID; uint16_t Reserved; - PartitionTableEntry TableEntries[4]; + struct PartitionTableEntry TableEntries[4]; uint16_t ValidBootsector; }__attribute__((packed)); -MBR* getPartitions( bool DEBUG = false){ +inline MBR* GetPartitions(bool DEBUG = false){ const int C = 0; const int H = 0; const int HPC = 16; @@ -21,10 +21,13 @@ MBR* getPartitions( bool DEBUG = false){ int S =1; uint32_t LBA = (C*HPC+H) * SPT + (S-1); + MBR* mbr =(MBR*) malloc(sizeof (MBR)); - ATAPIO::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, (uint16_t*)mbr); + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, (uint16_t*)mbr); + + printf("MBR (In Memory) Address 0x%x, Size = %d\n", mbr, sizeof (MBR)); if(DEBUG){ printf("BootSector: 0x%x\n", mbr->ValidBootsector ); for( int i = 0 ; i < 4 ; i ++){ diff --git a/kernel/partitiontable/mbr/PartitionTableEntry.h b/kernel/storage/partitiontables/mbr/PartitionTableEntry.h similarity index 100% rename from kernel/partitiontable/mbr/PartitionTableEntry.h rename to kernel/storage/partitiontables/mbr/PartitionTableEntry.h diff --git a/kernel/storage/vfs/StorageTypes.h b/kernel/storage/vfs/StorageTypes.h index 91e1e07..5acdc27 100644 --- a/kernel/storage/vfs/StorageTypes.h +++ b/kernel/storage/vfs/StorageTypes.h @@ -26,7 +26,15 @@ typedef struct _FILE_SYSTEM{ FILE (*Directory) (const char* Directoryname); void (*Mount) (); void (*Read) (PFILE file, unsigned char* buffer, unsigned int length); - void (Close) (PFILE); - FILE (*Open) (const char* filename); + void (*Write)(PFILE file, unsigned char* buffer, unsigned int length); + void (*Close) (PFILE); + FILE (*Open) (char* filename); }FILESYSTEM, *PFS; +typedef struct _PARTITION { + uint32_t Disk; + uint32_t StartAddress; + uint32_t Sectors; + uint8_t Fs_hint; + uint8_t Attributes; +}PARTITION, *PTR_PARTITION; diff --git a/kernel/storage/vfs/VFS.cpp b/kernel/storage/vfs/VFS.cpp deleted file mode 100644 index 6cdcf4d..0000000 --- a/kernel/storage/vfs/VFS.cpp +++ /dev/null @@ -1,54 +0,0 @@ -#include "VFS.h" -#include -#include "../../memory/KernelHeap.h" -#include - -PFS VirtualFileSystem::_filesystems[VirtualFileSystem::DEVICE_MAX]; - -void VirtualFileSystem::initialize() -{ - -} - -void VirtualFileSystem::ResolvePath(Path &path) -{ - // See reference material (1) https://man7.org/linux/man-pages/man7/path_resolution.7.html - - char* string_path = path.str(); - void* cpy = string_path; - - bool isAbsolutePath = string_path[0] == '/'; - if(isAbsolutePath) - { - // strip the first slash - string_path++; - } - - char* tokstate = NULL; - char* nextdir = strtok(string_path, "/", &tokstate); - while (nextdir) - { - printf("First entry to look for: %s\n", nextdir); - nextdir = strtok(NULL, "/", &tokstate); - } - - free(cpy); -} - -void VirtualFileSystem::Mount(PFS filesystemDescriptor, unsigned int DeviceID) -{ - if(DeviceID < DEVICE_MAX) - if(filesystemDescriptor) - _filesystems[DeviceID] = filesystemDescriptor; -} - - -void VirtualFileSystem::Unmount(unsigned int DeviceID) { - if(DeviceID < DEVICE_MAX) - _filesystems[DeviceID] = nullptr; -} - - - - - diff --git a/kernel/storage/vfs/vfs.cpp b/kernel/storage/vfs/vfs.cpp new file mode 100644 index 0000000..5597ebc --- /dev/null +++ b/kernel/storage/vfs/vfs.cpp @@ -0,0 +1,130 @@ +#include "vfs.h" +#include +#include "../../memory/KernelHeap.h" +#include "../ata pio/ATAPIO.h" +#include "../partitiontables/mbr/MasterBootRecord.h" +#include "../filesystems/FAT/FAT.h" +#include "StorageTypes.h" + +#include + +PFS VirtualFileSystem::_filesystems[VirtualFileSystem::DEVICE_MAX]; +PTR_PARTITION VirtualFileSystem::_partitions [VirtualFileSystem::PARTITION_MAX]; +unsigned int VirtualFileSystem::num_partitions = 0; + +void VirtualFileSystem::initialize() +{ + + // Mount the boot disk + // NOTE: we assume for now that it is the only disk in the system + // This information could possibly be had from the bootloader (GRUB) + // We als assume it is the primary device on the Master port. + ATAPIO::Soft_Reset(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); + bool isAvailable = ATAPIO::Identify(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); + if(!isAvailable){ + // PANIC!!! + printf("Failed to mount root filesystem!\n"); + return; + } + + auto masterbootrecord = GetPartitions(false); + + for (auto partition : masterbootrecord->TableEntries) + { + if(partition.PartitionType == 0x0) continue; // Consider marked as free + + PTR_PARTITION found_partition = (PARTITION*) malloc(sizeof(PARTITION)); + found_partition->Disk = ATAPIO_PORT::Primary | ( DEVICE_DRIVE::MASTER << 16); + printf("Disk Identifier: 0x%x\n", found_partition->Disk); + found_partition->Attributes = partition.driveAttribute; + found_partition->StartAddress = partition.LBA_partition_start; + found_partition->Sectors = partition.Number_sectors_inPartition; + found_partition->Fs_hint = partition.PartitionType; + + VirtualFileSystem::RegisterPartition(found_partition); + } + + printf("Found %d partitions on disk!\n", num_partitions); + + for (int i = 0; i < num_partitions; i++) + { + auto* partition = _partitions[i]; + // Check the fs_hint for a proper driver + if ( partition->Fs_hint != 0x06){ + printf("Assumed Unkown filesystem!\n"); + continue; + } + // Check if filesystem OK + + printf("Partition Start Address (LBA): 0x%x\n", partition->StartAddress); + bool valid = FAT::Validate(partition); + if(!valid) + { + printf("Not a valid FAT fs!\n"); + continue; + } + + // setup FileSystem Description before mounting + PFS FS_FAT = (PFS)malloc(sizeof(FILESYSTEM)); + + FAT::Info(partition, FS_FAT); + + // Mount the partition/filesystem + Mount(FS_FAT , i); + } + + + + +}; + +void VirtualFileSystem::RegisterPartition(PTR_PARTITION partition) { + _partitions[num_partitions] = partition; + num_partitions++; +} + +FILE VirtualFileSystem::OpenFile(const char* path) +{ + // See reference material (1) https://man7.org/linux/man-pages/man7/path_resolution.7.html + unsigned char device = 'a'; + char* filename = (char*)path; + char* cpy = filename; + + + if(filename[1] == ':'){ + device = filename[0]; + filename += 2; + } + + + if ( _filesystems[device - 'a']){ + // Unfortunately this way the FAT Driver doesn't know which device and which partition to read from + // leaving us hopeless of finding the file. + FILE file = _filesystems[device-'a']->Open(filename); + file.device = device; + free(cpy); + return file; + } + + free(cpy); + FILE file; + file.flags = FS_INVALID; + return file; +} + +void VirtualFileSystem::Mount(PFS filesystemDescriptor, unsigned int DeviceID) +{ + if(DeviceID < DEVICE_MAX) + if(filesystemDescriptor) + _filesystems[DeviceID] = filesystemDescriptor; +} + +void VirtualFileSystem::Unmount(unsigned int DeviceID) { + if(DeviceID < DEVICE_MAX) + _filesystems[DeviceID] = nullptr; +} + + + + + diff --git a/kernel/storage/vfs/VFS.h b/kernel/storage/vfs/vfs.h similarity index 58% rename from kernel/storage/vfs/VFS.h rename to kernel/storage/vfs/vfs.h index 095d7de..4c91792 100644 --- a/kernel/storage/vfs/VFS.h +++ b/kernel/storage/vfs/vfs.h @@ -8,10 +8,13 @@ static void initialize(); static void Mount(PFS fs, unsigned int DeviceID); static void Unmount(unsigned int DeviceID); - static void ResolvePath(Path& path); + static FILE OpenFile(const char* path); + static void RegisterPartition(PTR_PARTITION partition); private: static const unsigned int DEVICE_MAX = 26; + static const unsigned int PARTITION_MAX = 4 * DEVICE_MAX; static PFS _filesystems[DEVICE_MAX]; - + static unsigned int num_partitions; + static PTR_PARTITION _partitions [PARTITION_MAX]; }; \ No newline at end of file diff --git a/kernel/supervisorterminal/superVisorTerminal.cpp b/kernel/supervisorterminal/superVisorTerminal.cpp index f239593..bee1a3e 100644 --- a/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/kernel/supervisorterminal/superVisorTerminal.cpp @@ -1,8 +1,8 @@ #include "superVisorTerminal.h" -#include "../storage/ata pio/ataDevice.h" -#include "../partitiontable/mbr/MasterBootRecord.h" -#include "../filesystem/FAT/BiosParameterBlock.h" -#include "../filesystem/FAT/DirectoryEntry.h" +#include "../storage/ata pio/ATAPIO.h" +#include "../storage/partitiontables/mbr/MasterBootRecord.h" +#include "../storage/filesystems/FAT/BiosParameterBlock.h" +#include "../storage/filesystems/FAT/DirectoryEntry.h" bool isRunning = true; extern "C" void startSuperVisorTerminal() diff --git a/scripts/create_harddrive.sh b/scripts/create_harddrive.sh old mode 100644 new mode 100755 index 45dc117..4e0926d --- a/scripts/create_harddrive.sh +++ b/scripts/create_harddrive.sh @@ -9,11 +9,8 @@ echo "Building a FAT16 filesystem" - -su - -# dd if=/dev/zero of=diks.img bs=512 count=131072 -# fdisk disk.img +dd if=/dev/zero of=disk.img bs=512 count=131072 +fdisk disk.img # Use the following options in fdisk (Format Disk Tool) # We want to create a MBR (NOT GPT) Partition table containing 1 logical disk # with a primary FAT16 partition marked bootable @@ -42,23 +39,23 @@ su # w # Create a "block" device from the disk.img -# losetup /dev/loop9 disk.img +losetup /dev/loop9 disk.img # Format the partition on the disk as FAT16 -# mkdosfs -F16 /dev/loop9 +mkdosfs -F16 /dev/loop9 # Mount the disk to a folder on our dev machine -# mount /dev/loop9 /mnt +mount /dev/loop9 /mnt # Install the grub bootloader onto the disk -# grub-install --no-floppy --modules="normal multiboot" /dev/loop9 --target=i386-pc --boot-directory=/mnt/boot --force +grub-install --no-floppy --modules="normal multiboot" /dev/loop9 --target=i386-pc --boot-directory=/mnt/boot --force # copy the necessary OS files -# cp root/boot/myos.bin /mnt/boot/myos.bin -# cp root/boot/grub/grub.cfg /mnt/boot/grub/grub.cfg +cp root/boot/myos.bin /mnt/boot/myos.bin +cp root/boot/grub/grub.cfg /mnt/boot/grub/grub.cfg # Unmount the device -# umount /mnt +umount /mnt -# Destroy the loop device -# losetup -d /dev/loop9 +# Destroy the loop device +losetup -d /dev/loop9 -- 2.39.5 From a77621faf50bf8cc39f88a6f6bad64897c47cd76 Mon Sep 17 00:00:00 2001 From: Nigel Date: Thu, 23 Feb 2023 23:54:02 +0100 Subject: [PATCH 102/115] Shellscript improvement plus FAT driver implementations - Improved the run bash script to exit when an error occurs in one of the sub tasks - Wrote basic FAT16 functions that should give enough information to properly implement the rest of the driver - FAT structure namings are now in accordence with the microsoft spec of March 2005 --- kernel/Makefile | 6 +- kernel/kernel.cpp | 75 ++++- .../filesystems/FAT/BiosParameterBlock.h | 21 -- .../storage/filesystems/FAT/DirectoryEntry.h | 37 --- .../filesystems/FAT/ExtendBootRecord.h | 32 -- kernel/storage/filesystems/FAT/FAT.cpp | 307 ++++++++++-------- kernel/storage/filesystems/FAT/FAT.h | 156 +++++++-- kernel/storage/filesystems/FAT/msdosDate.h | 40 +++ .../storage/partitions/partitionManager.cpp | 18 + kernel/storage/partitions/partitionManager.h | 11 + kernel/storage/vfs/FileSystem.cpp | 41 --- kernel/storage/vfs/FileSystem.h | 18 - kernel/storage/vfs/Inode.cpp | 5 - kernel/storage/vfs/Inode.h | 24 -- kernel/storage/vfs/StorageTypes.h | 40 --- kernel/storage/vfs/vfs.cpp | 250 ++++++++------ kernel/storage/vfs/vfs.h | 34 +- kernel/storage/vfs/vfs_types.h | 116 +++++++ .../supervisorterminal/superVisorTerminal.cpp | 3 +- run.sh | 21 +- 20 files changed, 760 insertions(+), 495 deletions(-) delete mode 100644 kernel/storage/filesystems/FAT/BiosParameterBlock.h delete mode 100644 kernel/storage/filesystems/FAT/DirectoryEntry.h delete mode 100644 kernel/storage/filesystems/FAT/ExtendBootRecord.h create mode 100644 kernel/storage/filesystems/FAT/msdosDate.h create mode 100644 kernel/storage/partitions/partitionManager.cpp create mode 100644 kernel/storage/partitions/partitionManager.h delete mode 100644 kernel/storage/vfs/FileSystem.cpp delete mode 100644 kernel/storage/vfs/FileSystem.h delete mode 100644 kernel/storage/vfs/Inode.cpp delete mode 100644 kernel/storage/vfs/Inode.h delete mode 100644 kernel/storage/vfs/StorageTypes.h create mode 100644 kernel/storage/vfs/vfs_types.h diff --git a/kernel/Makefile b/kernel/Makefile index 4d333d1..0c8f291 100644 --- a/kernel/Makefile +++ b/kernel/Makefile @@ -1,6 +1,6 @@ -AS = ${HOME}/opt/cross/bin/i686-elf-as -CC = ${HOME}/opt/cross/bin/i686-elf-gcc -CPP = ${HOME}/opt/cross/bin/i686-elf-g++ +AS = /opt/cross/bin/i686-elf-as +CC = /opt/cross/bin/i686-elf-gcc +CPP = /opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra -I ../build/CoreLib/include BUILD_DIR = ../build/kernel OBJ_DIR = ../bin/kernel diff --git a/kernel/kernel.cpp b/kernel/kernel.cpp index 7609e71..1ca7bf7 100644 --- a/kernel/kernel.cpp +++ b/kernel/kernel.cpp @@ -15,6 +15,8 @@ #include "interrupts/idt.h" #include "serial.h" #include "storage/vfs/vfs.h" +#include "storage/filesystems/FAT/FAT.h" + extern "C" void LoadGlobalDescriptorTable(); extern "C" void jump_usermode(); @@ -54,20 +56,83 @@ extern "C" void kernel () printf("booted from floppy disk\n"); printf("Part1: %d, Part2: %d, Part3: %d\n", part1, part2 , part3); + ATAPIO::Identify(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); + auto* bpb = FAT::getBPB(false); + auto* mbr = GetPartitions(false); + auto fsType = FAT::determineFATType(bpb); + switch (fsType) { + case FAT_TYPE::FAT12: + printf("FAT12 Disk!\n"); + break; + case FAT_TYPE::FAT16: + printf("FAT16 Disk!\n"); + break; + case FAT_TYPE::FAT32: + printf("FAT32 Disk!\n"); + break; + } - VirtualFileSystem::initialize(); + // list files in root + int total_sectors = bpb->TotSec32; + int fat_size = bpb->FATSz16; + int root_dir_sectors = FAT::RootDirSize(bpb); + int first_data_sector = bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sectors ; + int first_fat_sector = bpb->RsvdSecCnt; + int data_sectors = bpb->TotSec32 - (bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sectors); + int total_clusters = data_sectors / bpb->SecPerClus; - // Try and open hello.txt file - VirtualFileSystem::OpenFile("a:hello.txt"); + + int first_root_dir_sector = first_data_sector - root_dir_sectors; + //int first_sector_of_cluster = ((cluster - 2) * bpb->SecPerClus) + first_data_sector; + uint16_t data[256]; + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, first_root_dir_sector, data); + + auto* RootDirectory = (DIR*)data; + for(int i = 0; i < sizeof(data) / sizeof (DIR); i++) + { + DIR* entry = (DIR*)((uint32_t)RootDirectory + (i * sizeof(DIR))); + + + if(entry->Name[0] == FAT::FREE_DIR || entry->Name[0] == FAT::FREE_DIR_2 || entry->Name[0] == 0xE5){ + continue; + } + + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_HIDDEN){ + continue; + } + + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_SYSTEM) + continue; + + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_VOLUME_ID){ + continue; + + } + if (!(entry->ATTR & FAT::ATTRIBUTES::ATTR_LONG_NAME)){ + for(char n : entry->Name){ + if(n == 0x20) + continue; + kterm_put(n); + } + }else{ + printf("Long file name detected!\n"); + } + printf(" [Size: %d bytes, Attributes: %x\n", entry->ATTR, entry->FileSize); + + + } - // Try and open grub.cfg file - VirtualFileSystem::OpenFile("a:boot/grub/grub.cfg"); + // VirtualFileSystem::initialize(); + + // VirtualFileSystem::open("/hello.txt", 0); + + #ifdef USERMODE_RELEASE // Lets jump into user mode jump_usermode(); diff --git a/kernel/storage/filesystems/FAT/BiosParameterBlock.h b/kernel/storage/filesystems/FAT/BiosParameterBlock.h deleted file mode 100644 index 3bf2de3..0000000 --- a/kernel/storage/filesystems/FAT/BiosParameterBlock.h +++ /dev/null @@ -1,21 +0,0 @@ -#pragma once -#include -#include "./ExtendBootRecord.h" - -struct BiosParameterBlock { - uint8_t BootLoaderCodeSection [3]; - uint8_t OEM_id [8]; - uint16_t BytesPerSector ; // I suspect would be 512 - uint8_t SectorsPerCluster ; - uint16_t ReservedSectors; - uint8_t NumberOfFileAllocationTables; // Probably equals 2 - uint16_t NumberOfDirectoryEntries; // Root directory must contain entire sectors - uint16_t TotalSectorsInLogicalVolume ; // 0 means >65535 sectors in volume , actual count can be found in LargeSectorCount - uint8_t MediaDescriptor ; // Indication the media descriptor type - uint16_t NumberOfSectorsPerFAT;// only in FAT12 / FAT 16 - uint16_t NumberOfSectorsPerTrack; - uint16_t NumberOfHeadsOnMedia; - uint32_t NumberOfHiddenSectors; - uint32_t LargeSectorCount; - ExtendedBootRecord_FAT16 ebpb; -}__attribute__((packed)); \ No newline at end of file diff --git a/kernel/storage/filesystems/FAT/DirectoryEntry.h b/kernel/storage/filesystems/FAT/DirectoryEntry.h deleted file mode 100644 index bbc3a9a..0000000 --- a/kernel/storage/filesystems/FAT/DirectoryEntry.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once -#include - -struct DirectoryEntry { - uint8_t filename [8]; - uint8_t Extension [3]; - uint8_t attribute; - uint8_t Reserved; - uint8_t creation; // Creation in tenths of a second - uint16_t CreationTime; // Time Created NOTE: Multiply the seconds by 2 - uint16_t CreationDate; // Date Created - uint16_t LastAccessDate; - uint16_t ReservedFAT32; - uint16_t LastWriteTime; - uint16_t LastWriteDate; - uint16_t StartingCluster; - uint32_t FilesizeInBytes; - -}__attribute__((packed)); - - - -typedef struct _DIRECTORY{ - uint8_t Filename[8]; - uint8_t Ext[3]; - uint8_t Attrib; - uint8_t Reserved; - uint8_t TimeCreatedMs; - uint16_t TimeCreated; - uint16_t DateCreated; - uint16_t DateLastAccessed; - uint16_t FirstClusterHiBytes; - uint16_t LastModTime; - uint16_t LastModDate; - uint16_t FirstCluster; - uint32_t FileSize; -}__attribute__((packed)) DIRECTORY, *PDIRECTORY; \ No newline at end of file diff --git a/kernel/storage/filesystems/FAT/ExtendBootRecord.h b/kernel/storage/filesystems/FAT/ExtendBootRecord.h deleted file mode 100644 index 38a40b7..0000000 --- a/kernel/storage/filesystems/FAT/ExtendBootRecord.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -#include - -struct ExtendedBootRecord_FAT16{ - uint8_t DriveNumber; - uint8_t Reserved; - uint8_t Signature; - const uint32_t VOLUME_ID_SERIAL_NUMBER; - uint8_t volume_label [11]; - uint8_t Identifier_string [8]; - uint8_t bootCode [448]; - uint16_t partitionSignature; -}__attribute__((packed)); - -struct ExtendedBootRecord_FAT32{ - uint32_t SectorsPerFAT; - uint16_t Flags; - const uint16_t FAT_VERSION_NUMBER; - uint32_t rootDirectory_clusterNumber;// Often set to 2; - uint16_t FSInfo_SectorNumber; - uint16_t backup_bpb_sectorNumber; - uint8_t Reserved [12]; - uint8_t DriveNumber; - uint8_t Reserved2; - uint8_t Signature; // must be 0x28 or 0x29 - uint32_t VOLUME_ID_SERIAL; - uint8_t volume_label[11]; - uint8_t SystemIdentifierString [8]; // ALWAYS "FAT32 " but spec says do not trust - uint8_t BootCode [420]; // NICE - uint16_t PartitionSignature; // 0xAA55 - -}__attribute__((packed)); \ No newline at end of file diff --git a/kernel/storage/filesystems/FAT/FAT.cpp b/kernel/storage/filesystems/FAT/FAT.cpp index 9161c6b..84a77f4 100644 --- a/kernel/storage/filesystems/FAT/FAT.cpp +++ b/kernel/storage/filesystems/FAT/FAT.cpp @@ -4,105 +4,198 @@ #include "FAT.h" #include "../../ata pio/ATAPIO.h" #include "../../../memory/KernelHeap.h" +#include "../../../../CoreLib/Memory.h" +#include "../../partitiontables/mbr/MasterBootRecord.h" #include - -void FAT::Read(PFILE file, unsigned char* buffer , unsigned int length) +superblock* FAT::Mount(filesystem *fs, const char* name ,vfsmount *mnt) { -} - -FILE FAT::Open(char* filename) -{ - - char* tokstate = NULL; - char* nextdir = strtok(filename, "/", &tokstate); - - while (nextdir) + if( strncmp (fs->name, "fat", 3 ) != 0 ) { - - // Read the root directory - printf("First entry to look for: %s\n", nextdir); - - - - nextdir = strtok(NULL, "/", &tokstate); + printf("Can't mount filesystem with none fat type!\n"); + return nullptr; } - FILE file; - file.flags = FS_INVALID; - return file; + superblock* sb = (superblock*) malloc(sizeof(superblock)); + directoryEntry* root = (directoryEntry*) malloc(sizeof (directoryEntry)); + root->name = (char*) name; + root->node = nullptr; + root->parent = nullptr; + dentry_operations* op = (dentry_operations*) malloc(sizeof(dentry_operations)); + op->compare = FAT::compare; + + + root->op = op; + + + mnt->mnt_count =1; + mnt->mnt_devname = "QEMU HDD"; + mnt->mnt_flags = 0; + mnt->mnt_parent = nullptr; + + mnt->root = root; + mnt->sb = sb; + + sb->type = fs; + sb->root = root; + //sb->fs_info = getBPB(); + + return sb; } - -void FAT::Write(PFILE file, unsigned char* buffer, unsigned int length) +int FAT::Read(file* file, void* buffer , int length) { - + return 0; } - -void ParseDateInteger(unsigned int date){ - printf("Date (hex) 0x%x\n", date); - unsigned int year = (date >> 9 )+ 1980; - unsigned int month = (date & 0xf0 ) >> 4; - unsigned int day = date & 0xf ; - printf("Date: (D,M,Y) %d, %d ,%d\n", day , month, year ); - +int FAT::Write(file* file, const void* buffer, int length) +{ + return 0; } +int FAT::compare (directoryEntry*, char* filename, char* filename2) +{ + // use the size of the smallest string + int a = strlen(filename); + int b = strlen(filename2); + + if( a == b ){ + return strncmp(filename, filename2, a); + } + return a-b; +} +int FAT::create(inode* dir_node, inode** target, const char* component_name){} +int FAT::lookup (inode*, inode**, const char*){} -BiosParameterBlock* getBPB(PTR_PARTITION partition, bool DEBUG =false ){ +FAT_TYPE FAT::determineFATType(BiosParameterBlock* bpb){ + int RootDirSector = ((bpb->RootEntCnt * 32) + (bpb->BytsPerSec -1)) / bpb->BytsPerSec; + int FATSz = 0; + if(bpb->FATSz16 != 0){ + FATSz = bpb->FATSz16; + } else{ + // FATSz = bpb->FATSz32; + + } + int TotSec = 0; + if(bpb->TotSec16 != 0){ + TotSec= bpb->TotSec16; + }else{ + TotSec = bpb->TotSec32; + } + + int DataSec = TotSec - (bpb->RsvdSecCnt + (bpb->NumFATs * FATSz) + RootDirSector); + int CountofClusters = DataSec / bpb->SecPerClus; + + if(CountofClusters < 4085){ + return FAT_TYPE::FAT12; + } else if (CountofClusters < 65525) { + return FAT_TYPE::FAT16; + } else{ + return FAT_TYPE::FAT32; + } +}; +BiosParameterBlock* FAT::getBPB( bool DEBUG ){ BiosParameterBlock* bpb = (BiosParameterBlock*) malloc(sizeof(BiosParameterBlock)); - - ATAPIO_PORT port = (ATAPIO_PORT)(partition->Disk & 0x01FF); - DEVICE_DRIVE drive = (DEVICE_DRIVE)(partition->Disk >> 16); - - printf("ATAPIO_PORT: 0x%x DEVICE_DRIVE: 0x%x\n",port, drive); - printf("Partition Start Address (LBA): 0x%x\n", partition->StartAddress); - - ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, partition->StartAddress, (uint16_t*) bpb); + uint16_t StartAddress = 0x00 ; + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, StartAddress, (uint16_t*) bpb); if(DEBUG) { - printf("OEM ID: %s\n", bpb->OEM_id); - printf("Bytes per sector: %d\n", bpb->BytesPerSector); - printf("Sectors per cluster: %d\n", bpb->SectorsPerCluster); - printf("Reserved sectors: %d\n", bpb->ReservedSectors); - printf("Number of FAT: %d\n", bpb->NumberOfFileAllocationTables); - printf("Number of Dir entries: %d\n", bpb->NumberOfDirectoryEntries); - printf("Total Sectors in volume: %d\n", bpb->TotalSectorsInLogicalVolume); - printf("Sectors per FAT: %d\n", bpb->NumberOfSectorsPerFAT); + printf("OEM ID: %s\n", bpb->OEMName); + printf("Bytes per sector: %d\n", bpb->BytsPerSec); + printf("Sectors per cluster: %d\n", bpb->SecPerClus); + printf("Reserved sectors: %d\n", bpb->RsvdSecCnt); + printf("Number of FAT: %d\n", bpb->NumFATs); + printf("Number of Dir entries: %d\n", bpb->RootEntCnt); + printf("Total Sectors in volume: %d\n", bpb->TotSec16 == 0 ? bpb->TotSec32 : bpb->TotSec16); + printf("Sectors per FAT: %d\n", bpb->FATSz16 ); } return bpb; } - -bool FAT::Validate(PTR_PARTITION partition ) -{ - - auto* bootParams = getBPB(partition, true); - - if(bootParams->OEM_id) { - return true; +uint16_t FAT::GetFATEntry (BiosParameterBlock* bpb, unsigned int cluster){ + int FATSz =0; + if(bpb->FATSz16 != 0){ + FATSz = bpb->FATSz16; + } else{ + //FATSz = bpb->FATSz32; } - return false; + int FATOffset = 0; + FAT_TYPE type = FAT::determineFATType(bpb); + if( type == FAT_TYPE::FAT16){ + FATOffset = cluster *2; + } else if( type == FAT_TYPE::FAT32){ + FATOffset = cluster * 4; + } + + int thisFATSecNum = bpb->RsvdSecCnt + (FATOffset / bpb->BytsPerSec); // Sector number containing the entry for the cluster + + // For any other FAT other then the default + // SectorNumber = (FATNumber * FATSz) + ThisFATSecNum + + uint16_t buff[bpb->BytsPerSec]; + + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, thisFATSecNum, buff ); + + int thisFATEntOffset = FATOffset % bpb->BytsPerSec; // offset for the entry in the sector containing the entry for the cluster + uint16_t ClusterEntryValue = 0; + // Get the FATEntry + if(type == FAT_TYPE::FAT16){ + return *((uint16_t*) &buff[thisFATEntOffset]); + + } + else{ + // FAT32 logic + return 0; + } } -void FAT::Info(_PARTITION *pPartition, PFS pSystem) { - pSystem->Read = FAT::Read; - pSystem->Write = FAT::Write; - pSystem->Open = FAT::Open; + + +uint16_t FAT::DetermineFreeSpace() +{ + // Loop through all FAT entries in all FAT's + // to construct a list of free/available clusters + // Free clusters are recorded with all 0's except on FAT32 where + // the highest order 4 bits should be ignored. + +/* + * The number of sectors reserved for each FAT (count of sectors in the BPB_FATSz16 or +BPB_FATSz32 fields) may be bigger than the actual number of sectors required for +containing the entire FAT. Therefore, there may be totally unused FAT sectors at the end of +each FAT in the FAT region of the volume. Each implementation must determine the value +for the last valid sector in the FAT using CountOfClusters (the last valid sector in the FAT +is the one containing the FAT entry numbered CountOfClusters + 1). +All sectors reserved for the FAT beyond the last valid sector (defined as the one containing +the FAT entry for the last cluster) must be set to 0x0 during volume initialization/format. + */ } -uint16_t* ReadFAT (BiosParameterBlock& bpb , PTR_PARTITION partition, bool DEBUG = false ) { - uint32_t FATAddress = partition->StartAddress + bpb.ReservedSectors ; +int FAT::GetSectorOfRootDirectory (BiosParameterBlock* bpb) +{ + return (bpb->RsvdSecCnt + (bpb->NumFATs * bpb->FATSz16)); +} + +int FAT::RootDirSize(BiosParameterBlock* bpb) +{ + int size = bpb->RootEntCnt * 32; + if((size % bpb->BytsPerSec) != 0){ + printf("ERR: Root entry count invalid!\n"); + return -1; + } + return size; +} + + + +uint16_t* ReadFAT (BiosParameterBlock& bpb , bool DEBUG = false ) { + uint32_t FATAddress = /*StartAddress*/ 0x00 + bpb.RsvdSecCnt ; uint16_t* FAT = (uint16_t*)malloc(sizeof (uint16_t) * 256); - ATAPIO_PORT port = (ATAPIO_PORT)(partition->Disk & 0x01FF); - DEVICE_DRIVE drive = (DEVICE_DRIVE)(partition->Disk >> 16); - ATAPIO::Read(port, drive, FATAddress, FAT ); + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); // Show data in terminal if(DEBUG){ @@ -115,14 +208,15 @@ uint16_t* ReadFAT (BiosParameterBlock& bpb , PTR_PARTITION partition, bool DEBUG return FAT; } -void readFile(uint32_t DataRegion, DirectoryEntry* entry, uint16_t FATentry, BiosParameterBlock& bpb ){ + +void readFile(uint32_t DataRegion, DIR* entry, uint16_t FATentry, BiosParameterBlock& bpb ){ printf("Show contents"); - printf("Start cluster of the file: 0x%x\n", entry->StartingCluster); + printf("Start cluster of the file: 0x%x\n", entry->FileSize); printf("IS it only 1 cluster? %s\n", FATentry == 0xFFFF ? "Yes" : "No"); - uint32_t sector = DataRegion + ((entry->StartingCluster - 0x02) * bpb.SectorsPerCluster); + uint32_t sector = DataRegion + ((entry->FileSize - 0x02) * bpb.SecPerClus); uint16_t dataBlob[256]; @@ -134,66 +228,21 @@ void readFile(uint32_t DataRegion, DirectoryEntry* entry, uint16_t FATentry, Bio } kterm_put('\n'); } + + + /* -void listFilesInRoot(MBR& mbr, BiosParameterBlock& bpb ){ - auto FATAddress = mbr.TableEntries[0].LBA_partition_start + bpb.ReservedSectors; - uint32_t RootDirectoryRegion = FATAddress + ( bpb.NumberOfFileAllocationTables * bpb.NumberOfSectorsPerFAT ); - uint32_t DataRegion = RootDirectoryRegion + ((bpb.NumberOfDirectoryEntries * 32) / bpb.BytesPerSector ); - uint16_t* FAT = ReadFAT(bpb, mbr); - - uint16_t data2 [256]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, RootDirectoryRegion, data2 ); - auto* RootDirectory = (DirectoryEntry*) data2; - - // List files in root - for(int i= 0; i < sizeof (data2) / sizeof (DirectoryEntry); i++ ) { - auto *entry = (DirectoryEntry * )((uint32_t) RootDirectory + (i * sizeof(DirectoryEntry))); - - if (entry->filename[0] == (uint8_t) 0x00) - continue; // There are no more entries in this directory or the entry is free - - if (entry->attribute & ATTRIBUTES::ATT_HIDDEN) - continue; - if(entry->attribute & ATTRIBUTES::ATTR_SYSTEM) - continue; - if(entry->attribute & ATTRIBUTES::ATTR_VOLUME_ID) - continue; - - // Print the filename; - for (char n: entry->filename) { - if (n == 0x20) - break; - kterm_put(n); - } - for (unsigned char n: entry->Extension) { - kterm_put(n); - } - kterm_put('\n'); - - - printf("Attribute: %x \n", entry->attribute); - printf("FileSize: %d Bytes\n", entry->FilesizeInBytes); - - if (entry->FilesizeInBytes != 0x0 && (entry->attribute != 0x10)) { - readFile(DataRegion,entry, FAT[i], bpb); - } - - } - free(FAT); - -} - -FILE fsysFatDirectory (const char* DirectoryName){ - FILE file; +file fsysFatDirectory (const char* DirectoryName){ + file file; unsigned char* buf; PDIRECTORY directory; char DosFileName[11]; - ToDosFileName(DirectoryName, DosFileName, 11); + //ToDosFileName(DirectoryName, DosFileName, 11); DosFileName[11] =0; for (int sector=0; sector <14 ; sector++){ - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mountInfo.rootOffset + sector, (uint16_t*)buf); + ATAPIO::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mountInfo.rootOffset + sector, (uint16_t*)buf); directory = (PDIRECTORY) buf; for (int i =0; i < 16; i++){ @@ -209,9 +258,9 @@ FILE fsysFatDirectory (const char* DirectoryName){ file.filelength = directory->FileSize; if(directory->Attrib == 0x10){ - file.flags = FS_DIRECTORY; + file.flags = 2; } else { - file.flags = FS_FILE; + file.flags = 1; } return file; } @@ -220,7 +269,7 @@ FILE fsysFatDirectory (const char* DirectoryName){ } // Can't find file - file.flags = FS_INVALID; + file.flags = -1; return file; } @@ -300,9 +349,9 @@ FILE fsysFatOpenSubDir(FILE kFile, const char* filename){ // set file type; if(pkDir->Attrib == 0x10){ - file.flags = FS_DIRECTORY; + file.flags = 2; } else{ - file.flags = FS_FILE; + file.flags = 1; } return file; @@ -312,7 +361,7 @@ FILE fsysFatOpenSubDir(FILE kFile, const char* filename){ } } // unable to find file - file.flags = FS_INVALID; + file.flags = -1; return file; } - */ +*/ diff --git a/kernel/storage/filesystems/FAT/FAT.h b/kernel/storage/filesystems/FAT/FAT.h index bf8cce9..388811e 100644 --- a/kernel/storage/filesystems/FAT/FAT.h +++ b/kernel/storage/filesystems/FAT/FAT.h @@ -2,48 +2,152 @@ // Created by nigel on 21/02/23. // #pragma once -#include "ExtendBootRecord.h" -#include "BiosParameterBlock.h" -#include "DirectoryEntry.h" -#include "../../vfs/StorageTypes.h" +#include "../../vfs/vfs_types.h" +#include "../../vfs/vfs_types.h" +#include "../../partitiontables/mbr/MasterBootRecord.h" -// Date Format -// [0..4] Day -// [5..8] Month -// [9..15] Year +struct ExtendedBootRecord_FAT16{ + uint8_t DrvNum; + uint8_t Reserved1; + uint8_t BootSig; + const uint32_t VolID; + uint8_t VolLab [11]; + uint8_t FilSysType [8]; + uint8_t bootCode [448]; + uint16_t Signature_word; + uint8_t SecRmndr[512]; +}__attribute__((packed)); -// Time Format -// [0..4] Seconds -// [5..10] Minute -// [11..15] Hour +struct ExtendedBootRecord_FAT32{ + uint32_t SectorsPerFAT; + uint16_t Flags; + const uint16_t FAT_VERSION_NUMBER; + uint32_t rootDirectory_clusterNumber;// Often set to 2; + uint16_t FSInfo_SectorNumber; + uint16_t backup_bpb_sectorNumber; + uint8_t Reserved [12]; + uint8_t DriveNumber; + uint8_t Reserved2; + uint8_t Signature; // must be 0x28 or 0x29 + uint32_t VOLUME_ID_SERIAL; + uint8_t volume_label[11]; + uint8_t SystemIdentifierString [8]; // ALWAYS "FAT32 " but spec says do not trust + uint8_t BootCode [420]; // NICE + uint16_t PartitionSignature; // 0xAA55 +}__attribute__((packed)); + +struct BiosParameterBlock { + uint8_t jmpBoot[3]; + uint8_t OEMName [8]; + uint16_t BytsPerSec ; // I suspect would be 512 + uint8_t SecPerClus ; + uint16_t RsvdSecCnt; + uint8_t NumFATs; // Probably equals 2 + uint16_t RootEntCnt; // Root directory must contain entire sectors + uint16_t TotSec16 ; // 0 means >65535 sectors in volume , actual count can be found in LargeSectorCount + uint8_t Media ; // Indication the media descriptor type + uint16_t FATSz16;// only in FAT12 / FAT 16 + uint16_t SecPerTrk; + uint16_t NumHeads; + uint32_t HiddSec; + uint32_t TotSec32; + ExtendedBootRecord_FAT16 ebpb; +}__attribute__((packed)); + +struct DIR { + uint8_t Name [11]; + uint8_t ATTR ; + uint8_t NTRes; + uint8_t CrtTimeTenth; // File Creation time component - count of tenths of a second (between 0 and 199) + uint16_t CrtTime; // Creation time. Granularity is 2 seconds + uint16_t CrtDate; // Creation date. + uint16_t LstAccDate; // Last Access Date (Last read or write date) + uint16_t FstClusHi; // High Word of first data cluster for file/directory described + uint16_t WrtTime; // Last Modification time | Must equal CrtTime + uint16_t WrtDate; // Last Modification date | Must equal CrtDate + uint16_t FstClusLO; // Low word of first data cluster for file/directory described + uint32_t FileSize; // size in bytes of file/directory described +}__attribute__((packed)); + +typedef struct _DIRECTORY{ + uint8_t Filename[8]; + uint8_t Ext[3]; + uint8_t Attrib; + uint8_t Reserved; + uint8_t TimeCreatedMs; + uint16_t TimeCreated; + uint16_t DateCreated; + uint16_t DateLastAccessed; + uint16_t FirstClusterHiBytes; + uint16_t LastModTime; + uint16_t LastModDate; + uint16_t FirstCluster; + uint32_t FileSize; +}__attribute__((packed)) DIRECTORY, *PDIRECTORY; + +enum struct FAT_TYPE{ + FAT12, + FAT16, + FAT32, + VFAT, + UNKOWN +}; class FAT { public: + // Wanted API for vfs + static file Open(char* filename); + static int close(file* file); + static int Read(file* file, void* buffer , int length); + static int Write(file* file, const void* buffer, int length); + static int create(inode* dir_node, inode** target, const char* component_name); + static int lookup(inode* , inode**, const char*); + static int compare(directoryEntry* , char* , char*); + static superblock* Mount(filesystem* fs, const char* name ,vfsmount* mount); - static bool Validate(PTR_PARTITION partition ); + // TEMP + static void listFilesInRoot(MBR* mbr, BiosParameterBlock* bpb ); + static BiosParameterBlock* getBPB( bool DEBUG =false ); + static FAT_TYPE determineFATType(BiosParameterBlock* bpb); + static uint16_t GetFATEntry(BiosParameterBlock*, unsigned int); + static uint16_t DetermineFreeSpace(); + static int GetSectorOfRootDirectory(BiosParameterBlock*); + static int RootDirSize(BiosParameterBlock*); - static FILE Open(char* filename); - static void Read(PFILE file, unsigned char* buffer , unsigned int length); - static void Write(PFILE file, unsigned char* buffer, unsigned int length); + static const int FREE = 0x0000; + static const int ALLOCATED = 0x0002; + static const int BAD = 0xFFF7; + static const int EOF = 0xFFFF; - static void Info(_PARTITION *pPartition, PFS pSystem); + static const int ClnShutBitMask = 0x8000; + static const int HrdErrBitMask = 0x4000; + + static const char DOS_TRAILING_SPACE = 0x20; + static const char FREE_DIR = 0xE5; // If KANJI charset 0x05 + static const char FREE_DIR_2 = 0x00; // All directories after this are free including this one -private: - enum struct TYPE{ - FAT, - FAT16, - FAT32, - VFAT - }; enum ATTRIBUTES { ATTR_READ_ONLY = 0x01, - ATT_HIDDEN = 0x02, + ATTR_HIDDEN = 0x02, ATTR_SYSTEM = 0x04, ATTR_VOLUME_ID = 0x08, ATTR_DIRECTORY = 0x10, - ATTR_ARCHIVE = 0x20 + ATTR_ARCHIVE = 0x20, + ATTR_LONG_NAME = (ATTR_READ_ONLY | ATTR_HIDDEN | ATTR_SYSTEM | ATTR_VOLUME_ID) }; + +private: + + + enum ENTRY_SIZE { + FAT12 = 12, + FAT16 = 16, + FAT32 = 32 + }; + + + }; diff --git a/kernel/storage/filesystems/FAT/msdosDate.h b/kernel/storage/filesystems/FAT/msdosDate.h new file mode 100644 index 0000000..c1fff64 --- /dev/null +++ b/kernel/storage/filesystems/FAT/msdosDate.h @@ -0,0 +1,40 @@ +// +// Created by nigel on 23/02/23. +// + +#pragma once + +#include "../../../terminal/kterm.h" + +// Date Format +// [0..4] Day +// [5..8] Month +// [9..15] Year +class MSDOSDATE { + static void ParseDate(unsigned int date){ + printf("Date (hex) 0x%x\n", date); + unsigned int year = (date >> 9 )+ 1980; + unsigned int month = (date & 0xf0 ) >> 4; + unsigned int day = date & 0xf ; + printf("Date: (D,M,Y) %d, %d ,%d\n", day , month, year ); + } +}; + + + +// Time Format +// [0..4] Seconds +// [5..10] Minute +// [11..15] Hour +class MSDOSTIME { + static void ParseTime(unsigned int time) + { + printf("Time (hex) 0x%x\n", time); + unsigned int seconds = ( time & 0x0f) * 2; + unsigned int minutes = (time & 0xf0); + unsigned int hours = (time & 0xf00); + printf("Time (H:M:S) %d:%d:%d\n", hours, minutes, seconds); + } +}; + + diff --git a/kernel/storage/partitions/partitionManager.cpp b/kernel/storage/partitions/partitionManager.cpp new file mode 100644 index 0000000..ef62452 --- /dev/null +++ b/kernel/storage/partitions/partitionManager.cpp @@ -0,0 +1,18 @@ +// +// Created by nigel on 23/02/23. +// + +#include "partitionManager.h" + +bool partitionManager::Validate( ) +{ + + //auto* bootParams = getBPB(this, true); + + //if(bootParams->OEM_id) { + // return true; + //} + + return true; + +} diff --git a/kernel/storage/partitions/partitionManager.h b/kernel/storage/partitions/partitionManager.h new file mode 100644 index 0000000..56cbee9 --- /dev/null +++ b/kernel/storage/partitions/partitionManager.h @@ -0,0 +1,11 @@ +// +// Created by nigel on 23/02/23. +// +#pragma once + +class partitionManager { +public: + static bool Validate(); + +}; + diff --git a/kernel/storage/vfs/FileSystem.cpp b/kernel/storage/vfs/FileSystem.cpp deleted file mode 100644 index fe92789..0000000 --- a/kernel/storage/vfs/FileSystem.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// -// Created by nigel on 21/02/23. -// -#include "FileSystem.h" - -void FileSystem::WriteFile(int file, unsigned char* buffer, unsigned int length) { - -} - -void FileSystem::ReadFile(int file, unsigned char* buffer, unsigned int length) { - -} - -FILE FileSystem::OpenFile(const char* fname){ - if(fname){ - unsigned char device = 'a'; - char* filename = (char*) fname; - - if(fname[1]== ':'){ - device = fname[0]; - filename += 2; // strip the volume component from the path - } - - if(_filesystems[device - 'a']){ - FILE file = _filesystems[device-'a']->Open(filename); - file.device = device; - return file; - } - } - FILE file; - file.flags = FS_INVALID; - return file; -} - -void FileSystem::CloseFile(PFILE file) { - if(file->device < DEVICE_MAX){ - // _filesystems[file->device]->Close(file); - } -} - - diff --git a/kernel/storage/vfs/FileSystem.h b/kernel/storage/vfs/FileSystem.h deleted file mode 100644 index 939eab9..0000000 --- a/kernel/storage/vfs/FileSystem.h +++ /dev/null @@ -1,18 +0,0 @@ -// -// Created by nigel on 21/02/23. -// -#pragma once -#include "StorageTypes.h" - -class FileSystem { -public: - static void WriteFile(PFILE file, unsigned char* beffer, unsigned int length); - static void ReadFile(PFILE file, unsigned char* buffer, unsigned int length); - static FILE OpenFile(const char* fname); - static void CloseFile(PFILE file); - - -}; - - - diff --git a/kernel/storage/vfs/Inode.cpp b/kernel/storage/vfs/Inode.cpp deleted file mode 100644 index a01eebb..0000000 --- a/kernel/storage/vfs/Inode.cpp +++ /dev/null @@ -1,5 +0,0 @@ -// -// Created by nigel on 21/02/23. -// - -#include "Inode.h" diff --git a/kernel/storage/vfs/Inode.h b/kernel/storage/vfs/Inode.h deleted file mode 100644 index 59d7ee5..0000000 --- a/kernel/storage/vfs/Inode.h +++ /dev/null @@ -1,24 +0,0 @@ -// -// Created by nigel on 21/02/23. -// -#pragma once -enum struct NODE_TYPE { - FILESYSTEM, - FILE, - DIRECTORY -}; - -enum struct PERMISSIONS { - READ, - WRITE, - EXECUTE -}; - -struct Inode { - NODE_TYPE type; - PERMISSIONS permissions; - Inode* Parent; - Inode* sibling; -}; - - diff --git a/kernel/storage/vfs/StorageTypes.h b/kernel/storage/vfs/StorageTypes.h deleted file mode 100644 index 5acdc27..0000000 --- a/kernel/storage/vfs/StorageTypes.h +++ /dev/null @@ -1,40 +0,0 @@ -// -// Created by nigel on 21/02/23. -// -#pragma once -#include - -enum FS_TYPES { - FS_FILE =0, - FS_DIRECTORY =1, - FS_INVALID=2 -}; - -typedef struct _FILE { - char name [32]; - uint32_t flags; - uint32_t filelength; - uint32_t id; - uint32_t eof; - uint32_t position; - uint32_t currentCluster; - uint32_t device; -}FILE, *PFILE; - -typedef struct _FILE_SYSTEM{ - char name[8]; - FILE (*Directory) (const char* Directoryname); - void (*Mount) (); - void (*Read) (PFILE file, unsigned char* buffer, unsigned int length); - void (*Write)(PFILE file, unsigned char* buffer, unsigned int length); - void (*Close) (PFILE); - FILE (*Open) (char* filename); -}FILESYSTEM, *PFS; - -typedef struct _PARTITION { - uint32_t Disk; - uint32_t StartAddress; - uint32_t Sectors; - uint8_t Fs_hint; - uint8_t Attributes; -}PARTITION, *PTR_PARTITION; diff --git a/kernel/storage/vfs/vfs.cpp b/kernel/storage/vfs/vfs.cpp index 5597ebc..7d67144 100644 --- a/kernel/storage/vfs/vfs.cpp +++ b/kernel/storage/vfs/vfs.cpp @@ -4,127 +4,183 @@ #include "../ata pio/ATAPIO.h" #include "../partitiontables/mbr/MasterBootRecord.h" #include "../filesystems/FAT/FAT.h" -#include "StorageTypes.h" - +#include "vfs_types.h" +#include "../../../CoreLib/Memory.h" #include -PFS VirtualFileSystem::_filesystems[VirtualFileSystem::DEVICE_MAX]; -PTR_PARTITION VirtualFileSystem::_partitions [VirtualFileSystem::PARTITION_MAX]; -unsigned int VirtualFileSystem::num_partitions = 0; +vfsmount* VirtualFileSystem::rootfs; +int VirtualFileSystem::mount_number = 0; +int VirtualFileSystem::superblock_number =0; +int VirtualFileSystem::filesystem_number =0; + +filesystem* VirtualFileSystem::filesystems[4]; +superblock* VirtualFileSystem::superblocks[8]; +vfsmount* VirtualFileSystem::mounts[12]; + +void VirtualFileSystem::Mount(filesystem* fs, const char* name) +{ + vfsmount* mnt_point = (vfsmount*) malloc(sizeof(vfsmount)); + superblock* sb = fs->mount(fs, name, mnt_point); + + mounts[mount_number++] = mnt_point; + superblocks[superblock_number++] = sb; + + rootfs = mnt_point; +} void VirtualFileSystem::initialize() { + // TODO: setup memory pools etc to speed things up + // a bit + // TODO: Add a devfs, procfs etc... - // Mount the boot disk - // NOTE: we assume for now that it is the only disk in the system - // This information could possibly be had from the bootloader (GRUB) - // We als assume it is the primary device on the Master port. - ATAPIO::Soft_Reset(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); - bool isAvailable = ATAPIO::Identify(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); - if(!isAvailable){ - // PANIC!!! - printf("Failed to mount root filesystem!\n"); - return; - } - - auto masterbootrecord = GetPartitions(false); - - for (auto partition : masterbootrecord->TableEntries) - { - if(partition.PartitionType == 0x0) continue; // Consider marked as free - - PTR_PARTITION found_partition = (PARTITION*) malloc(sizeof(PARTITION)); - found_partition->Disk = ATAPIO_PORT::Primary | ( DEVICE_DRIVE::MASTER << 16); - printf("Disk Identifier: 0x%x\n", found_partition->Disk); - found_partition->Attributes = partition.driveAttribute; - found_partition->StartAddress = partition.LBA_partition_start; - found_partition->Sectors = partition.Number_sectors_inPartition; - found_partition->Fs_hint = partition.PartitionType; - - VirtualFileSystem::RegisterPartition(found_partition); - } - - printf("Found %d partitions on disk!\n", num_partitions); - - for (int i = 0; i < num_partitions; i++) - { - auto* partition = _partitions[i]; - // Check the fs_hint for a proper driver - if ( partition->Fs_hint != 0x06){ - printf("Assumed Unkown filesystem!\n"); - continue; - } - // Check if filesystem OK - - printf("Partition Start Address (LBA): 0x%x\n", partition->StartAddress); - bool valid = FAT::Validate(partition); - if(!valid) - { - printf("Not a valid FAT fs!\n"); - continue; - } - - // setup FileSystem Description before mounting - PFS FS_FAT = (PFS)malloc(sizeof(FILESYSTEM)); - - FAT::Info(partition, FS_FAT); - - // Mount the partition/filesystem - Mount(FS_FAT , i); - } - - + filesystem* fat_fs = (filesystem*) malloc(sizeof (filesystem)); + fat_fs->name = "fat"; + fat_fs->mount = FAT::Mount; + //register_filesystem(fat_fs); + // Mount the bootdrive + // NOTE: for now will hardcode this + Mount(fat_fs, "/"); }; -void VirtualFileSystem::RegisterPartition(PTR_PARTITION partition) { - _partitions[num_partitions] = partition; - num_partitions++; + +int VirtualFileSystem::register_filesystem(struct filesystem* fs) { + // register the filesystem to the kernel. + filesystems[filesystem_number] = fs; + filesystem_number++; + + } -FILE VirtualFileSystem::OpenFile(const char* path) -{ +struct file* VirtualFileSystem::open(const char* pathname, int flags){ + // 1. Lookup pathname from the root node + // 2. Create a new file descriptor for this v_node if found. + // 3. Create a new file if O_CREATE is specified in the flags. + // See reference material (1) https://man7.org/linux/man-pages/man7/path_resolution.7.html - unsigned char device = 'a'; - char* filename = (char*)path; - char* cpy = filename; - - if(filename[1] == ':'){ - device = filename[0]; - filename += 2; + // FILE file = ->Open(filename); + if(pathname[0] != '/'){ + printf("We won't handle relative paths yet!"); + file file; + file.flags = 1; + return &file; } - if ( _filesystems[device - 'a']){ - // Unfortunately this way the FAT Driver doesn't know which device and which partition to read from - // leaving us hopeless of finding the file. - FILE file = _filesystems[device-'a']->Open(filename); - file.device = device; - free(cpy); - return file; + + auto* dentry = rootfs->root; + + int result = dentry->op->compare(dentry, "/", dentry->name); + if(result != 0 ){ + printf("rootfs not called / \n"); + file file; + file.flags = 1; + return &file; } - free(cpy); - FILE file; - file.flags = FS_INVALID; - return file; + char* tokstate = nullptr; + auto nextdir = strtok ((char*)pathname, "/", &tokstate ); + while (nextdir) + { + printf("Look for dentry: %s\n", nextdir); + // look to its children + if (dentry->children ) { + printf("No children | children unknown!\n"); + break; + } + if (dentry->op->compare(dentry, nextdir, dentry->name)) + { + // file found + nextdir = strtok(nullptr, "/", &tokstate); + } + + } + + file file; + file.flags = 1; + return &file; } -void VirtualFileSystem::Mount(PFS filesystemDescriptor, unsigned int DeviceID) -{ - if(DeviceID < DEVICE_MAX) - if(filesystemDescriptor) - _filesystems[DeviceID] = filesystemDescriptor; +int VirtualFileSystem::close (struct file* file){ + // 1. release the file descriptor +} +int VirtualFileSystem::write(struct file* file, const void* buf, size_t len){ + // 1. Write len bytes from buf to the opened file. + // 2. return written size or error code if an error occurs +} +int VirtualFileSystem::read (struct file* file, void* buf, size_t len){ + // 1. read min(len, readable file data size) bytes ro buf from the opened file. + // 2. return read size or error code if an error occurs } -void VirtualFileSystem::Unmount(unsigned int DeviceID) { - if(DeviceID < DEVICE_MAX) - _filesystems[DeviceID] = nullptr; +/* + +void fs_discovery(){ + + + // Mount the boot disk + // NOTE: we assume for now that it is the only disk in the system + // This information could possibly be had from the bootloader (GRUB) + // We als assume it is the primary device on the Master port. + ATAPIO::Soft_Reset(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); + bool isAvailable = ATAPIO::Identify(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); + if(!isAvailable){ + // PANIC!!! + printf("Failed to mount root filesystem!\n"); + return; + } + + auto masterbootrecord = GetPartitions(false); + + for (auto partition : masterbootrecord->TableEntries) + { + if(partition.PartitionType == 0x0) continue; // Consider marked as free + + PTR_PARTITION found_partition = (PARTITION*) malloc(sizeof(PARTITION)); + found_partition->Disk = ATAPIO_PORT::Primary | ( DEVICE_DRIVE::MASTER << 16); + printf("Disk Identifier: 0x%x\n", found_partition->Disk); + found_partition->Attributes = partition.driveAttribute; + found_partition->StartAddress = partition.LBA_partition_start; + found_partition->Sectors = partition.Number_sectors_inPartition; + found_partition->Fs_hint = partition.PartitionType; + + + } + + printf("Found %d partitions on disk!\n", num_partitions); + + for (int i = 0; i < num_partitions; i++) + { + auto* partition = _partitions[i]; + // Check the fs_hint for a proper driver + if ( partition->Fs_hint != 0x06){ + printf("Assumed Unkown filesystem!\n"); + continue; + } + // Check if filesystem OK + + printf("Partition Start Address (LBA): 0x%x\n", partition->StartAddress); + bool valid = FAT::Validate(partition); + if(!valid) + { + printf("Not a valid FAT fs!\n"); + continue; + } + + // setup FileSystem Description before mounting + PFS FS_FAT = (PFS)malloc(sizeof(FILESYSTEM)); + + FAT::Info(partition, FS_FAT); + + // Mount the partition/filesystem + } + + } - - +*/ \ No newline at end of file diff --git a/kernel/storage/vfs/vfs.h b/kernel/storage/vfs/vfs.h index 4c91792..804f09a 100644 --- a/kernel/storage/vfs/vfs.h +++ b/kernel/storage/vfs/vfs.h @@ -1,20 +1,32 @@ #pragma once #include #include "../../../CoreLib/Path.h" -#include "StorageTypes.h" +#include "vfs_types.h" +#include "vfs_types.h" class VirtualFileSystem { public: static void initialize(); - static void Mount(PFS fs, unsigned int DeviceID); - static void Unmount(unsigned int DeviceID); - static FILE OpenFile(const char* path); - static void RegisterPartition(PTR_PARTITION partition); + static void Mount(filesystem* fs, const char* name); + + static int register_filesystem(struct filesystem* fs); + + static struct file* open(const char* pathname, int flags); + static int close(struct file* file); + static int write(struct file* file, const void* buf, size_t len); + static int read(struct file* file, void* buf, size_t len); private: - static const unsigned int DEVICE_MAX = 26; - static const unsigned int PARTITION_MAX = 4 * DEVICE_MAX; - static PFS _filesystems[DEVICE_MAX]; - static unsigned int num_partitions; - static PTR_PARTITION _partitions [PARTITION_MAX]; - }; \ No newline at end of file + static vfsmount* rootfs; + + + static int mount_number; + static int superblock_number; + static int filesystem_number; + + static filesystem* filesystems[]; + static superblock* superblocks[]; + static vfsmount* mounts[]; + + }; + diff --git a/kernel/storage/vfs/vfs_types.h b/kernel/storage/vfs/vfs_types.h new file mode 100644 index 0000000..c989dbe --- /dev/null +++ b/kernel/storage/vfs/vfs_types.h @@ -0,0 +1,116 @@ +// +// Created by nigel on 21/02/23. +// +#pragma once +// grasslab.github.io/osdi/en/labs/lab7.html +#include +#include + +struct inode_operations; +struct vfsmount; +struct superblock; +struct inode; +struct dentry_operations; +struct directoryEntry; +struct filesystem; +struct superblock; +struct file; + +struct file_operations{ + int(*write) (file* file, const void* buf, size_t len); + int(*read) (file* file, void* buf, size_t len); +}; +struct inode_operations { + int (*create)(inode*, directoryEntry*, const char* ); + directoryEntry* (*lookup)(inode* , directoryEntry*); + int (*link)(directoryEntry*, inode* , directoryEntry*); + int (*unlink)(inode*, directoryEntry*); + int (*symlink)(inode*, directoryEntry*); + int (*mkdir)(inode*, directoryEntry*, const char*); + int (*rmdir)(inode*, directoryEntry*); + int (*rename)(inode*, directoryEntry*, inode*, directoryEntry*); + void (*truncate)(inode*); + int (*permission)(inode*, int); + int (*setattr)(directoryEntry, unsigned long*); + int (*getattr)(vfsmount* mnt, directoryEntry*, unsigned long*); +}; +// Describes a mount +struct vfsmount { + vfsmount* mnt_parent; // fs we are mounted on + directoryEntry* mountpoint; // dentry of mount point + directoryEntry* root; // root of the mounted tree + superblock* sb; // pointer to the superblock + unsigned int mnt_count; // keep track of users of this structure + int mnt_flags; + char* mnt_devname; // name of device eg /dev/dsk/hda1 + +}; +struct superblock; +// Represents a filesystem object (i.e. a file or directory or device) +struct inode { + unsigned long mode; // access permissions + unsigned long uid; // user id owner + unsigned long gid; // group id owner + unsigned int flags; + inode_operations* i_op; // operations possible on inode + superblock* sb; + unsigned long ino; // unique number of this inode + unsigned int links; // number of hard links + void* device; + unsigned long size; // size of inode contents in bytes + unsigned long atime; // Access time + unsigned long mtime; // Modify time + unsigned long ctime; // Creation time + unsigned short bytes; // bytes consumed + file_operations* fop; + void* internal; // point to underlying representation of this virtual node (e.g. FAT entry or Directory Entry) +}; +// Represents the possible operations on a directory entry +struct dentry_operations +{ + int (*compare)(directoryEntry*, char*, char* ); + int (*o_delete)(directoryEntry*); + void (*release)(directoryEntry*); + void (*iput)(directoryEntry*, inode* ); + +}; +// Represents the name of files in the filesystem +// it identifies the file that an inode represents +struct directoryEntry { + char* name; // name of the file on the disk + directoryEntry* parent; // parent of the file + inode* node; // node belongs to... + dentry_operations* op; + directoryEntry* children[]; + +}; +// Represents a filesystem type +struct filesystem { + const char* name; + superblock* (*mount)(filesystem* self, const char* name, vfsmount* mnt); +}; + +// Represents a mounted filesystem +struct superblock { + + void* device; // device associated with the filesystem + unsigned long blocksize; + unsigned long maxbytes; + filesystem* type; + unsigned long magic; // IDK + directoryEntry* root; // Root dentry + int count; // IDK + void* fs_info; // pointer to raw filesystem info + dentry_operations* d_op; + inode* inodes[]; +}; + +// Represents an opened file +struct file { + inode* root; + size_t f_pos; // The next read/write position of this file descriptor; + file_operations* f_ops; + int flags; +}; + + diff --git a/kernel/supervisorterminal/superVisorTerminal.cpp b/kernel/supervisorterminal/superVisorTerminal.cpp index bee1a3e..ea6e9b2 100644 --- a/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/kernel/supervisorterminal/superVisorTerminal.cpp @@ -1,8 +1,7 @@ #include "superVisorTerminal.h" #include "../storage/ata pio/ATAPIO.h" #include "../storage/partitiontables/mbr/MasterBootRecord.h" -#include "../storage/filesystems/FAT/BiosParameterBlock.h" -#include "../storage/filesystems/FAT/DirectoryEntry.h" +#include "../storage/filesystems/FAT/FAT.h" bool isRunning = true; extern "C" void startSuperVisorTerminal() diff --git a/run.sh b/run.sh index a97e584..99d34c5 100755 --- a/run.sh +++ b/run.sh @@ -1,12 +1,25 @@ #!/bin/bash +PROC=$$ +# Build the Corelib static library +(cd CoreLib +if ! make; then + echo "Build failed!" + kill -10 $PROC +fi) -cd CoreLib -make -cd ../kernel +# Build the kernel image +(cd kernel make clean make -cd .. +if ! make; then + echo "Build failed!" + kill -10 $PROC +fi) ./scripts/update_harddrive.sh + + + ./scripts/run_qemu.sh + -- 2.39.5 From 644ff5b1f5555372336e18539b13867f783fa80b Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 24 Feb 2023 21:31:20 +0100 Subject: [PATCH 103/115] Adding subdir functionality Added FAT16 driver ability to list subdir entries Removed structure of FAT32 (we won't be using it anytime soon) --- kernel/kernel.cpp | 11 ++-- kernel/storage/filesystems/FAT/FAT.cpp | 86 +++++++++++++++++++++----- kernel/storage/filesystems/FAT/FAT.h | 41 ++---------- 3 files changed, 84 insertions(+), 54 deletions(-) diff --git a/kernel/kernel.cpp b/kernel/kernel.cpp index 1ca7bf7..f10b3cf 100644 --- a/kernel/kernel.cpp +++ b/kernel/kernel.cpp @@ -78,7 +78,6 @@ extern "C" void kernel () int fat_size = bpb->FATSz16; int root_dir_sectors = FAT::RootDirSize(bpb); int first_data_sector = bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sectors ; - int first_fat_sector = bpb->RsvdSecCnt; int data_sectors = bpb->TotSec32 - (bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sectors); int total_clusters = data_sectors / bpb->SecPerClus; @@ -98,6 +97,7 @@ extern "C" void kernel () continue; } + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_HIDDEN){ continue; } @@ -105,9 +105,9 @@ extern "C" void kernel () if(entry->ATTR & FAT::ATTRIBUTES::ATTR_SYSTEM) continue; + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_VOLUME_ID){ continue; - } if (!(entry->ATTR & FAT::ATTRIBUTES::ATTR_LONG_NAME)){ for(char n : entry->Name){ @@ -116,10 +116,13 @@ extern "C" void kernel () kterm_put(n); } }else{ - printf("Long file name detected!\n"); + printf("Long file name detected!"); } - printf(" [Size: %d bytes, Attributes: %x\n", entry->ATTR, entry->FileSize); + printf(" [Size: %d bytes, Attributes: %d]\n", entry->ATTR, entry->FileSize); + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_DIRECTORY ){ + FAT::OpenSubdir(entry, bpb); + } } diff --git a/kernel/storage/filesystems/FAT/FAT.cpp b/kernel/storage/filesystems/FAT/FAT.cpp index 84a77f4..7a635e4 100644 --- a/kernel/storage/filesystems/FAT/FAT.cpp +++ b/kernel/storage/filesystems/FAT/FAT.cpp @@ -113,12 +113,7 @@ BiosParameterBlock* FAT::getBPB( bool DEBUG ){ return bpb; } uint16_t FAT::GetFATEntry (BiosParameterBlock* bpb, unsigned int cluster){ - int FATSz =0; - if(bpb->FATSz16 != 0){ - FATSz = bpb->FATSz16; - } else{ - //FATSz = bpb->FATSz32; - } + int FATSz = bpb->FATSz16; int FATOffset = 0; FAT_TYPE type = FAT::determineFATType(bpb); @@ -130,7 +125,7 @@ uint16_t FAT::GetFATEntry (BiosParameterBlock* bpb, unsigned int cluster){ int thisFATSecNum = bpb->RsvdSecCnt + (FATOffset / bpb->BytsPerSec); // Sector number containing the entry for the cluster - // For any other FAT other then the default + // For any other FAT other than the default // SectorNumber = (FATNumber * FATSz) + ThisFATSecNum uint16_t buff[bpb->BytsPerSec]; @@ -179,14 +174,10 @@ int FAT::GetSectorOfRootDirectory (BiosParameterBlock* bpb) return (bpb->RsvdSecCnt + (bpb->NumFATs * bpb->FATSz16)); } -int FAT::RootDirSize(BiosParameterBlock* bpb) +unsigned int FAT::RootDirSize(BiosParameterBlock* bpb) { - int size = bpb->RootEntCnt * 32; - if((size % bpb->BytsPerSec) != 0){ - printf("ERR: Root entry count invalid!\n"); - return -1; - } - return size; + return ((bpb->RootEntCnt * 32) + (bpb->BytsPerSec -1)) /bpb->BytsPerSec; + } @@ -208,6 +199,73 @@ uint16_t* ReadFAT (BiosParameterBlock& bpb , bool DEBUG = false ) { return FAT; } +void FAT::OpenSubdir(DIR* directory, BiosParameterBlock* bpb ){ + + unsigned int cluster = directory->FstClusLo; + printf("Listing contents of " ); + + for(unsigned char n : directory->Name){ + if(n == 0x20) + continue; + kterm_put(n); + } + kterm_put('\n'); + printf("FsCluHi: 0x%x , FsCluLo: 0x%x\n", directory->FstClusHi, directory->FstClusLo); + printf("Cluster: 0x%x\n", cluster); + unsigned int FATEntry = FAT::GetFATEntry(bpb, cluster); + printf("FAT_Entry: 0x%x\n", FATEntry); + + unsigned int root_dir_sectors = FAT::RootDirSize(bpb); + unsigned int fat_size = bpb->FATSz16; + unsigned int first_data_sector = bpb->RsvdSecCnt + ( bpb->NumFATs * fat_size) + root_dir_sectors; + unsigned int first_directory_sector = ((cluster - 2) * bpb->SecPerClus) + first_data_sector; + printf("Directory first sector 0x%x\n" , first_directory_sector); + uint16_t data[256]; + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, first_directory_sector, data); + + auto* directoryContents = (DIR*) data; + for(int i = 0; i < sizeof(data) / sizeof(DIR); i++){ + DIR* entry = (DIR*)((uint32_t)directoryContents + (i * sizeof(DIR))); + + if(entry->Name[0] == FAT::FREE_DIR || entry->Name[0] == FAT::FREE_DIR_2 || entry->Name[0] == 0xE5) + continue; + + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_HIDDEN){ + continue; + } + + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_SYSTEM) + continue; + + + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_VOLUME_ID){ + continue; + } + + if (!(entry->ATTR & FAT::ATTRIBUTES::ATTR_LONG_NAME)){ + for(char n : entry->Name){ + if(n == 0x20) + continue; + kterm_put(n); + } + kterm_put('\n'); + }else{ + printf("LFN\n"); + } + + + + + + + + + } + + + +} + void readFile(uint32_t DataRegion, DIR* entry, uint16_t FATentry, BiosParameterBlock& bpb ){ printf("Show contents"); diff --git a/kernel/storage/filesystems/FAT/FAT.h b/kernel/storage/filesystems/FAT/FAT.h index 388811e..1627aab 100644 --- a/kernel/storage/filesystems/FAT/FAT.h +++ b/kernel/storage/filesystems/FAT/FAT.h @@ -18,25 +18,6 @@ struct ExtendedBootRecord_FAT16{ uint8_t SecRmndr[512]; }__attribute__((packed)); -struct ExtendedBootRecord_FAT32{ - uint32_t SectorsPerFAT; - uint16_t Flags; - const uint16_t FAT_VERSION_NUMBER; - uint32_t rootDirectory_clusterNumber;// Often set to 2; - uint16_t FSInfo_SectorNumber; - uint16_t backup_bpb_sectorNumber; - uint8_t Reserved [12]; - uint8_t DriveNumber; - uint8_t Reserved2; - uint8_t Signature; // must be 0x28 or 0x29 - uint32_t VOLUME_ID_SERIAL; - uint8_t volume_label[11]; - uint8_t SystemIdentifierString [8]; // ALWAYS "FAT32 " but spec says do not trust - uint8_t BootCode [420]; // NICE - uint16_t PartitionSignature; // 0xAA55 - -}__attribute__((packed)); - struct BiosParameterBlock { uint8_t jmpBoot[3]; uint8_t OEMName [8]; @@ -66,25 +47,10 @@ struct DIR { uint16_t FstClusHi; // High Word of first data cluster for file/directory described uint16_t WrtTime; // Last Modification time | Must equal CrtTime uint16_t WrtDate; // Last Modification date | Must equal CrtDate - uint16_t FstClusLO; // Low word of first data cluster for file/directory described + uint16_t FstClusLo; // Low word of first data cluster for file/directory described uint32_t FileSize; // size in bytes of file/directory described }__attribute__((packed)); -typedef struct _DIRECTORY{ - uint8_t Filename[8]; - uint8_t Ext[3]; - uint8_t Attrib; - uint8_t Reserved; - uint8_t TimeCreatedMs; - uint16_t TimeCreated; - uint16_t DateCreated; - uint16_t DateLastAccessed; - uint16_t FirstClusterHiBytes; - uint16_t LastModTime; - uint16_t LastModDate; - uint16_t FirstCluster; - uint32_t FileSize; -}__attribute__((packed)) DIRECTORY, *PDIRECTORY; enum struct FAT_TYPE{ FAT12, @@ -115,7 +81,10 @@ public: static uint16_t GetFATEntry(BiosParameterBlock*, unsigned int); static uint16_t DetermineFreeSpace(); static int GetSectorOfRootDirectory(BiosParameterBlock*); - static int RootDirSize(BiosParameterBlock*); + static unsigned int RootDirSize(BiosParameterBlock*); + static void OpenSubdir (DIR*, BiosParameterBlock*); + + static const int FREE = 0x0000; static const int ALLOCATED = 0x0002; -- 2.39.5 From 745656eb2d8b512b195d2db0be7ee73a82562b43 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 25 Feb 2023 20:04:34 +0100 Subject: [PATCH 104/115] Fixup C++ compiler path in makefile of CoreLib memcpy implementation added --- CoreLib/Makefile | 3 ++- CoreLib/Memory.cpp | 11 +++++++++++ CoreLib/Memory.h | 2 ++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/CoreLib/Makefile b/CoreLib/Makefile index a37ab45..74159a8 100644 --- a/CoreLib/Makefile +++ b/CoreLib/Makefile @@ -1,4 +1,4 @@ -CPP = ${HOME}/opt/cross/bin/i686-elf-g++ +CPP = /opt/cross/bin/i686-elf-g++ CFLAGS = -ffreestanding -Og -ggdb -Wall -Wextra BUILD_DIR = ../build/CoreLib @@ -12,6 +12,7 @@ all: $(OUTPUTFILE) cp *.h $(BUILD_DIR)/include/CoreLib $(OUTPUTFILE): $(OFILES) + pwd ar -rc $(OUTPUTFILE) $(OFILES) $(OBJ_FOLDER)/memory.o: Memory.cpp diff --git a/CoreLib/Memory.cpp b/CoreLib/Memory.cpp index 830a346..4559461 100644 --- a/CoreLib/Memory.cpp +++ b/CoreLib/Memory.cpp @@ -32,6 +32,17 @@ int memcmp( const void* ptr1, const void* ptr2, size_t num) } +void memcpy (void* dest, const void* src, size_t count ){ + for( int i = 0; i < count; i++){ + ((char *)dest)[i] = ((const char*)src)[i]; + } +} + + + + + + size_t strlen(const char* str) { size_t len = 0; while(str[len]){ diff --git a/CoreLib/Memory.h b/CoreLib/Memory.h index a4cc9d5..e0a1d67 100644 --- a/CoreLib/Memory.h +++ b/CoreLib/Memory.h @@ -7,6 +7,8 @@ void* memset (void* ptr, int value, size_t num); int memcmp( const void* ptr1, const void* ptr2, size_t num); +void memcpy (void* dest, const void* src, size_t count ); + size_t strlen(const char* str); int strncmp ( const char* str1, const char* str2, size_t num ); -- 2.39.5 From 32b0d990df3df4417b861a138cba10aa35c68f8e Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 25 Feb 2023 20:41:21 +0100 Subject: [PATCH 105/115] Added ctype std lib functions --- CoreLib/Makefile | 7 ++- CoreLib/ctype.cpp | 141 ++++++++++++++++++++++++++++++++++++++++++++++ CoreLib/ctype.h | 21 +++++++ 3 files changed, 168 insertions(+), 1 deletion(-) create mode 100644 CoreLib/ctype.cpp create mode 100644 CoreLib/ctype.h diff --git a/CoreLib/Makefile b/CoreLib/Makefile index 74159a8..cb74d68 100644 --- a/CoreLib/Makefile +++ b/CoreLib/Makefile @@ -5,7 +5,7 @@ BUILD_DIR = ../build/CoreLib OBJ_FOLDER = ../bin/CoreLib OUTPUTFILE = $(BUILD_DIR)/libCoreLib.a -OFILES = $(OBJ_FOLDER)/memory.o $(OBJ_FOLDER)/path.o $(OBJ_FOLDER)/stack.o $(OBJ_FOLDER)/string.o $(OBJ_FOLDER)/stringview.o +OFILES = $(OBJ_FOLDER)/ctype.o $(OBJ_FOLDER)/memory.o $(OBJ_FOLDER)/path.o $(OBJ_FOLDER)/stack.o $(OBJ_FOLDER)/string.o $(OBJ_FOLDER)/stringview.o .phony: all all: $(OUTPUTFILE) @@ -15,6 +15,11 @@ $(OUTPUTFILE): $(OFILES) pwd ar -rc $(OUTPUTFILE) $(OFILES) + + +$(OBJ_FOLDER)/ctype.o: ctype.cpp + $(CPP) -c ctype.cpp -o $(OBJ_FOLDER)/ctype.o $(CFLAGS) + $(OBJ_FOLDER)/memory.o: Memory.cpp $(CPP) -c Memory.cpp -o $(OBJ_FOLDER)/memory.o $(CFLAGS) diff --git a/CoreLib/ctype.cpp b/CoreLib/ctype.cpp new file mode 100644 index 0000000..2c81ade --- /dev/null +++ b/CoreLib/ctype.cpp @@ -0,0 +1,141 @@ +// +// Created by nigel on 25/02/23. +// +#include "ctype.h" + +int isupper (int ch){ + if( ch >= 'A' && ch <= 'Z'){ + return 1; + } + return 0; +} +int islower (int ch){ + if(ch >= 'a' && ch <= 'z'){ + return 1; + } + return 0; +} + +int isalpha (int ch) { + if(isupper(ch)){ + return 1; + } + if(islower(ch)){ + return 1; + } + return 0; +} +int isdigit (int ch){ + if(ch >= '0' && ch <= '9'){ + return 1; + } + return 0; +} + +int isxdigit (int ch){ + if(isdigit(ch)){ + return 1; + } + + if( ch >= 'a' && ch <= 'f'){ + return 1; + } + + if( ch >= 'A' && ch <= 'F'){ + return 1; + } + return 0; +} + +int iscntrl (int ch){ + if(ch >= 0x00 && ch <= 0x1f ) + return 1; + if(ch == 0x7f) + return 1; + return 0; +} + + +int isgraph (int ch){ + if(isdigit(ch)) + return 1; + if(isupper(ch)) + return 1; + if(islower(ch)) + return 1; + if(ispunct(ch)) + return 1; + return 0; +} + +int isspace(int ch){ + if (ch == 0x20) + return 1; + if(ch == 0x0c) + return 1; + if(ch == 0x0a) + return 1; + if(ch == 0x0d) + return 1; + if(ch == 0x09) + return 1; + if(ch == 0x0b) + return 1; + + return 0; +} + +int isblank (int ch){ + if( ch == 0x20 || ch == 0x09) + return 1; + return 0; +} + +int ispunct(int ch){ + if(ch >= '!' && ch <= '~') + return 1; + return 0; +} + +int isprint (int ch){ + if (isdigit(ch)) + return 1; + if(isupper(ch)) + return 1; + if(islower(ch)) + return 1; + if(ispunct(ch)) + return 1; + if(isspace(ch)) + return 1; + +} + + +int tolower(int ch){ + + if(islower(ch)) return ch; + int diff = 'a' - 'A'; + return ch + diff; +} + +int toupper(int ch){ + if(isupper(ch)) return ch; + int diff = 'a' - 'A'; + return ch - diff; +} + + + +int isalnum (int ch){ + if(isdigit(ch)){ + return 1; + } + + if(isalpha(ch)){ + return 1; + } + + return 0; + +} \ No newline at end of file diff --git a/CoreLib/ctype.h b/CoreLib/ctype.h new file mode 100644 index 0000000..43262d6 --- /dev/null +++ b/CoreLib/ctype.h @@ -0,0 +1,21 @@ +// +// Created by nigel on 25/02/23. +// +#pragma once + +//NOTE: Uses default locale +int isupper (int ch); +int islower (int ch); +int isalpha (int ch); +int isdigit (int ch); +int isxdigit (int ch); +int iscntrl (int ch); +int isgraph(int ch); +int isspace(int ch); +int isblank(int ch); +int ispunct(int ch); +int isprint(int ch); +int isalnum (int ch); +int tolower(int ch); +int toupper(int ch); + -- 2.39.5 From 61f1852420f06e840d3cb7f0c40fcaae83d118a1 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sat, 25 Feb 2023 21:03:10 +0100 Subject: [PATCH 106/115] Added file reading without cluster chain following --- kernel/kernel.cpp | 2 ++ kernel/storage/filesystems/FAT/FAT.cpp | 43 ++++++++------------------ kernel/storage/filesystems/FAT/FAT.h | 1 + 3 files changed, 16 insertions(+), 30 deletions(-) diff --git a/kernel/kernel.cpp b/kernel/kernel.cpp index f10b3cf..48081dc 100644 --- a/kernel/kernel.cpp +++ b/kernel/kernel.cpp @@ -122,6 +122,8 @@ extern "C" void kernel () printf(" [Size: %d bytes, Attributes: %d]\n", entry->ATTR, entry->FileSize); if(entry->ATTR & FAT::ATTRIBUTES::ATTR_DIRECTORY ){ FAT::OpenSubdir(entry, bpb); + } else { + FAT::readFile(entry, bpb); } } diff --git a/kernel/storage/filesystems/FAT/FAT.cpp b/kernel/storage/filesystems/FAT/FAT.cpp index 7a635e4..19619a0 100644 --- a/kernel/storage/filesystems/FAT/FAT.cpp +++ b/kernel/storage/filesystems/FAT/FAT.cpp @@ -146,8 +146,6 @@ uint16_t FAT::GetFATEntry (BiosParameterBlock* bpb, unsigned int cluster){ } - - uint16_t FAT::DetermineFreeSpace() { // Loop through all FAT entries in all FAT's @@ -180,8 +178,6 @@ unsigned int FAT::RootDirSize(BiosParameterBlock* bpb) } - - uint16_t* ReadFAT (BiosParameterBlock& bpb , bool DEBUG = false ) { uint32_t FATAddress = /*StartAddress*/ 0x00 + bpb.RsvdSecCnt ; uint16_t* FAT = (uint16_t*)malloc(sizeof (uint16_t) * 256); @@ -253,42 +249,29 @@ void FAT::OpenSubdir(DIR* directory, BiosParameterBlock* bpb ){ printf("LFN\n"); } - - - - - - - } - - } +void FAT::readFile(DIR* fileEntry , BiosParameterBlock* bpb){ + unsigned int cluster = fileEntry->FstClusLo; + unsigned int FATEntry = FAT::GetFATEntry(bpb, cluster); + unsigned int root_dir_sectors = FAT::RootDirSize(bpb); + unsigned int fat_size = bpb->FATSz16; + unsigned int first_data_sector = bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sectors; + unsigned int file_data_sector = ((cluster -2) * bpb->SecPerClus) + first_data_sector; + printf("FAT entry = %x\n", FATEntry); + uint16_t data[256]; + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, file_data_sector, data); -void readFile(uint32_t DataRegion, DIR* entry, uint16_t FATentry, BiosParameterBlock& bpb ){ - printf("Show contents"); - - printf("Start cluster of the file: 0x%x\n", entry->FileSize); - - printf("IS it only 1 cluster? %s\n", FATentry == 0xFFFF ? "Yes" : "No"); - - uint32_t sector = DataRegion + ((entry->FileSize - 0x02) * bpb.SecPerClus); - - - uint16_t dataBlob[256]; - ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, sector, dataBlob); - for (unsigned short n: dataBlob) { + for (unsigned short n : data) + { kterm_put(n & 0x00ff); - kterm_put(n >> 8); } - kterm_put('\n'); + } - - /* file fsysFatDirectory (const char* DirectoryName){ file file; diff --git a/kernel/storage/filesystems/FAT/FAT.h b/kernel/storage/filesystems/FAT/FAT.h index 1627aab..4d5ed59 100644 --- a/kernel/storage/filesystems/FAT/FAT.h +++ b/kernel/storage/filesystems/FAT/FAT.h @@ -83,6 +83,7 @@ public: static int GetSectorOfRootDirectory(BiosParameterBlock*); static unsigned int RootDirSize(BiosParameterBlock*); static void OpenSubdir (DIR*, BiosParameterBlock*); + static void readFile(DIR*, BiosParameterBlock*); -- 2.39.5 From e6901f05263a52cf0ff688c54ace9dceaccf2c60 Mon Sep 17 00:00:00 2001 From: Nigel Date: Sun, 26 Feb 2023 13:44:41 +0100 Subject: [PATCH 107/115] We can now open and read files on the harddisk through a messy virtual filesystem The uri has to contain 8.3 filenames for now as I have not yet figured out how to convert from that to regular filenaming for the name comparison. reading files is still limited to 1 sector --- CoreLib/List.h | 12 + CoreLib/Memory.cpp | 2 +- CoreLib/Memory.h | 2 +- README.md | 2 +- kernel/kernel.cpp | 95 ++---- kernel/storage/filesystems/FAT/FAT.cpp | 340 ++++++++++----------- kernel/storage/filesystems/FAT/FAT.h | 44 ++- kernel/storage/filesystems/FAT/msdosDate.h | 2 + kernel/storage/vfs/vfs.cpp | 94 +++--- kernel/storage/vfs/vfs.h | 10 +- kernel/storage/vfs/vfs_types.h | 90 +++--- todo.md | 2 +- 12 files changed, 310 insertions(+), 385 deletions(-) create mode 100644 CoreLib/List.h diff --git a/CoreLib/List.h b/CoreLib/List.h new file mode 100644 index 0000000..8d11e3b --- /dev/null +++ b/CoreLib/List.h @@ -0,0 +1,12 @@ +// +// Created by nigel on 25/02/23. +// +#pragma once + + +class List { +public: + List* next; + void* data; +}; + diff --git a/CoreLib/Memory.cpp b/CoreLib/Memory.cpp index 4559461..491ed38 100644 --- a/CoreLib/Memory.cpp +++ b/CoreLib/Memory.cpp @@ -32,7 +32,7 @@ int memcmp( const void* ptr1, const void* ptr2, size_t num) } -void memcpy (void* dest, const void* src, size_t count ){ +[[maybe_unused]] void memcpy (void* dest, const void* src, size_t count ){ for( int i = 0; i < count; i++){ ((char *)dest)[i] = ((const char*)src)[i]; } diff --git a/CoreLib/Memory.h b/CoreLib/Memory.h index e0a1d67..7482d65 100644 --- a/CoreLib/Memory.h +++ b/CoreLib/Memory.h @@ -7,7 +7,7 @@ void* memset (void* ptr, int value, size_t num); int memcmp( const void* ptr1, const void* ptr2, size_t num); -void memcpy (void* dest, const void* src, size_t count ); +[[maybe_unused]] void memcpy (void* dest, const void* src, size_t count ); size_t strlen(const char* str); diff --git a/README.md b/README.md index 2edcad6..9befc1a 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ Enumerating the PCI bus Correctly identified our ATAPI device 🎉 ![Reading Files from FAT-16](screenshots/ReadingFilesFromFAT16.png) \ -Reading a file from a FAT-16 Formatted drive +Reading a FILE from a FAT-16 Formatted drive ________________________ diff --git a/kernel/kernel.cpp b/kernel/kernel.cpp index 48081dc..d705045 100644 --- a/kernel/kernel.cpp +++ b/kernel/kernel.cpp @@ -16,6 +16,7 @@ #include "serial.h" #include "storage/vfs/vfs.h" #include "storage/filesystems/FAT/FAT.h" +#include "../CoreLib/Memory.h" extern "C" void LoadGlobalDescriptorTable(); @@ -57,86 +58,26 @@ extern "C" void kernel () printf("Part1: %d, Part2: %d, Part3: %d\n", part1, part2 , part3); ATAPIO::Identify(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); - auto* bpb = FAT::getBPB(false); - auto* mbr = GetPartitions(false); - auto fsType = FAT::determineFATType(bpb); - switch (fsType) { - case FAT_TYPE::FAT12: - printf("FAT12 Disk!\n"); - break; - case FAT_TYPE::FAT16: - printf("FAT16 Disk!\n"); - break; - case FAT_TYPE::FAT32: - printf("FAT32 Disk!\n"); - break; + + VirtualFileSystem::initialize(); + + printf("Lets open hello.txt\n"); + auto fontFile = VirtualFileSystem::open("/HELLO TXT", 0); + if(fontFile->flags == 0){ + uint16_t* contents = (uint16_t*) malloc(sizeof(uint16_t) * 256); + fontFile->read(fontFile, contents, 512); + + for(int i =0 ; i < fontFile->root->size; i++ ){ + kterm_put(contents[i] & 0x00ff); + kterm_put(contents[i] >> 8); + } + kterm_put('\n'); + free((void*)contents); + }else{ + printf("Could not find file\n"); } - // list files in root - int total_sectors = bpb->TotSec32; - int fat_size = bpb->FATSz16; - int root_dir_sectors = FAT::RootDirSize(bpb); - int first_data_sector = bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sectors ; - int data_sectors = bpb->TotSec32 - (bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sectors); - int total_clusters = data_sectors / bpb->SecPerClus; - - - int first_root_dir_sector = first_data_sector - root_dir_sectors; - //int first_sector_of_cluster = ((cluster - 2) * bpb->SecPerClus) + first_data_sector; - uint16_t data[256]; - ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, first_root_dir_sector, data); - - auto* RootDirectory = (DIR*)data; - for(int i = 0; i < sizeof(data) / sizeof (DIR); i++) - { - DIR* entry = (DIR*)((uint32_t)RootDirectory + (i * sizeof(DIR))); - - - if(entry->Name[0] == FAT::FREE_DIR || entry->Name[0] == FAT::FREE_DIR_2 || entry->Name[0] == 0xE5){ - continue; - } - - - if(entry->ATTR & FAT::ATTRIBUTES::ATTR_HIDDEN){ - continue; - } - - if(entry->ATTR & FAT::ATTRIBUTES::ATTR_SYSTEM) - continue; - - - if(entry->ATTR & FAT::ATTRIBUTES::ATTR_VOLUME_ID){ - continue; - } - if (!(entry->ATTR & FAT::ATTRIBUTES::ATTR_LONG_NAME)){ - for(char n : entry->Name){ - if(n == 0x20) - continue; - kterm_put(n); - } - }else{ - printf("Long file name detected!"); - } - - printf(" [Size: %d bytes, Attributes: %d]\n", entry->ATTR, entry->FileSize); - if(entry->ATTR & FAT::ATTRIBUTES::ATTR_DIRECTORY ){ - FAT::OpenSubdir(entry, bpb); - } else { - FAT::readFile(entry, bpb); - } - - } - - - - - - - // VirtualFileSystem::initialize(); - - // VirtualFileSystem::open("/hello.txt", 0); - #ifdef USERMODE_RELEASE // Lets jump into user mode diff --git a/kernel/storage/filesystems/FAT/FAT.cpp b/kernel/storage/filesystems/FAT/FAT.cpp index 19619a0..80465b9 100644 --- a/kernel/storage/filesystems/FAT/FAT.cpp +++ b/kernel/storage/filesystems/FAT/FAT.cpp @@ -4,10 +4,14 @@ #include "FAT.h" #include "../../ata pio/ATAPIO.h" #include "../../../memory/KernelHeap.h" -#include "../../../../CoreLib/Memory.h" #include "../../partitiontables/mbr/MasterBootRecord.h" +#include "../../../../CoreLib/ctype.h" +#include "../../../../CoreLib/Memory.h" #include -superblock* FAT::Mount(filesystem *fs, const char* name ,vfsmount *mnt) +#include + +// exposed driver API +FS_SUPER* FAT::Mount(filesystem *fs, const char* name , vfsmount *mnt) { if( strncmp (fs->name, "fat", 3 ) != 0 ) @@ -15,58 +19,138 @@ superblock* FAT::Mount(filesystem *fs, const char* name ,vfsmount *mnt) printf("Can't mount filesystem with none fat type!\n"); return nullptr; } + auto* bpb = GetBiosParameterBlock(); + auto fat_type = DetermineFATType(bpb); - superblock* sb = (superblock*) malloc(sizeof(superblock)); - directoryEntry* root = (directoryEntry*) malloc(sizeof (directoryEntry)); + if(fat_type != FAT_TYPE::FAT16) + return nullptr; + + FS_SUPER* sb = (FS_SUPER*) malloc(sizeof(FS_SUPER)); + DirectoryNode* root = (DirectoryNode*) malloc(sizeof (DirectoryNode)); + inode* node = (inode*) malloc(sizeof(inode)); + + root->children = nullptr; + node->internal = (void*)FAT::GetSectorOfRootDirectory(bpb); //sector number; + node->lookup = FAT::Lookup; root->name = (char*) name; - root->node = nullptr; + root->node = node; root->parent = nullptr; - - dentry_operations* op = (dentry_operations*) malloc(sizeof(dentry_operations)); - op->compare = FAT::compare; - - - root->op = op; - - + root->compare = FAT::Compare; mnt->mnt_count =1; mnt->mnt_devname = "QEMU HDD"; mnt->mnt_flags = 0; mnt->mnt_parent = nullptr; - mnt->root = root; mnt->sb = sb; - sb->type = fs; sb->root = root; - //sb->fs_info = getBPB(); + sb->fs_info = bpb; return sb; } -int FAT::Read(file* file, void* buffer , int length) -{ - return 0; -} -int FAT::Write(file* file, const void* buffer, int length) -{ - return 0; -} -int FAT::compare (directoryEntry*, char* filename, char* filename2) -{ - // use the size of the smallest string - int a = strlen(filename); - int b = strlen(filename2); +FILE FAT::Open(char* filename){ - if( a == b ){ - return strncmp(filename, filename2, a); + return (FILE){nullptr, 0, nullptr, nullptr, 1} ; +} +int FAT::Read(FILE* file, void* buffer , unsigned int length) +{ + + if(file == nullptr) + { + printf("NO FILE!!\n"); + return -1; } - return a-b; + inode* node = file->root; + + if(node== nullptr) + { + printf("No INODE!\n"); + return -1; + } + + int cluster = (int)node->internal; + auto* bpb = FAT::GetBiosParameterBlock(); + + unsigned int FAT_entry = FAT::GetFATEntry(bpb, cluster); + unsigned int root_dir_sector = FAT::RootDirSize(bpb); + unsigned int fat_size = bpb->FATSz16; + unsigned int first_data_sector = bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sector; + unsigned int file_data_sector = ((cluster - 2) * bpb->SecPerClus) + first_data_sector; + + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, file_data_sector, (uint16_t*)buffer); + + return 0; } -int FAT::create(inode* dir_node, inode** target, const char* component_name){} -int FAT::lookup (inode*, inode**, const char*){} + +int FAT::Write(FILE* file, const void* buffer, unsigned int length) +{ + return 0; +} + +int FAT::Compare (DirectoryNode*, char* filename, char* filename2) +{ + //TODO Implement proper compare method for 8.3 filenames + // printf("COMPARE: %s with %s\n", filename, filename2); + return memcmp(filename, filename2, 11); +} + +int FAT::Create(inode* dir_node, inode** target, const char* component_name){} + +DirectoryNode* FAT::Lookup (inode* currentDir , DirectoryNode* dir) +{ + + uint16_t data[256]; + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, (int)currentDir->internal , data); + + List* lastAdded = nullptr; + auto* directory = (DIR*)data; + for(int i = 0; i < sizeof(data) / sizeof (DIR); i++) + { + DIR* entry = (DIR*)((uint32_t)directory + (i * sizeof(DIR))); + if( + entry->Name[0] == FAT::FREE_DIR || + entry->Name[0] == FAT::FREE_DIR_2 || + entry->Name[0] == 0xE5 || + entry->ATTR & FAT::ATTRIBUTES::ATTR_VOLUME_ID || + entry->ATTR & FAT::ATTRIBUTES::ATTR_SYSTEM || + entry->ATTR & FAT::ATTRIBUTES::ATTR_HIDDEN + ){ + continue; + } + + auto* dirNode = (DirectoryNode*) malloc(sizeof (DirectoryNode)); + + char* name = (char*)malloc(sizeof(char[11])); + memcpy(name, entry->Name, 11 ); + dirNode->name = name; + dirNode->compare = dir->compare; + dirNode->parent = dir; + + dirNode->node= (inode*) malloc(sizeof (inode)); + dirNode->node->internal = (void*)entry->FstClusLo; + + dirNode->node->read = currentDir->read; + dirNode->node->lookup = currentDir->lookup; + dirNode->node->sb = currentDir->sb; + dirNode->node->size = entry->FileSize; + + List* dirlist = (List*) malloc(sizeof (List)); + dirlist->data = dirNode; + dirlist->next = nullptr; + + lastAdded = dirlist; + auto* temp = dir->children; + dir->children = lastAdded; + lastAdded->next = temp; -FAT_TYPE FAT::determineFATType(BiosParameterBlock* bpb){ + } + + return (DirectoryNode*)dir; +} + +// internal functions +FAT_TYPE FAT::DetermineFATType(BiosParameterBlock* bpb){ int RootDirSector = ((bpb->RootEntCnt * 32) + (bpb->BytsPerSec -1)) / bpb->BytsPerSec; int FATSz = 0; if(bpb->FATSz16 != 0){ @@ -93,7 +177,7 @@ FAT_TYPE FAT::determineFATType(BiosParameterBlock* bpb){ return FAT_TYPE::FAT32; } }; -BiosParameterBlock* FAT::getBPB( bool DEBUG ){ +BiosParameterBlock* FAT::GetBiosParameterBlock(bool DEBUG ){ BiosParameterBlock* bpb = (BiosParameterBlock*) malloc(sizeof(BiosParameterBlock)); uint16_t StartAddress = 0x00 ; ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, StartAddress, (uint16_t*) bpb); @@ -114,24 +198,20 @@ BiosParameterBlock* FAT::getBPB( bool DEBUG ){ } uint16_t FAT::GetFATEntry (BiosParameterBlock* bpb, unsigned int cluster){ int FATSz = bpb->FATSz16; - int FATOffset = 0; - FAT_TYPE type = FAT::determineFATType(bpb); + FAT_TYPE type = FAT::DetermineFATType(bpb); if( type == FAT_TYPE::FAT16){ FATOffset = cluster *2; } else if( type == FAT_TYPE::FAT32){ FATOffset = cluster * 4; } - int thisFATSecNum = bpb->RsvdSecCnt + (FATOffset / bpb->BytsPerSec); // Sector number containing the entry for the cluster // For any other FAT other than the default // SectorNumber = (FATNumber * FATSz) + ThisFATSecNum uint16_t buff[bpb->BytsPerSec]; - ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, thisFATSecNum, buff ); - int thisFATEntOffset = FATOffset % bpb->BytsPerSec; // offset for the entry in the sector containing the entry for the cluster uint16_t ClusterEntryValue = 0; // Get the FATEntry @@ -145,7 +225,6 @@ uint16_t FAT::GetFATEntry (BiosParameterBlock* bpb, unsigned int cluster){ } } - uint16_t FAT::DetermineFreeSpace() { // Loop through all FAT entries in all FAT's @@ -166,35 +245,15 @@ the FAT entry for the last cluster) must be set to 0x0 during volume initializat } - int FAT::GetSectorOfRootDirectory (BiosParameterBlock* bpb) { return (bpb->RsvdSecCnt + (bpb->NumFATs * bpb->FATSz16)); } - unsigned int FAT::RootDirSize(BiosParameterBlock* bpb) { return ((bpb->RootEntCnt * 32) + (bpb->BytsPerSec -1)) /bpb->BytsPerSec; } - -uint16_t* ReadFAT (BiosParameterBlock& bpb , bool DEBUG = false ) { - uint32_t FATAddress = /*StartAddress*/ 0x00 + bpb.RsvdSecCnt ; - uint16_t* FAT = (uint16_t*)malloc(sizeof (uint16_t) * 256); - - ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, FATAddress, FAT ); - - // Show data in terminal - if(DEBUG){ - for( unsigned int i =0 ; i < 256 ; i++) { - printf("0x%x ", (unsigned short)FAT[i]); - } - kterm_put('\n'); - } - - return FAT; -} - void FAT::OpenSubdir(DIR* directory, BiosParameterBlock* bpb ){ unsigned int cluster = directory->FstClusLo; @@ -252,9 +311,9 @@ void FAT::OpenSubdir(DIR* directory, BiosParameterBlock* bpb ){ } } - -void FAT::readFile(DIR* fileEntry , BiosParameterBlock* bpb){ +void FAT::ReadFileContents(DIR* fileEntry , BiosParameterBlock* bpb){ unsigned int cluster = fileEntry->FstClusLo; + printf("cluster NR: %x\n", cluster); unsigned int FATEntry = FAT::GetFATEntry(bpb, cluster); unsigned int root_dir_sectors = FAT::RootDirSize(bpb); unsigned int fat_size = bpb->FATSz16; @@ -269,140 +328,63 @@ void FAT::readFile(DIR* fileEntry , BiosParameterBlock* bpb){ kterm_put(n & 0x00ff); kterm_put(n >> 8); } + kterm_put('\n'); } +void FAT::ListRootDirectoryContents(BiosParameterBlock* bpb){ + int total_sectors = bpb->TotSec32; + int fat_size = bpb->FATSz16; + int root_dir_sectors = FAT::RootDirSize(bpb); + int first_data_sector = bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sectors ; + int data_sectors = bpb->TotSec32 - (bpb->RsvdSecCnt + (bpb->NumFATs * fat_size) + root_dir_sectors); + int total_clusters = data_sectors / bpb->SecPerClus; -/* -file fsysFatDirectory (const char* DirectoryName){ - file file; - unsigned char* buf; - PDIRECTORY directory; - char DosFileName[11]; - //ToDosFileName(DirectoryName, DosFileName, 11); - DosFileName[11] =0; + int first_root_dir_sector = first_data_sector - root_dir_sectors; + //int first_sector_of_cluster = ((cluster - 2) * bpb->SecPerClus) + first_data_sector; + uint16_t data[256]; + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, first_root_dir_sector, data); - for (int sector=0; sector <14 ; sector++){ - ATAPIO::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mountInfo.rootOffset + sector, (uint16_t*)buf); - directory = (PDIRECTORY) buf; + auto* RootDirectory = (DIR*)data; + for(int i = 0; i < sizeof(data) / sizeof (DIR); i++) + { + DIR* entry = (DIR*)((uint32_t)RootDirectory + (i * sizeof(DIR))); - for (int i =0; i < 16; i++){ - char name[11]; - memcpy(name, directory->Filename, 11); - name[11]=0; - if(strncmp(DosFileName, name, 11) == 0){ - strcpy(file.name, DirectoryName); - file.id = 0; - file.currentCluster = directory->FirstCluster; - file.eof = 0; - file.filelength = directory->FileSize; - - if(directory->Attrib == 0x10){ - file.flags = 2; - } else { - file.flags = 1; - } - return file; - } - directory++; + if(entry->Name[0] == FAT::FREE_DIR || entry->Name[0] == FAT::FREE_DIR_2 || entry->Name[0] == 0xE5){ + continue; } - } - - // Can't find file - file.flags = -1; - return file; - -} -void fsysFATRead(PFILE file, unsigned char* buffer, unsigned int length){ - if(file){ - unsigned int physSector = 32 + (file->currentCluster - 1); - const unsigned int SECTOR_SIZE = 512; - // read sector - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, physSector, (uint16_t*) buffer ); + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_HIDDEN){ + continue; + } - unsigned int FAT_Offset = file->currentCluster + (file->currentCluster /2); - unsigned int FAT_Sector = 1 + (FAT_Offset / SECTOR_SIZE); - unsigned int entryOffset =FAT_Offset % SECTOR_SIZE; + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_SYSTEM) + continue; - uint8_t FAT[SECTOR_SIZE*2]; - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FAT_Sector,(uint16_t*) FAT); // Read 1st FAT sector - ATA_DEVICE::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, FAT_Sector +1, (uint16_t*)FAT+SECTOR_SIZE); - - // read entry for next cluster - uint16_t nextCluster = *(uint16_t*) &FAT[entryOffset]; - - // test if entry is odd or even - if(file->currentCluster & 0x0001){ - nextCluster>>= 4; // grab the high 12 bits + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_VOLUME_ID){ + continue; + } + if (!(entry->ATTR & FAT::ATTRIBUTES::ATTR_LONG_NAME)){ + for(char n : entry->Name){ + if(n == 0x20) + continue; + kterm_put(n); + } }else{ - nextCluster &= 0x0FFF; // grab the low 12 bits + printf("Long file name detected!"); } - // test for end of file - if(nextCluster >= 0xff8){ - file->eof -1; - return; + printf(" [Size: %d bytes, Attributes: %d]\n", entry->ATTR, entry->FileSize); + if(entry->ATTR & FAT::ATTRIBUTES::ATTR_DIRECTORY ){ + FAT::OpenSubdir(entry, bpb); + } else { + FAT::ReadFileContents(entry, bpb); } - // test for file corruption - if(nextCluster == 0){ - file->eof =1; - return; - } - - // set next cluster - file->currentCluster = nextCluster; - - } } -FILE fsysFatOpenSubDir(FILE kFile, const char* filename){ - FILE file; - char DosFileName[11]; - ToDosFileName(filename, DosFileName, 11); - DosFileName[11] = 0; - - while(!kFile.eof){ - //read directory - unsigned char buf[512]; - fsysFATRead(&file, buf, 512); - - PDIRECTORY pkDir = (PDIRECTORY) buf; - - for (unsigned int i = 0; i < 16; i++){ - // get current filename - char name[11]; - memcpy(name, pkDir->Filename, 11); - name[11] = 0; - - if(strncmp(name, DosFileName, 11) == 0){ - strcpy(file.name, filename); - file.id = 0; - file.currentCluster = pkDir->FirstCluster; - file.filelength = pkDir->FileSize; - file.eof = 0; - - // set file type; - if(pkDir->Attrib == 0x10){ - file.flags = 2; - } else{ - file.flags = 1; - } - - return file; - } - // go to next entry - pkDir++; - } - } - // unable to find file - file.flags = -1; - return file; -} -*/ diff --git a/kernel/storage/filesystems/FAT/FAT.h b/kernel/storage/filesystems/FAT/FAT.h index 4d5ed59..3a29bc1 100644 --- a/kernel/storage/filesystems/FAT/FAT.h +++ b/kernel/storage/filesystems/FAT/FAT.h @@ -63,32 +63,18 @@ enum struct FAT_TYPE{ class FAT { public: - // Wanted API for vfs - static file Open(char* filename); - static int close(file* file); - static int Read(file* file, void* buffer , int length); - static int Write(file* file, const void* buffer, int length); - static int create(inode* dir_node, inode** target, const char* component_name); - static int lookup(inode* , inode**, const char*); - static int compare(directoryEntry* , char* , char*); - static superblock* Mount(filesystem* fs, const char* name ,vfsmount* mount); + static FILE Open(char* filename); + static int close(FILE* file); + static int Read(FILE* file, void* buffer , unsigned int length); + static int Write(FILE* file, const void* buffer, unsigned int length); + static int Create(inode* dir_node, inode** target, const char* component_name); + static DirectoryNode* Lookup(inode* , DirectoryNode*); + static int Compare(DirectoryNode* , char *filename, char *filename2); + static FS_SUPER* Mount(filesystem* fs, const char* name , vfsmount* mount); - // TEMP - static void listFilesInRoot(MBR* mbr, BiosParameterBlock* bpb ); - static BiosParameterBlock* getBPB( bool DEBUG =false ); - static FAT_TYPE determineFATType(BiosParameterBlock* bpb); - static uint16_t GetFATEntry(BiosParameterBlock*, unsigned int); - static uint16_t DetermineFreeSpace(); - static int GetSectorOfRootDirectory(BiosParameterBlock*); - static unsigned int RootDirSize(BiosParameterBlock*); - static void OpenSubdir (DIR*, BiosParameterBlock*); - static void readFile(DIR*, BiosParameterBlock*); - - - - static const int FREE = 0x0000; - static const int ALLOCATED = 0x0002; + static const int FREE = 0x0000; + static const int ALLOCATED = 0x0002; static const int BAD = 0xFFF7; static const int EOF = 0xFFFF; @@ -98,6 +84,9 @@ public: static const char DOS_TRAILING_SPACE = 0x20; static const char FREE_DIR = 0xE5; // If KANJI charset 0x05 static const char FREE_DIR_2 = 0x00; // All directories after this are free including this one + static void ListRootDirectoryContents(BiosParameterBlock* bpb ); + static BiosParameterBlock* GetBiosParameterBlock(bool DEBUG =false ); + enum ATTRIBUTES { ATTR_READ_ONLY = 0x01, @@ -111,6 +100,13 @@ public: private: + static FAT_TYPE DetermineFATType(BiosParameterBlock* bpb); + static uint16_t GetFATEntry(BiosParameterBlock*, unsigned int); + static uint16_t DetermineFreeSpace(); + static int GetSectorOfRootDirectory(BiosParameterBlock*); + static unsigned int RootDirSize(BiosParameterBlock*); + static void OpenSubdir (DIR*, BiosParameterBlock*); + static void ReadFileContents(DIR *fileEntry, BiosParameterBlock *bpb); enum ENTRY_SIZE { FAT12 = 12, diff --git a/kernel/storage/filesystems/FAT/msdosDate.h b/kernel/storage/filesystems/FAT/msdosDate.h index c1fff64..8eb2cc4 100644 --- a/kernel/storage/filesystems/FAT/msdosDate.h +++ b/kernel/storage/filesystems/FAT/msdosDate.h @@ -5,6 +5,8 @@ #pragma once #include "../../../terminal/kterm.h" +#include "../../../memory/KernelHeap.h" +#include "../../../../CoreLib/Memory.h" // Date Format // [0..4] Day diff --git a/kernel/storage/vfs/vfs.cpp b/kernel/storage/vfs/vfs.cpp index 7d67144..d432632 100644 --- a/kernel/storage/vfs/vfs.cpp +++ b/kernel/storage/vfs/vfs.cpp @@ -14,17 +14,21 @@ int VirtualFileSystem::superblock_number =0; int VirtualFileSystem::filesystem_number =0; filesystem* VirtualFileSystem::filesystems[4]; -superblock* VirtualFileSystem::superblocks[8]; +FS_SUPER* VirtualFileSystem::superblocks[8]; vfsmount* VirtualFileSystem::mounts[12]; void VirtualFileSystem::Mount(filesystem* fs, const char* name) { - vfsmount* mnt_point = (vfsmount*) malloc(sizeof(vfsmount)); - superblock* sb = fs->mount(fs, name, mnt_point); + vfsmount* mnt_point = (vfsmount*) malloc(sizeof(vfsmount)); + FS_SUPER* sb = fs->mount(fs, name, mnt_point); + if( sb == nullptr){ + printf("mount failed!\n"); + return; + } mounts[mount_number++] = mnt_point; superblocks[superblock_number++] = sb; - + mnt_point->mnt_count = 1; rootfs = mnt_point; } @@ -54,64 +58,58 @@ int VirtualFileSystem::register_filesystem(struct filesystem* fs) { } -struct file* VirtualFileSystem::open(const char* pathname, int flags){ +FILE* VirtualFileSystem::open(const char* pathname, int flags){ // 1. Lookup pathname from the root node - // 2. Create a new file descriptor for this v_node if found. + // 2. Create a new file descriptor for this inode if found. // 3. Create a new file if O_CREATE is specified in the flags. - - // See reference material (1) https://man7.org/linux/man-pages/man7/path_resolution.7.html - - // FILE file = ->Open(filename); - if(pathname[0] != '/'){ - printf("We won't handle relative paths yet!"); - file file; - file.flags = 1; - return &file; - } - - - - auto* dentry = rootfs->root; - - int result = dentry->op->compare(dentry, "/", dentry->name); - if(result != 0 ){ - printf("rootfs not called / \n"); - file file; - file.flags = 1; - return &file; - } - + FILE* file = (FILE*) malloc(sizeof (FILE)) ; + auto* rootentry = rootfs->root; char* tokstate = nullptr; auto nextdir = strtok ((char*)pathname, "/", &tokstate ); - while (nextdir) - { - printf("Look for dentry: %s\n", nextdir); - // look to its children - if (dentry->children ) { - printf("No children | children unknown!\n"); - break; - } - if (dentry->op->compare(dentry, nextdir, dentry->name)) - { - // file found - nextdir = strtok(nullptr, "/", &tokstate); - } + // look up children if not filled + if(rootentry->children == nullptr) + { + rootentry = rootentry->node->lookup(rootentry->node, rootentry); } - file file; - file.flags = 1; - return &file; + if(rootentry->children == nullptr) + { + file->flags =1; + return file; + } + + // let's just loop through the folder first + auto* child = rootentry->children; + while(child->next != nullptr){ + + auto* directory = (DirectoryNode*)child->data; + if( directory->compare(directory, directory->name, nextdir) == 0){ + nextdir = strtok(nullptr, "/", &tokstate); + if(nextdir == NULL){ + file->root = directory->node; + file->flags =0; + file->read = FAT::Read; + return file; + } + } + child = child->next; + } + + + + file->flags = 1; + return file; } -int VirtualFileSystem::close (struct file* file){ +int VirtualFileSystem::close (struct FILE* file){ // 1. release the file descriptor } -int VirtualFileSystem::write(struct file* file, const void* buf, size_t len){ +int VirtualFileSystem::write(struct FILE* file, const void* buf, unsigned int len){ // 1. Write len bytes from buf to the opened file. // 2. return written size or error code if an error occurs } -int VirtualFileSystem::read (struct file* file, void* buf, size_t len){ +int VirtualFileSystem::read (struct FILE* file, void* buf, unsigned int len){ // 1. read min(len, readable file data size) bytes ro buf from the opened file. // 2. return read size or error code if an error occurs } diff --git a/kernel/storage/vfs/vfs.h b/kernel/storage/vfs/vfs.h index 804f09a..821853d 100644 --- a/kernel/storage/vfs/vfs.h +++ b/kernel/storage/vfs/vfs.h @@ -11,10 +11,10 @@ static int register_filesystem(struct filesystem* fs); - static struct file* open(const char* pathname, int flags); - static int close(struct file* file); - static int write(struct file* file, const void* buf, size_t len); - static int read(struct file* file, void* buf, size_t len); + static FILE* open(const char* pathname, int flags); + static int close(struct FILE* file); + static int write(struct FILE* file, const void* buf, unsigned int len); + static int read(struct FILE* file, void* buf, unsigned int len); private: static vfsmount* rootfs; @@ -25,7 +25,7 @@ static int filesystem_number; static filesystem* filesystems[]; - static superblock* superblocks[]; + static FS_SUPER* superblocks[]; static vfsmount* mounts[]; }; diff --git a/kernel/storage/vfs/vfs_types.h b/kernel/storage/vfs/vfs_types.h index c989dbe..73744ca 100644 --- a/kernel/storage/vfs/vfs_types.h +++ b/kernel/storage/vfs/vfs_types.h @@ -5,55 +5,52 @@ // grasslab.github.io/osdi/en/labs/lab7.html #include #include +#include "../../../CoreLib/List.h" struct inode_operations; struct vfsmount; -struct superblock; +struct FS_SUPER; struct inode; struct dentry_operations; -struct directoryEntry; +struct DirectoryNode; struct filesystem; -struct superblock; -struct file; +struct FS_SUPER; +struct FILE; + -struct file_operations{ - int(*write) (file* file, const void* buf, size_t len); - int(*read) (file* file, void* buf, size_t len); -}; -struct inode_operations { - int (*create)(inode*, directoryEntry*, const char* ); - directoryEntry* (*lookup)(inode* , directoryEntry*); - int (*link)(directoryEntry*, inode* , directoryEntry*); - int (*unlink)(inode*, directoryEntry*); - int (*symlink)(inode*, directoryEntry*); - int (*mkdir)(inode*, directoryEntry*, const char*); - int (*rmdir)(inode*, directoryEntry*); - int (*rename)(inode*, directoryEntry*, inode*, directoryEntry*); - void (*truncate)(inode*); - int (*permission)(inode*, int); - int (*setattr)(directoryEntry, unsigned long*); - int (*getattr)(vfsmount* mnt, directoryEntry*, unsigned long*); -}; // Describes a mount struct vfsmount { vfsmount* mnt_parent; // fs we are mounted on - directoryEntry* mountpoint; // dentry of mount point - directoryEntry* root; // root of the mounted tree - superblock* sb; // pointer to the superblock + DirectoryNode* mountpoint; // dentry of mount point + DirectoryNode* root; // root of the mounted tree + FS_SUPER* sb; // pointer to the superblock unsigned int mnt_count; // keep track of users of this structure int mnt_flags; char* mnt_devname; // name of device eg /dev/dsk/hda1 }; -struct superblock; +struct FS_SUPER; // Represents a filesystem object (i.e. a file or directory or device) struct inode { unsigned long mode; // access permissions unsigned long uid; // user id owner unsigned long gid; // group id owner unsigned int flags; - inode_operations* i_op; // operations possible on inode - superblock* sb; + // operations possible on inode + int (*create)(inode*, DirectoryNode*, const char* ); + DirectoryNode* (*lookup)(inode* , DirectoryNode*); + int (*link)(DirectoryNode*, inode* , DirectoryNode*); + int (*unlink)(inode*, DirectoryNode*); + int (*symlink)(inode*, DirectoryNode*); + int (*mkdir)(inode*, DirectoryNode*, const char*); + int (*rmdir)(inode*, DirectoryNode*); + int (*rename)(inode*, DirectoryNode*, inode*, DirectoryNode*); + void (*truncate)(inode*); + int (*permission)(inode*, int); + int (*setattr)(DirectoryNode, unsigned long*); + int (*getattr)(vfsmount* mnt, DirectoryNode*, unsigned long*); + + FS_SUPER* sb; unsigned long ino; // unique number of this inode unsigned int links; // number of hard links void* device; @@ -62,43 +59,39 @@ struct inode { unsigned long mtime; // Modify time unsigned long ctime; // Creation time unsigned short bytes; // bytes consumed - file_operations* fop; + // File operations possible on Inode; + int(*write) (FILE* file, const void* buf, unsigned int len); + int(*read) (FILE* file, void* buf, unsigned int len); void* internal; // point to underlying representation of this virtual node (e.g. FAT entry or Directory Entry) }; -// Represents the possible operations on a directory entry -struct dentry_operations -{ - int (*compare)(directoryEntry*, char*, char* ); - int (*o_delete)(directoryEntry*); - void (*release)(directoryEntry*); - void (*iput)(directoryEntry*, inode* ); -}; // Represents the name of files in the filesystem // it identifies the file that an inode represents -struct directoryEntry { +struct DirectoryNode { char* name; // name of the file on the disk - directoryEntry* parent; // parent of the file + DirectoryNode* parent; // parent of the file inode* node; // node belongs to... - dentry_operations* op; - directoryEntry* children[]; - + int (*compare)(DirectoryNode*, char*, char* ); + int (*o_delete)(DirectoryNode*); + void (*release)(DirectoryNode*); + void (*iput)(DirectoryNode*, inode*); + List* children; }; // Represents a filesystem type struct filesystem { const char* name; - superblock* (*mount)(filesystem* self, const char* name, vfsmount* mnt); + FS_SUPER* (*mount)(filesystem* self, const char* name, vfsmount* mnt); }; // Represents a mounted filesystem -struct superblock { +struct FS_SUPER { void* device; // device associated with the filesystem unsigned long blocksize; unsigned long maxbytes; filesystem* type; unsigned long magic; // IDK - directoryEntry* root; // Root dentry + DirectoryNode* root; // Root dentry int count; // IDK void* fs_info; // pointer to raw filesystem info dentry_operations* d_op; @@ -106,10 +99,11 @@ struct superblock { }; // Represents an opened file -struct file { +struct FILE { inode* root; - size_t f_pos; // The next read/write position of this file descriptor; - file_operations* f_ops; + unsigned int f_pos; // The next read/write position of this file descriptor; + int(*write) (FILE* file, const void* buf, unsigned int len); + int(*read) (FILE* file, void* buf, unsigned int len); int flags; }; diff --git a/todo.md b/todo.md index cb71d04..b5556ea 100644 --- a/todo.md +++ b/todo.md @@ -4,7 +4,7 @@ This list keeps me focused and organised so I don't forget what -needs to be done. It is a expansion on the features markdown file which describes the features. Here I put things I need to remember +needs to be done. It is a expansion on the features markdown FILE which describes the features. Here I put things I need to remember to do on a more in depth level. ## -- -- 2.39.5 From 2d0bb16fad4c70f5adcee3af133aae29bf5e6b49 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 27 Feb 2023 00:32:16 +0100 Subject: [PATCH 108/115] Fixed up ACPI Version 1.0 checksum validation code --- CoreLib/Memory.cpp | 12 +++++------- kernel/acpi/acpi.cpp | 34 +++++++++++++++++++++++++--------- kernel/acpi/acpi.h | 7 ++++--- kernel/acpi/rsdp.cpp | 9 +-------- kernel/acpi/rsdp.h | 25 ++++++++++++++++++------- 5 files changed, 53 insertions(+), 34 deletions(-) diff --git a/CoreLib/Memory.cpp b/CoreLib/Memory.cpp index 491ed38..155dba1 100644 --- a/CoreLib/Memory.cpp +++ b/CoreLib/Memory.cpp @@ -16,16 +16,14 @@ void* memset (void* ptr, int value, size_t num) int memcmp( const void* ptr1, const void* ptr2, size_t num) { - const unsigned char * cs = (const unsigned char*) ptr1; - const unsigned char * ct = (const unsigned char*) ptr2; + auto* cs = (const unsigned char*) ptr1; + auto* ct = (const unsigned char*) ptr2; for (int i = 0 ; i < num ; i++, cs++, ct++ ){ - if( *cs < *ct){ - return -1; - } else if( *cs > *ct){ - return 1; - } + if( *cs != *ct) + return *cs - *ct; + } return 0; diff --git a/kernel/acpi/acpi.cpp b/kernel/acpi/acpi.cpp index e904ae6..bc83d08 100644 --- a/kernel/acpi/acpi.cpp +++ b/kernel/acpi/acpi.cpp @@ -1,5 +1,6 @@ #include "acpi.h" RSDPDescriptor* ACPI::rsd_ptr; +RSCPDescriptor20* ACPI::rsd2_ptr; RSDT* ACPI::rsd_table; @@ -8,19 +9,34 @@ void ACPI::initialize(){ // Find the Root System Description Pointer ACPI::rsd_ptr = FindRSD(); + printf("RSD address: 0x%x\n", ACPI::rsd_ptr); + //printRSD(rsd_ptr); - // is it valid - int sum = 0; - for (int i =0; i < 20 ; i++) { - sum += ((char*)rsd_ptr)[i]; + + if( rsd_ptr->Revision == 0 ){ + // Using veriosn 1.0 of the ACPI specifiction + int sum = rsd_ptr->Checksum; + for (int i =0; i < sizeof(RSDPDescriptor) ; i++) { + sum += ((char*)rsd_ptr)[i]; + } + + printf(" 0x%x sum\n", sum); + if(sum & 0xfff0) + printf("valid rsd!\n"); + else + printf("invalid rsd\n"); + + + // Get the Root System Description Table NOTE: might need memory mapping + //RSDT* rootSystemDescriptionTable = (RSDT*) (rsd_ptr->RsdtAddress + 0xC0000000); + } else{ + // parse it as of version2.0 + ACPI::rsd2_ptr = (RSCPDescriptor20*)rsd_ptr; } - printf(" 0x%x sum\n", sum); - return; - // Get the Root System Description Table - RSDT* rootSystemDescriptionTable = getRSDT((RSDPDescriptor *) rsd_ptr); +/* auto tableHeader = &rootSystemDescriptionTable->h; // do checksum @@ -31,5 +47,5 @@ void ACPI::initialize(){ } if( sum != 0) - printf("Table invalid!"); + printf("Table invalid!");*/ } \ No newline at end of file diff --git a/kernel/acpi/acpi.h b/kernel/acpi/acpi.h index c2293d0..97ca223 100644 --- a/kernel/acpi/acpi.h +++ b/kernel/acpi/acpi.h @@ -6,8 +6,9 @@ class ACPI { // In the future ACPI might start // doing more systems initialization - + + static RSDPDescriptor* rsd_ptr; + static RSCPDescriptor20* rsd2_ptr; + static RSDT* rsd_table; private: - static RSDPDescriptor* rsd_ptr; - static RSDT* rsd_table; }; \ No newline at end of file diff --git a/kernel/acpi/rsdp.cpp b/kernel/acpi/rsdp.cpp index f4408c2..3ed66e9 100644 --- a/kernel/acpi/rsdp.cpp +++ b/kernel/acpi/rsdp.cpp @@ -1,5 +1,6 @@ #include "rsdp.h" #include "../memory/VirtualMemoryManager.h" +#include "../../CoreLib/Memory.h" void printRSD(RSDPDescriptor* rsd){ @@ -16,7 +17,6 @@ void printRSD(RSDPDescriptor* rsd){ kterm_put('\n'); printf("Revision: %d\n", rsd->Revision); - printf("RSDT Address: 0x%x\n", rsd->RsdtAddress ); } RSDPDescriptor* FindRSD(){ @@ -31,10 +31,3 @@ RSDPDescriptor* FindRSD(){ } return (RSDPDescriptor*) memory_byte; } - - -RSDT* getRSDT(RSDPDescriptor* rsd){ - printf("rsdt Address: 0x%x\n", rsd->RsdtAddress); - return (RSDT*)rsd->RsdtAddress ; - -} \ No newline at end of file diff --git a/kernel/acpi/rsdp.h b/kernel/acpi/rsdp.h index 4ae6899..aef9445 100644 --- a/kernel/acpi/rsdp.h +++ b/kernel/acpi/rsdp.h @@ -3,13 +3,6 @@ #include #include -struct RSDPDescriptor { - char signature[8]; - uint8_t Checksum ; - char OEMID [6]; - uint8_t Revision; - uint32_t RsdtAddress; -}__attribute__((packed)); struct ACPISDTHeader{ char Signature[4]; @@ -28,6 +21,24 @@ struct RSDT{ struct ACPISDTHeader h; uint32_t PointerToSDT[]; // Length of array : (header.Length - sizeof(header))/ 4 }__attribute__((packed)); + + +struct RSDPDescriptor { + char signature[8]; + uint8_t Checksum ; + char OEMID [6]; + uint8_t Revision; + RSDT* RsdtAddress; +}__attribute__((packed)); + +struct RSCPDescriptor20{ + RSDPDescriptor base; + uint32_t Length; + uint64_t XsdtAddress; + uint8_t ExtendedChecksum; + uint8_t reserved[3]; +}__attribute__((packed)); + RSDPDescriptor* FindRSD(); void printRSD(RSDPDescriptor* rsd); -- 2.39.5 From 5781f730d96cfce562417546bbffa5943793fd34 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 27 Feb 2023 00:34:30 +0100 Subject: [PATCH 109/115] Implemented the basis for syscalls A software interrupt with vector 0x50 will cause a syscall to start executing. The EAX register will hold the syscall_num. Other registers and the stack can be used to hold further arguments. --- kernel/interrupts/idt.cpp | 35 ++++- kernel/interrupts/idt.h | 1 + kernel/irq_table.s | 131 ++++-------------- kernel/irs_table.s | 6 +- kernel/kernel.cpp | 54 ++++---- .../supervisorterminal/superVisorTerminal.cpp | 5 +- kernel/syscalls.h | 52 +++++++ 7 files changed, 141 insertions(+), 143 deletions(-) create mode 100644 kernel/syscalls.h diff --git a/kernel/interrupts/idt.cpp b/kernel/interrupts/idt.cpp index 50acd47..87c5975 100644 --- a/kernel/interrupts/idt.cpp +++ b/kernel/interrupts/idt.cpp @@ -3,6 +3,9 @@ #include "../drivers/ps-2/keyboard.h" #include "../i386/processor.h" #include "../memory/VirtualMemoryManager.h" +#include "../syscalls.h" + + IDT_entry idt_table[256]; IDT_ptr idt_ptr; @@ -18,7 +21,7 @@ void set_id_entry (uint8_t num , uint32_t base, uint16_t sel, uint8_t flags){ void irs_handler (registers* regs) { uint32_t FaultingAddress; - //printf("(IRS) Interrupt number: %d \r", regs.int_no); + printf("(IRS) Interrupt number: %d \n EAX: ", regs->int_no, regs->eax); switch (regs->int_no) { case 0: @@ -259,6 +262,29 @@ void irs_handler (registers* regs) { printf("EBP: 0x%x\n", regs->ebp); break; + case 50: + printf("SYSTEMCALL\n"); + printf("EAX 0x%x\n", regs->eax); + + switch (regs->eax) { + case 0x0: + printf("test!\n"); + break; + case 0x5: + sys_open(); + break; + case 0x10: + sys_read((FILE*)regs->ebx, (char*)regs->ecx); + break; + case 0x20: + sys_write((FILE*)regs->ebx, (const char*)regs->ecx, regs->edx); + break; + case 0x666: + sys_version(); + break; + + }; + break; default: // PANIC!!! break; @@ -269,9 +295,6 @@ void irs_handler (registers* regs) { } void irq_handler (registers regs) { - - - switch (regs.int_no) { case 0: pit_tick++; @@ -328,7 +351,7 @@ void irq_handler (registers regs) { } void initidt(){ - // Initialise the IDT pointer + // Initialize the IDT pointer idt_ptr.length = sizeof(IDT_entry) * 255; idt_ptr.base = (uint32_t)&idt_table; @@ -371,7 +394,7 @@ void initidt(){ set_id_entry(30, (uint32_t) irs30 , 0x08, 0x8E); set_id_entry(31, (uint32_t) irs31 , 0x08, 0x8E); - + set_id_entry(0x50, (uint32_t) irs50, 0x08, 0x8E); //print_serial("Remapping PIC\n"); PIC_remap(0x20, 0x28); diff --git a/kernel/interrupts/idt.h b/kernel/interrupts/idt.h index 0a87d8d..9a4d126 100644 --- a/kernel/interrupts/idt.h +++ b/kernel/interrupts/idt.h @@ -70,6 +70,7 @@ extern "C" { extern void irs29 (); extern void irs30 (); extern void irs31 (); + extern void irs50(); diff --git a/kernel/irq_table.s b/kernel/irq_table.s index fac477d..5b20edd 100644 --- a/kernel/irq_table.s +++ b/kernel/irq_table.s @@ -1,115 +1,32 @@ .globl irq0 -irq0: - cli - push $0 - push $0 - jmp irq_common -.globl irq1 -irq1: - cli - push $0 - push $1 - jmp irq_common +.macro IRQ NAME, VECTOR + .globl irq\NAME + irq\NAME: + cli + push $0 + push \VECTOR + jmp irq_common +.endm -.globl irq2 -irq2: - cli - push $0 - push $2 - jmp irq_common - -.globl irq3 -irq3: - cli - push $0 - push $3 - jmp irq_common - -.globl irq4 -irq4: - cli - push $0 - push $4 - jmp irq_common - -.globl irq5 -irq5: - cli - push $0 - push $5 - jmp irq_common - -.globl irq6 -irq6: - cli - push $0 - push $6 - jmp irq_common - -.globl irq7 -irq7: - cli - push $0 - push $7 - jmp irq_common - -.globl irq8 -irq8: - cli - push $0 - push $8 - jmp irq_common - -.globl irq9 -irq9: - cli - push $0 - push $9 - jmp irq_common - -.globl irq10 -irq10: - cli - push $0 - push $10 - jmp irq_common - -.globl irq11 -irq11: - cli - push $0 - push $11 - jmp irq_common +IRQ 0 $0 +IRQ 1 $1 +IRQ 2 $2 +IRQ 3 $3 +IRQ 4 $4 +IRQ 5 $5 +IRQ 6 $6 +IRQ 7 $7 +IRQ 8 $8 +IRQ 9 $9 +IRQ 10 $10 +IRQ 11 $11 +IRQ 12 $12 +IRQ 13 $13 +IRQ 14 $14 +IRQ 15 $15 -.globl irq12 -irq12: - cli - push $0 - push $12 - jmp irq_common - -.globl irq13 -irq13: - cli - push $0 - push $13 - jmp irq_common - -.globl irq14 -irq14: - cli - push $0 - push $14 - jmp irq_common - -.globl irq15 -irq15: - cli - push $0 - push $15 - jmp irq_common irq_common: pusha diff --git a/kernel/irs_table.s b/kernel/irs_table.s index a9c8cb8..6ecbb78 100644 --- a/kernel/irs_table.s +++ b/kernel/irs_table.s @@ -53,7 +53,7 @@ ISR_NOERRORCODE 28 $28 ISR_NOERRORCODE 29 $29 ISR_NOERRORCODE 30 $30 ISR_NOERRORCODE 31 $31 - +ISR_NOERRORCODE 50 $50 irs_common: pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax @@ -74,7 +74,7 @@ irs_common: call irs_handler - pop %eax + pop %eax // pop stack pointer pop %ebx // reload ther orignal data segment descriptor mov %bx, %ds mov %bx, %es @@ -82,6 +82,6 @@ irs_common: mov %bx, %gs popa - add $12, %esp # cleans push error and irs code + add $8, %esp # cleans push error and irs code iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP diff --git a/kernel/kernel.cpp b/kernel/kernel.cpp index d705045..5551f25 100644 --- a/kernel/kernel.cpp +++ b/kernel/kernel.cpp @@ -9,23 +9,37 @@ #include "drivers/vga/VBE.h" #include "pci/pci.h" #include "drivers/pit/pit.h" -#include "acpi/acpi.h" #include "i386/processor.h" #include "terminal/kterm.h" #include "interrupts/idt.h" #include "serial.h" #include "storage/vfs/vfs.h" #include "storage/filesystems/FAT/FAT.h" -#include "../CoreLib/Memory.h" +#include "acpi/acpi.h" +#include "memory/VirtualMemoryManager.h" +extern BootInfoBlock* BIB; extern "C" void LoadGlobalDescriptorTable(); extern "C" void jump_usermode(); -extern BootInfoBlock* BIB; + +void initBootDrive(){ + printf("Boot device: 0x%x\n", BIB->bootDeviceID); + unsigned int part3 = BIB->bootDeviceID & 0xFF; + unsigned int part2 = (BIB->bootDeviceID & 0xFF00) >> 8; + unsigned int part1 = (BIB->bootDeviceID & 0xFF0000) >> 16; + unsigned int drive = (BIB->bootDeviceID & 0xFF000000) >> 24; + if (drive == 0x80 ) + printf("booted from disk!\n"); + if(drive == 0x00) + printf("booted from floppy disk\n"); + + printf("Part1: %d, Part2: %d, Part3: %d\n", part1, part2 , part3); + ATAPIO::Identify(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); +} extern "C" void kernel () { - init_serial(); kterm_init(); @@ -42,32 +56,21 @@ extern "C" void kernel () initHeap(); pit_initialise(); ACPI::initialize(); - PCI::Scan(); processor::initialize(); processor::enable_protectedMode(); - printf("Boot device: 0x%x\n", BIB->bootDeviceID); - unsigned int part3 = BIB->bootDeviceID & 0xFF; - unsigned int part2 = (BIB->bootDeviceID & 0xFF00) >> 8; - unsigned int part1 = (BIB->bootDeviceID & 0xFF0000) >> 16; - unsigned int drive = (BIB->bootDeviceID & 0xFF000000) >> 24; - if (drive == 0x80 ) - printf("booted from disk!\n"); - if(drive == 0x00) - printf("booted from floppy disk\n"); - - printf("Part1: %d, Part2: %d, Part3: %d\n", part1, part2 , part3); - ATAPIO::Identify(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); - + initBootDrive(); VirtualFileSystem::initialize(); - printf("Lets open hello.txt\n"); - auto fontFile = VirtualFileSystem::open("/HELLO TXT", 0); - if(fontFile->flags == 0){ - uint16_t* contents = (uint16_t*) malloc(sizeof(uint16_t) * 256); - fontFile->read(fontFile, contents, 512); + - for(int i =0 ; i < fontFile->root->size; i++ ){ +#ifdef VFS_EXAMPLE + auto fontFile = VirtualFileSystem::open("/FONT PSF", 0); + if(grubcfg->flags == 0){ + uint16_t* contents = (uint16_t*) malloc(sizeof(uint16_t) * 256); + grubcfg->read(grubcfg, contents, 512); + + for(int i =0 ; i < grubcfg->root->size; i++ ){ kterm_put(contents[i] & 0x00ff); kterm_put(contents[i] >> 8); } @@ -76,8 +79,7 @@ extern "C" void kernel () }else{ printf("Could not find file\n"); } - - +#endif #ifdef USERMODE_RELEASE // Lets jump into user mode diff --git a/kernel/supervisorterminal/superVisorTerminal.cpp b/kernel/supervisorterminal/superVisorTerminal.cpp index ea6e9b2..2034e65 100644 --- a/kernel/supervisorterminal/superVisorTerminal.cpp +++ b/kernel/supervisorterminal/superVisorTerminal.cpp @@ -6,6 +6,8 @@ bool isRunning = true; extern "C" void startSuperVisorTerminal() { + + /* * Show a little banner for cuteness */ @@ -62,7 +64,8 @@ extern "C" void startSuperVisorTerminal() { // Show version information printf("========= Version ========\n"); - printf("Kernel v%d\n", 0); + + asm volatile ("movl $0x666, %eax; int $0x50"); } if(strncmp("CLEAR", command, characterCount) == 0) diff --git a/kernel/syscalls.h b/kernel/syscalls.h new file mode 100644 index 0000000..dddb884 --- /dev/null +++ b/kernel/syscalls.h @@ -0,0 +1,52 @@ +// +// Created by nigel on 26/02/23. +// +#pragma once + + +#include "terminal/kterm.h" +#include "storage/vfs/vfs_types.h" + + +void sys_version (){ + printf("KERNEL VERSION v0.4\n"); +} + +void sys_open(){ + +} + +void sys_read(FILE* file, char* data){ + file->read(file, data, 512); +} + +void sys_write(FILE* path, const char* data, size_t size){ + +} + +// NOTE: this should become our standard! +void syscall_handler(int syscall_no , uint32_t* args... ){ + switch(syscall_no){ + case 0x0: + printf("test!\n"); + break; + case 0x5: + // SYS_OPEN + // sys_open(); + break; + case 0x10: + // SYS_READ + // sys_read((FILE*)args[1], (char*) args[2] ); + break; + case 0x20: + // SYS_WRITE + //sys_write((FILE*)args[1], (const char*) args[2], (size_t)args[3]); + break; + case 0x666: + // SYS_VERSION + sys_version(); + break; + } +} + + -- 2.39.5 From e8df6ec6286d6ab2bcaaba11ffaca8c55d306a75 Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 11 Sep 2023 23:21:43 +0200 Subject: [PATCH 110/115] Updating Build scripts --- kernel/Makefile | 4 ++-- run.sh | 21 +++++++++++---------- scripts/run_qemu.sh | 8 +++++++- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/kernel/Makefile b/kernel/Makefile index 0c8f291..8fdb8ad 100644 --- a/kernel/Makefile +++ b/kernel/Makefile @@ -39,7 +39,7 @@ OFILES = $(OBJ_DIR)/boot.o \ OBJ_LINK_LIST = $(CRTI_OBJ) $(CRTBEGIN_OBJ) $(OFILES) $(CRTEND_OBJ) $(CRTN_OBJ) INTERNAL_OBJS = $(CRTI_OBJ) $(OFILES) $(CRTN_OBJ) -all: build +all: clean build clean: rm $(OBJ_DIR)/* -r @@ -49,7 +49,7 @@ build: $(OBJ_LINK_LIST) $(CPP) -T linker.ld -o $(BUILD_DIR)/myos.bin -ffreestanding -ggdb -Og -nostdlib $(OBJ_LINK_LIST) -lgcc -L ../build/CoreLib -lCoreLib # C++ definition -> Object files -$(OBJ_DIR)/kernel.o: +$(OBJ_DIR)/kernel.o: kernel.cpp $(CPP) -c kernel.cpp -o $(OBJ_DIR)/kernel.o $(CFLAGS) -fno-exceptions -fno-rtti $(OBJ_DIR)/kterm.o: diff --git a/run.sh b/run.sh index 99d34c5..6013267 100755 --- a/run.sh +++ b/run.sh @@ -3,23 +3,24 @@ PROC=$$ # Build the Corelib static library (cd CoreLib -if ! make; then - echo "Build failed!" +if ! make 2> warnings.log 1> /dev/null ; then + echo "Build Corelib failed!" kill -10 $PROC fi) # Build the kernel image (cd kernel -make clean -make -if ! make; then - echo "Build failed!" +# make clean +if ! make 2> warnings.log 1> /dev/null ; then + echo "Build kernel failed!" kill -10 $PROC fi) ./scripts/update_harddrive.sh - - -./scripts/run_qemu.sh - +args=""; +if [[ $1 == "-d" ]] +then + args="debug" +fi +./scripts/run_qemu.sh $args diff --git a/scripts/run_qemu.sh b/scripts/run_qemu.sh index 072a4bd..f728be6 100755 --- a/scripts/run_qemu.sh +++ b/scripts/run_qemu.sh @@ -1,7 +1,13 @@ #!/bin/bash +if [[ $1 == "debug" ]] +then + qemu-system-i386 -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-shutdown -no-reboot +else + qemu-system-i386 -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo +fi # Run from harddisk -qemu-system-i386 -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo +#qemu-system-i386 -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-shutdown -no-reboot # Run disk version # qemu-system-i386 -cdrom barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -s -d int -no-shutdown -no-reboot -- 2.39.5 From 29708067059985b545d96632fc8d85471b82308b Mon Sep 17 00:00:00 2001 From: Nigel Date: Mon, 11 Sep 2023 23:23:38 +0200 Subject: [PATCH 111/115] ACPI reading memory when mapped to higher half --- kernel/acpi/acpi.cpp | 37 +++++++++++++++++++++++++++++++------ kernel/acpi/rsdp.cpp | 15 +++++++++++++-- kernel/acpi/rsdp.h | 5 ++--- 3 files changed, 46 insertions(+), 11 deletions(-) diff --git a/kernel/acpi/acpi.cpp b/kernel/acpi/acpi.cpp index bc83d08..66d4c7a 100644 --- a/kernel/acpi/acpi.cpp +++ b/kernel/acpi/acpi.cpp @@ -1,20 +1,22 @@ #include "acpi.h" +#include "../../CoreLib/Memory.h" +#include "../memory/VirtualMemoryManager.h" + RSDPDescriptor* ACPI::rsd_ptr; RSCPDescriptor20* ACPI::rsd2_ptr; RSDT* ACPI::rsd_table; - +const int KERNEL_OFFSET = 0xC0000000; void ACPI::initialize(){ - // Find the Root System Description Pointer ACPI::rsd_ptr = FindRSD(); printf("RSD address: 0x%x\n", ACPI::rsd_ptr); - //printRSD(rsd_ptr); + printRSD(rsd_ptr); if( rsd_ptr->Revision == 0 ){ - // Using veriosn 1.0 of the ACPI specifiction + // Using version 1.0 of the ACPI specification int sum = rsd_ptr->Checksum; for (int i =0; i < sizeof(RSDPDescriptor) ; i++) { sum += ((char*)rsd_ptr)[i]; @@ -26,11 +28,34 @@ void ACPI::initialize(){ else printf("invalid rsd\n"); + printf("rsdp: 0x%x\n", rsd_ptr); + + printf("0x%x address\n", (rsd_ptr->RsdtAddress)); + Immediate_Map(rsd_ptr->RsdtAddress + KERNEL_OFFSET, rsd_ptr->RsdtAddress); + + RSDT* rootSystemDescriptionTable = (RSDT*)(rsd_ptr->RsdtAddress + KERNEL_OFFSET); + //printf("0x%x Root System Descriptor address\n", rootSystemDescriptionTable); + // checksum it, but we'll ignore it for now + printf("signature "); + for (int i = 0; i < 4; i++) { + kterm_put( rootSystemDescriptionTable->h.Signature[i]); + } + kterm_put('\n'); + + + int entries = (rootSystemDescriptionTable->h.Length - sizeof (rootSystemDescriptionTable->h)) /4; + printf("%d num entries\n", entries); + for( int i = 0; i < entries; i++){ + ACPISDTHeader* h = (ACPISDTHeader*) rootSystemDescriptionTable->PointerToSDT + i ; + if(strncmp(h->Signature, "FACP", 4)){ + printf("Found FACP Entry!\n"); + } + } + - // Get the Root System Description Table NOTE: might need memory mapping - //RSDT* rootSystemDescriptionTable = (RSDT*) (rsd_ptr->RsdtAddress + 0xC0000000); } else{ // parse it as of version2.0 + printf("rsd2_ptr\n"); ACPI::rsd2_ptr = (RSCPDescriptor20*)rsd_ptr; } diff --git a/kernel/acpi/rsdp.cpp b/kernel/acpi/rsdp.cpp index 3ed66e9..8882f7f 100644 --- a/kernel/acpi/rsdp.cpp +++ b/kernel/acpi/rsdp.cpp @@ -23,11 +23,22 @@ RSDPDescriptor* FindRSD(){ char* memory_byte = (char*) 0x000f2e14; const void* string = "RSD PTR "; - for( ; (uint32_t) memory_byte < 0x00100000; memory_byte+=10){ + + for( ; (uint32_t) memory_byte < 0x0100000; memory_byte+=10){ if( memcmp(memory_byte , string , 8 ) == 0 ) { printf("RSD PTR found at 0x%x !\n", memory_byte); + return (RSDPDescriptor*) memory_byte; break; } } - return (RSDPDescriptor*) memory_byte; + + memory_byte = (char*) 0x000E0000; + for ( ;(uint32_t) memory_byte < 0x000FFFFF; memory_byte += 1) + { + if( memcmp(memory_byte , string , 8 ) == 0 ) { + printf("RSD PTR found at 0x%x !\n", memory_byte); + return (RSDPDescriptor*) memory_byte; + break; + } + } } diff --git a/kernel/acpi/rsdp.h b/kernel/acpi/rsdp.h index aef9445..77014fc 100644 --- a/kernel/acpi/rsdp.h +++ b/kernel/acpi/rsdp.h @@ -16,10 +16,9 @@ struct ACPISDTHeader{ uint32_t CreatorRevision; }; - struct RSDT{ struct ACPISDTHeader h; - uint32_t PointerToSDT[]; // Length of array : (header.Length - sizeof(header))/ 4 + uint32_t *PointerToSDT; // Length of array : (header.Length - sizeof(header))/ 4 }__attribute__((packed)); @@ -28,7 +27,7 @@ struct RSDPDescriptor { uint8_t Checksum ; char OEMID [6]; uint8_t Revision; - RSDT* RsdtAddress; + uint32_t RsdtAddress; }__attribute__((packed)); struct RSCPDescriptor20{ -- 2.39.5 From 04470edcc6bdfa7543624da3b94524410535fb1f Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 27 Oct 2023 18:03:45 +0200 Subject: [PATCH 112/115] Adding gdb init and adjusting some of the build automation steps --- .gdbinit | 7 +++++++ .gitignore | 2 ++ run.sh | 1 + scripts/create_symbol_lookup.sh | 5 +++-- scripts/run_qemu.sh | 4 ++-- 5 files changed, 15 insertions(+), 4 deletions(-) create mode 100644 .gdbinit diff --git a/.gdbinit b/.gdbinit new file mode 100644 index 0000000..283cb0c --- /dev/null +++ b/.gdbinit @@ -0,0 +1,7 @@ +target remote localhost:1234 + +file root/boot/myos.bin +symbol-file kernel.sym + +break prekernel/prekernel.cpp:18 +continue \ No newline at end of file diff --git a/.gitignore b/.gitignore index 689ffcd..daf06ba 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,5 @@ root/ *.a +/CoreLib/warnings.log +/kernel/warnings.log diff --git a/run.sh b/run.sh index 6013267..20cebe8 100755 --- a/run.sh +++ b/run.sh @@ -17,6 +17,7 @@ if ! make 2> warnings.log 1> /dev/null ; then fi) ./scripts/update_harddrive.sh +./scripts/create_symbol_lookup.sh args=""; if [[ $1 == "-d" ]] diff --git a/scripts/create_symbol_lookup.sh b/scripts/create_symbol_lookup.sh index a150d4a..5d6dd6c 100755 --- a/scripts/create_symbol_lookup.sh +++ b/scripts/create_symbol_lookup.sh @@ -1,3 +1,4 @@ #!/bin/bash - -objcopy --only-keep-debug build/kernel/myos.bin kernel.sym \ No newline at end of file +echo "creating symbols file" +echo $(pwd) +objcopy --only-keep-debug root/boot/myos.bin kernel.sym \ No newline at end of file diff --git a/scripts/run_qemu.sh b/scripts/run_qemu.sh index f728be6..bf9cac3 100755 --- a/scripts/run_qemu.sh +++ b/scripts/run_qemu.sh @@ -2,9 +2,9 @@ if [[ $1 == "debug" ]] then - qemu-system-i386 -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-shutdown -no-reboot + qemu-system-i386 -s -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-shutdown -no-reboot else - qemu-system-i386 -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo + qemu-system-i386 -s -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo fi # Run from harddisk #qemu-system-i386 -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo -d int -no-shutdown -no-reboot -- 2.39.5 From 64c87a2a58204c2ec001d74d1c4a4fcceb59288d Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 27 Oct 2023 18:04:09 +0200 Subject: [PATCH 113/115] Fixing an issue in the CoreLib --- CoreLib/ctype.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CoreLib/ctype.cpp b/CoreLib/ctype.cpp index 2c81ade..13e9cde 100644 --- a/CoreLib/ctype.cpp +++ b/CoreLib/ctype.cpp @@ -108,7 +108,7 @@ int isprint (int ch){ return 1; if(isspace(ch)) return 1; - + return 0; } -- 2.39.5 From e82392e9d98eab07cd5dd525043742d1e305489b Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 27 Oct 2023 18:07:11 +0200 Subject: [PATCH 114/115] FAT Filesystem implementation additions --- CoreLib/Makefile | 2 - kernel/kernel.cpp | 33 ++++------- kernel/memory/VirtualMemoryManager.cpp | 56 ++++++++++--------- kernel/storage/filesystems/FAT/FAT.cpp | 18 +++++- .../partitiontables/mbr/MasterBootRecord.h | 16 +++--- kernel/storage/vfs/vfs.cpp | 21 ++++++- kernel/terminal/kterm.cpp | 29 +++++----- 7 files changed, 101 insertions(+), 74 deletions(-) diff --git a/CoreLib/Makefile b/CoreLib/Makefile index cb74d68..19b06ef 100644 --- a/CoreLib/Makefile +++ b/CoreLib/Makefile @@ -15,8 +15,6 @@ $(OUTPUTFILE): $(OFILES) pwd ar -rc $(OUTPUTFILE) $(OFILES) - - $(OBJ_FOLDER)/ctype.o: ctype.cpp $(CPP) -c ctype.cpp -o $(OBJ_FOLDER)/ctype.o $(CFLAGS) diff --git a/kernel/kernel.cpp b/kernel/kernel.cpp index 5551f25..4375be3 100644 --- a/kernel/kernel.cpp +++ b/kernel/kernel.cpp @@ -42,43 +42,33 @@ extern "C" void kernel () { init_serial(); kterm_init(); - + print_serial("kterm initialized...\n"); setup_tss(); initGDT(); initidt(); LoadGlobalDescriptorTable(); flush_tss(); printf("Memory setup complete!\n"); - + print_serial("Memory initialized....\n"); // Enable interrupts asm volatile("STI"); - initHeap(); - pit_initialise(); - ACPI::initialize(); - PCI::Scan(); + print_serial("Heap initialized...\n"); + //pit_initialise(); + + + //ACPI::initialize(); + //PCI::Scan(); processor::initialize(); processor::enable_protectedMode(); initBootDrive(); VirtualFileSystem::initialize(); - - + print_serial("Run test!"); +#define VFS_EXAMPLE #ifdef VFS_EXAMPLE auto fontFile = VirtualFileSystem::open("/FONT PSF", 0); - if(grubcfg->flags == 0){ - uint16_t* contents = (uint16_t*) malloc(sizeof(uint16_t) * 256); - grubcfg->read(grubcfg, contents, 512); - - for(int i =0 ; i < grubcfg->root->size; i++ ){ - kterm_put(contents[i] & 0x00ff); - kterm_put(contents[i] >> 8); - } - kterm_put('\n'); - free((void*)contents); - }else{ - printf("Could not find file\n"); - } + printf("Size of font file: %d bytes", fontFile->root->size); // COOL This Works like a charm #endif #ifdef USERMODE_RELEASE @@ -86,6 +76,7 @@ extern "C" void kernel () jump_usermode(); #else startSuperVisorTerminal(); + #endif } \ No newline at end of file diff --git a/kernel/memory/VirtualMemoryManager.cpp b/kernel/memory/VirtualMemoryManager.cpp index e866b28..a8ec187 100644 --- a/kernel/memory/VirtualMemoryManager.cpp +++ b/kernel/memory/VirtualMemoryManager.cpp @@ -1,4 +1,6 @@ #include "VirtualMemoryManager.h" +#include "../../CoreLib/Memory.h" + #define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) extern uint32_t boot_page_directory[1024] ; // points to the wrong location @@ -14,7 +16,7 @@ void flush_cr3(){ void AllocatePage(uint32_t vaddr) { - uint32_t page_aligned_address = ALIGN(vaddr, 4096); + //uint32_t page_aligned_address = ALIGN(vaddr, 4096); // allocate a page at virtual address int PageDirectoryEntryIndex = vaddr >> 22; @@ -54,16 +56,16 @@ void AllocatePage(uint32_t vaddr) void FreePage(uint32_t vaddr ) { - uint32_t page_aligned_address = ALIGN(vaddr, 4096); + // uint32_t page_aligned_address = ALIGN(vaddr, 4096); // allocate a page at virtual address int PageDirectoryEntryIndex = vaddr >> 22; int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; - uint32_t* pageTable = (uint32_t*)(boot_page_directory[PageDirectoryEntryIndex] & 0xFFFFE000 + 0xC0000000); + uint32_t* pageTable = (uint32_t*)(boot_page_directory[PageDirectoryEntryIndex] & (0xFFFFE000 + 0xC0000000)); - void* physicalAddressToFree = (void*)(pageTable[PageTableEntryIndex] & 0xFFFFE000 + 0xC0000000); + void* physicalAddressToFree = (void*)(pageTable[PageTableEntryIndex] & (0xFFFFE000 + 0xC0000000)); free_block(physicalAddressToFree); pageTable[PageTableEntryIndex] = 0x0; @@ -80,9 +82,9 @@ void Immediate_Map ( uint32_t vaddr, uint32_t paddr) int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; printf("Map address at PDE 0x%x PTE 0x%x\n", PageDirectoryEntryIndex, PageTableEntryIndex); - - if ((boot_page_directory - 0xC0000000)[PageDirectoryEntryIndex] & 0x1 ) - { + printf("boot pagedirectoy address: 0x%x\n", &boot_page_directory); + printf("PDE : 0x%x\n", boot_page_directory[PageTableEntryIndex]); + if (boot_page_directory[PageDirectoryEntryIndex] & 0x1 ) { printf("Directory entry is marked as present\n"); } else { @@ -90,37 +92,39 @@ void Immediate_Map ( uint32_t vaddr, uint32_t paddr) // mark the page table as present and allocate a physical block for it void* new_page_dir = allocate_block(); - printf("New page directory address 0x%x\n", new_page_dir); + memset(new_page_dir, 0 , 1024 * sizeof (uint32_t)); + printf("New page directory address 0x%x\n", &new_page_dir); boot_page_directory[PageDirectoryEntryIndex] = (uint32_t)new_page_dir | 0x3; - } printf("PDE found at : 0x%x\n", (uint32_t) &boot_page_directory[PageDirectoryEntryIndex]); - uint32_t* page_table = (uint32_t*)(boot_page_directory[PageDirectoryEntryIndex] & 0xFFFFE000) ; - //page_table = (uint32_t*) ((uint32_t)page_table - 0xC0000000); // remove kernel offset - printf("Page table address: 0x%x\n", (uint32_t)page_table); + uint32_t* page_table = (uint32_t*)(boot_page_directory[PageDirectoryEntryIndex] & 0xFFFFE000) ; + printf("Page table address: 0x%x\n", (uint32_t)page_table); - // check if the page table entry is marked as present - if ( page_table[PageTableEntryIndex] & 0x1 ) - { - printf("page already present!\n"); - printf("Entry found at addr: 0x%x\n", &(page_table[PageTableEntryIndex])); - } else{ - printf("Mapping a physical page.\n"); - // Map the entry to a physical page - page_table[PageTableEntryIndex] = (uint32_t)(paddr | 0x3); - } + // check if the page table entry is marked as present + if ( page_table[PageTableEntryIndex] & 0x1 ) + { + printf("page already present!\n"); + printf("Entry found at addr: 0x%x\n", &(page_table[PageTableEntryIndex])); + } else{ + printf("Mapping a physical page.\n"); + // Map the entry to a physical page + page_table[PageTableEntryIndex] = (uint32_t)(paddr | 0x3); + } - asm ("cli; invlpg (%0); sti" :: "r" (vaddr) : "memory" ); + asm ("invlpg (%0)" :: "r" (vaddr) : "memory" ); } + +// NOT IMPLEMENTED void Immediate_Unmap(uint32_t vaddr) { // NOTE: I will implement lazy unmapping for now - uint32_t page_aligned_address = ALIGN(vaddr, 4096); + //uint32_t page_aligned_address = ALIGN(vaddr, 4096); // allocate a page at virtual address - int PageDirectoryEntryIndex = vaddr >> 22; - int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; + //int PageDirectoryEntryIndex = vaddr >> 22; + //int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; + } diff --git a/kernel/storage/filesystems/FAT/FAT.cpp b/kernel/storage/filesystems/FAT/FAT.cpp index 80465b9..e181f7e 100644 --- a/kernel/storage/filesystems/FAT/FAT.cpp +++ b/kernel/storage/filesystems/FAT/FAT.cpp @@ -107,10 +107,10 @@ DirectoryNode* FAT::Lookup (inode* currentDir , DirectoryNode* dir) for(int i = 0; i < sizeof(data) / sizeof (DIR); i++) { DIR* entry = (DIR*)((uint32_t)directory + (i * sizeof(DIR))); + + if( entry->Name[0] == FAT::FREE_DIR || - entry->Name[0] == FAT::FREE_DIR_2 || - entry->Name[0] == 0xE5 || entry->ATTR & FAT::ATTRIBUTES::ATTR_VOLUME_ID || entry->ATTR & FAT::ATTRIBUTES::ATTR_SYSTEM || entry->ATTR & FAT::ATTRIBUTES::ATTR_HIDDEN @@ -118,6 +118,20 @@ DirectoryNode* FAT::Lookup (inode* currentDir , DirectoryNode* dir) continue; } + + if( entry->ATTR & FAT::ATTRIBUTES::ATTR_DIRECTORY){ + printf("entry in directory\n"); + for(int i = 0; i < 11 ;i ++) + kterm_put(entry->Name[i]); + kterm_put('\n'); + } + + + + + if( entry->Name[0] == FAT::FREE_DIR_2 ) + break; + auto* dirNode = (DirectoryNode*) malloc(sizeof (DirectoryNode)); char* name = (char*)malloc(sizeof(char[11])); diff --git a/kernel/storage/partitiontables/mbr/MasterBootRecord.h b/kernel/storage/partitiontables/mbr/MasterBootRecord.h index 1cb207c..4f83ceb 100644 --- a/kernel/storage/partitiontables/mbr/MasterBootRecord.h +++ b/kernel/storage/partitiontables/mbr/MasterBootRecord.h @@ -22,22 +22,22 @@ inline MBR* GetPartitions(bool DEBUG = false){ int S =1; uint32_t LBA = (C*HPC+H) * SPT + (S-1); - MBR* mbr =(MBR*) malloc(sizeof (MBR)); + uint16_t* mbr =(uint16_t*) malloc(sizeof (MBR)); - ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, (uint16_t*)mbr); + ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, LBA, mbr ); + auto bootRecord = (MBR*)(mbr); - - printf("MBR (In Memory) Address 0x%x, Size = %d\n", mbr, sizeof (MBR)); + printf("MBR (In Memory) Address 0x%x, Size = %d\n", bootRecord, sizeof (MBR)); if(DEBUG){ - printf("BootSector: 0x%x\n", mbr->ValidBootsector ); + printf("BootSector: 0x%x\n", bootRecord->ValidBootsector ); for( int i = 0 ; i < 4 ; i ++){ - PartitionTableEntry PT = mbr->TableEntries[i]; + PartitionTableEntry PT = bootRecord->TableEntries[i]; printf("Partition %d [ %d sectors, PartitionType: 0x%x, 0x%x, \nLBA Start: 0x%x ]\n" , - i, PT.Number_sectors_inPartition, PT.PartitionType, mbr->uniqueID, PT.LBA_partition_start ); + i, PT.Number_sectors_inPartition, PT.PartitionType, bootRecord->uniqueID, PT.LBA_partition_start ); } } - return mbr; + return bootRecord; } diff --git a/kernel/storage/vfs/vfs.cpp b/kernel/storage/vfs/vfs.cpp index d432632..0eb140e 100644 --- a/kernel/storage/vfs/vfs.cpp +++ b/kernel/storage/vfs/vfs.cpp @@ -80,20 +80,37 @@ FILE* VirtualFileSystem::open(const char* pathname, int flags){ } // let's just loop through the folder first + printf("looking for: "); + for(int i = 0; i < 5; i++) + kterm_put(nextdir[i]); + kterm_put('\n'); auto* child = rootentry->children; while(child->next != nullptr){ - auto* directory = (DirectoryNode*)child->data; + + for(int i = 0; i < 11 ; i++) + kterm_put(directory->name[i]); + kterm_put('\n'); + if( directory->compare(directory, directory->name, nextdir) == 0){ nextdir = strtok(nullptr, "/", &tokstate); + printf("Found dir!\n"); if(nextdir == NULL){ file->root = directory->node; file->flags =0; file->read = FAT::Read; return file; } + printf("continue searching next directory!\n"); + if(directory->children == nullptr) + directory->node->lookup(directory->node, directory); + + + child = directory->children; + + }else{ + child = child->next; } - child = child->next; } diff --git a/kernel/terminal/kterm.cpp b/kernel/terminal/kterm.cpp index ede8bbd..263d799 100644 --- a/kernel/terminal/kterm.cpp +++ b/kernel/terminal/kterm.cpp @@ -21,7 +21,14 @@ void kterm_init () { kterm_row = 0; kterm_column = 0; kterm_color = vga_entry_color ( VGA_COLOR_LIGHT_GREY , VGA_COLOR_BLACK); - kterm_buffer = (uint16_t*) 0xC03FF000; + + //Physical address + // 0xB8000 + // Virtual address + // 0xC03FF000 + + //kterm_buffer = ((uint16_t*) 0xB8000); + kterm_buffer = ((uint16_t*) 0xC03FF000 ); for (size_t y = 0; y < VGA_HEIGHT; y++ ){ for( size_t x = 0; x < VGA_WIDTH; x++){ @@ -59,7 +66,6 @@ void disable_cursor() outb(0x3D5, 0x20); } - void update_cursor(int x, int y){ uint16_t pos = y * VGA_WIDTH + x; @@ -86,8 +92,6 @@ int get_cursor_y (uint16_t cursor_pos ) { return cursor_pos / VGA_WIDTH; } - - /** * With the help from: * https://whiteheadsoftware.dev/operating-systems-development-for-dummies/ @@ -134,7 +138,6 @@ void kterm_writestring(const char* data ){ kterm_write(data, strlen(data)); } - static void itoa (char *buf, int base, int d) { char *p = buf; char *p1, *p2; @@ -173,28 +176,28 @@ static void itoa (char *buf, int base, int d) { void printf ( const char *format, ...) { - char **arg = (char **)&format; + auto **arg = (unsigned char **)&format; int c; char buf[20]; arg++; - while ((c = *format++) != 0){ + while ((c = *(const unsigned char*)format++) != 0){ if( c != '%') kterm_put(c); else{ - char *p, *p2; + char const *p, *p2; int pad0 = 0, pad = 0; - c = *format++; + c = *(const unsigned char*)format++; if(c =='0'){ pad0 = 1; - c = *format++; + c = *(const unsigned char*)format++; } if ( c >= '0' && c <= '9'){ pad = c - '0'; - c = *format++; + c = *(const unsigned char*)format++; } switch (c) @@ -210,7 +213,7 @@ void printf ( const char *format, ...) { break; case 's': - p = *arg++; + p = (char const *)*arg++; if(!p) p = "(null)"; @@ -224,7 +227,7 @@ void printf ( const char *format, ...) { default: - kterm_put(*((int *)arg++)); + kterm_put(*(int *) arg++); // NOLINT(cppcoreguidelines-narrowing-conversions) break; } } -- 2.39.5 From 252249283526351d10e0fe928d1ce396ad7bc000 Mon Sep 17 00:00:00 2001 From: Nigel Date: Fri, 27 Oct 2023 18:32:03 +0200 Subject: [PATCH 115/115] Couple of small changes * Commented out the map page function call to handle page not present * Mapped the ACPI_RECLAIMABLE_MEMORY * Set VBE to false when VBE is not initialized by the bootloader --- kernel/interrupts/idt.cpp | 2 +- kernel/prekernel/prekernel.cpp | 18 +++++++----------- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/kernel/interrupts/idt.cpp b/kernel/interrupts/idt.cpp index 87c5975..4b20f2e 100644 --- a/kernel/interrupts/idt.cpp +++ b/kernel/interrupts/idt.cpp @@ -191,7 +191,7 @@ void irs_handler (registers* regs) { printf("* Page protection violation!\n"); } else{ printf("* Page not-present!\n"); - Immediate_Map(FaultingAddress, FaultingAddress - 0xC0000000); + //Immediate_Map(FaultingAddress, FaultingAddress); } diff --git a/kernel/prekernel/prekernel.cpp b/kernel/prekernel/prekernel.cpp index e12bcf0..5e4f059 100644 --- a/kernel/prekernel/prekernel.cpp +++ b/kernel/prekernel/prekernel.cpp @@ -2,6 +2,8 @@ #include #include "multiboot.h" #include "../memory/PhysicalMemoryManager.h" +#include "../memory/VirtualMemoryManager.h" +#include "../acpi/acpi.h" #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) #define VADDR_TO_PADDR(vaddr) (vaddr - 0xC0000000) @@ -10,7 +12,6 @@ BootInfoBlock* BIB; extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) { - /* * Check Multiboot magic number */ @@ -21,18 +22,13 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) } mbi = PADDR_TO_VADDR(mbi); - - // Setup the physical memory manager immmediatly - // Doing so saves the complications of doing it later when - // paging is enabled - /* If we got a memory map from our bootloader we should be parsing it to find out the memory regions available. */ if (CHECK_FLAG(mbi->flags, 6)) - { - + { + // Calculate total memory size uint32_t RAM_size = 0; for( @@ -56,6 +52,8 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) deallocate_region(mmap->addr, mmap->len); if(mmap->type == MULTIBOOT_MEMORY_ACPI_RECLAIMABLE) allocate_region(mmap->addr, mmap->len); + // memory map + Immediate_Map(mmap->addr , mmap->addr); if(mmap->type == MULTIBOOT_MEMORY_RESERVED) allocate_region(mmap->addr, mmap->len); if(mmap->type == MULTIBOOT_MEMORY_NVS) @@ -99,8 +97,6 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) uint32_t i; BIB->GrubModuleCount = mbi->mods_count; - - for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ } @@ -135,6 +131,6 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) // NOTE: Do something with it.. (Store it , process it etc...) } else{ - BIB->EnabledVBE; + BIB->EnabledVBE = false; } } -- 2.39.5