Compare commits

11 Commits

Author SHA1 Message Date
6086b04054 Added klog as a new logging system
* The logging system sends the message to both VGA and serial
* The serial print uses color to indicate the category of the message

Message Categories  |  Colours
Debug			Green
Info			Blue
Error			Red
2023-10-28 22:28:21 +02:00
9c5667c454 Created a proper driver for the serial bus
* The driver can write to any of the pre-defined serial COM ports
* The driver can read from any of the pre-defined serial COM ports (Untested)
2023-10-28 21:51:04 +02:00
2522492835 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
2023-10-28 20:42:28 +02:00
e82392e9d9 FAT Filesystem implementation additions 2023-10-27 18:07:11 +02:00
64c87a2a58 Fixing an issue in the CoreLib 2023-10-27 18:04:09 +02:00
04470edcc6 Adding gdb init and adjusting some of the build automation steps 2023-10-27 18:03:45 +02:00
2970806705 ACPI reading memory when mapped to higher half 2023-09-11 23:23:38 +02:00
e8df6ec628 Updating Build scripts 2023-09-11 23:21:43 +02:00
5781f730d9 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.
2023-02-27 00:34:30 +01:00
2d0bb16fad Fixed up ACPI Version 1.0 checksum validation code 2023-02-27 00:32:16 +01:00
e6901f0526 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
2023-02-26 13:44:41 +01:00
39 changed files with 806 additions and 719 deletions

7
.gdbinit Normal file
View File

@ -0,0 +1,7 @@
target remote localhost:1234
file root/boot/myos.bin
symbol-file kernel.sym
break prekernel/prekernel.cpp:18
continue

2
.gitignore vendored
View File

@ -11,3 +11,5 @@ root/
*.a *.a
/CoreLib/warnings.log
/kernel/warnings.log

12
CoreLib/List.h Normal file
View File

@ -0,0 +1,12 @@
//
// Created by nigel on 25/02/23.
//
#pragma once
class List {
public:
List* next;
void* data;
};

View File

@ -15,8 +15,6 @@ $(OUTPUTFILE): $(OFILES)
pwd pwd
ar -rc $(OUTPUTFILE) $(OFILES) ar -rc $(OUTPUTFILE) $(OFILES)
$(OBJ_FOLDER)/ctype.o: ctype.cpp $(OBJ_FOLDER)/ctype.o: ctype.cpp
$(CPP) -c ctype.cpp -o $(OBJ_FOLDER)/ctype.o $(CFLAGS) $(CPP) -c ctype.cpp -o $(OBJ_FOLDER)/ctype.o $(CFLAGS)

View File

@ -16,23 +16,21 @@ void* memset (void* ptr, int value, size_t num)
int memcmp( const void* ptr1, const void* ptr2, size_t num) int memcmp( const void* ptr1, const void* ptr2, size_t num)
{ {
const unsigned char * cs = (const unsigned char*) ptr1; auto* cs = (const unsigned char*) ptr1;
const unsigned char * ct = (const unsigned char*) ptr2; auto* ct = (const unsigned char*) ptr2;
for (int i = 0 ; i < num ; i++, cs++, ct++ ){ for (int i = 0 ; i < num ; i++, cs++, ct++ ){
if( *cs < *ct){ if( *cs != *ct)
return -1; return *cs - *ct;
} else if( *cs > *ct){
return 1;
}
} }
return 0; return 0;
} }
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++){ for( int i = 0; i < count; i++){
((char *)dest)[i] = ((const char*)src)[i]; ((char *)dest)[i] = ((const char*)src)[i];
} }

View File

@ -7,7 +7,7 @@ void* memset (void* ptr, int value, size_t num);
int memcmp( const void* ptr1, const void* ptr2, 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); size_t strlen(const char* str);

View File

@ -108,7 +108,7 @@ int isprint (int ch){
return 1; return 1;
if(isspace(ch)) if(isspace(ch))
return 1; return 1;
return 0;
} }

View File

@ -27,7 +27,7 @@ Enumerating the PCI bus
Correctly identified our ATAPI device 🎉 Correctly identified our ATAPI device 🎉
![Reading Files from FAT-16](screenshots/ReadingFilesFromFAT16.png) \ ![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
________________________ ________________________

View File

@ -34,12 +34,14 @@ OFILES = $(OBJ_DIR)/boot.o \
$(OBJ_DIR)/ataDevice.o \ $(OBJ_DIR)/ataDevice.o \
$(OBJ_DIR)/rsdp.o \ $(OBJ_DIR)/rsdp.o \
$(OBJ_DIR)/acpi.o \ $(OBJ_DIR)/acpi.o \
$(OBJ_DIR)/fat.o $(OBJ_DIR)/fat.o \
$(OBJ_DIR)/serial.o \
$(OBJ_DIR)/klog.o
OBJ_LINK_LIST = $(CRTI_OBJ) $(CRTBEGIN_OBJ) $(OFILES) $(CRTEND_OBJ) $(CRTN_OBJ) OBJ_LINK_LIST = $(CRTI_OBJ) $(CRTBEGIN_OBJ) $(OFILES) $(CRTEND_OBJ) $(CRTN_OBJ)
INTERNAL_OBJS = $(CRTI_OBJ) $(OFILES) $(CRTN_OBJ) INTERNAL_OBJS = $(CRTI_OBJ) $(OFILES) $(CRTN_OBJ)
all: build all: clean build
clean: clean:
rm $(OBJ_DIR)/* -r rm $(OBJ_DIR)/* -r
@ -49,7 +51,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 $(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 # 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 $(CPP) -c kernel.cpp -o $(OBJ_DIR)/kernel.o $(CFLAGS) -fno-exceptions -fno-rtti
$(OBJ_DIR)/kterm.o: $(OBJ_DIR)/kterm.o:
@ -121,6 +123,12 @@ $(OBJ_DIR)/processor.o:
$(OBJ_DIR)/fat.o: $(OBJ_DIR)/fat.o:
$(CPP) -c storage/filesystems/FAT/FAT.cpp -o $(OBJ_DIR)/fat.o $(CFLAGS) -fno-exceptions -fno-rtti $(CPP) -c storage/filesystems/FAT/FAT.cpp -o $(OBJ_DIR)/fat.o $(CFLAGS) -fno-exceptions -fno-rtti
$(OBJ_DIR)/serial.o:
$(CPP) -c drivers/serial/serial.cpp -o $(OBJ_DIR)/serial.o $(CFLAGS) -fno-exceptions -fno-rtti
$(OBJ_DIR)/klog.o:
$(CPP) -c klog.cpp -o $(OBJ_DIR)/klog.o $(CFLAGS) -fno-exceptions -fno-rtti
# Assembly -> Object files # Assembly -> Object files
$(OBJ_DIR)/boot.o: $(OBJ_DIR)/boot.o:
$(AS) boot/boot.s -o $(OBJ_DIR)/boot.o $(AS) boot/boot.s -o $(OBJ_DIR)/boot.o

View File

@ -1,26 +1,67 @@
#include "acpi.h" #include "acpi.h"
#include "../../CoreLib/Memory.h"
#include "../memory/VirtualMemoryManager.h"
RSDPDescriptor* ACPI::rsd_ptr; RSDPDescriptor* ACPI::rsd_ptr;
RSCPDescriptor20* ACPI::rsd2_ptr;
RSDT* ACPI::rsd_table; RSDT* ACPI::rsd_table;
const int KERNEL_OFFSET = 0xC0000000;
void ACPI::initialize(){ void ACPI::initialize(){
// Find the Root System Description Pointer // Find the Root System Description Pointer
ACPI::rsd_ptr = FindRSD(); ACPI::rsd_ptr = FindRSD();
printf("RSD address: 0x%x\n", ACPI::rsd_ptr);
printRSD(rsd_ptr);
// is it valid
int sum = 0; if( rsd_ptr->Revision == 0 ){
for (int i =0; i < 20 ; i++) { // Using version 1.0 of the ACPI specification
sum += ((char*)rsd_ptr)[i]; 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");
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");
}
}
} else{
// parse it as of version2.0
printf("rsd2_ptr\n");
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; auto tableHeader = &rootSystemDescriptionTable->h;
// do checksum // do checksum
@ -31,5 +72,5 @@ void ACPI::initialize(){
} }
if( sum != 0) if( sum != 0)
printf("Table invalid!"); printf("Table invalid!");*/
} }

View File

@ -6,8 +6,9 @@ class ACPI {
// In the future ACPI might start // In the future ACPI might start
// doing more systems initialization // doing more systems initialization
static RSDPDescriptor* rsd_ptr;
static RSCPDescriptor20* rsd2_ptr;
static RSDT* rsd_table;
private: private:
static RSDPDescriptor* rsd_ptr;
static RSDT* rsd_table;
}; };

View File

@ -1,5 +1,6 @@
#include "rsdp.h" #include "rsdp.h"
#include "../memory/VirtualMemoryManager.h" #include "../memory/VirtualMemoryManager.h"
#include "../../CoreLib/Memory.h"
void printRSD(RSDPDescriptor* rsd){ void printRSD(RSDPDescriptor* rsd){
@ -16,25 +17,28 @@ void printRSD(RSDPDescriptor* rsd){
kterm_put('\n'); kterm_put('\n');
printf("Revision: %d\n", rsd->Revision); printf("Revision: %d\n", rsd->Revision);
printf("RSDT Address: 0x%x\n", rsd->RsdtAddress );
} }
RSDPDescriptor* FindRSD(){ RSDPDescriptor* FindRSD(){
char* memory_byte = (char*) 0x000f2e14; char* memory_byte = (char*) 0x000f2e14;
const void* string = "RSD PTR "; 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 ) { if( memcmp(memory_byte , string , 8 ) == 0 ) {
printf("RSD PTR found at 0x%x !\n", memory_byte); printf("RSD PTR found at 0x%x !\n", memory_byte);
return (RSDPDescriptor*) memory_byte;
break; 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;
}
}
} }
RSDT* getRSDT(RSDPDescriptor* rsd){
printf("rsdt Address: 0x%x\n", rsd->RsdtAddress);
return (RSDT*)rsd->RsdtAddress ;
}

View File

@ -3,13 +3,6 @@
#include <CoreLib/Memory.h> #include <CoreLib/Memory.h>
#include <stdint-gcc.h> #include <stdint-gcc.h>
struct RSDPDescriptor {
char signature[8];
uint8_t Checksum ;
char OEMID [6];
uint8_t Revision;
uint32_t RsdtAddress;
}__attribute__((packed));
struct ACPISDTHeader{ struct ACPISDTHeader{
char Signature[4]; char Signature[4];
@ -23,11 +16,28 @@ struct ACPISDTHeader{
uint32_t CreatorRevision; uint32_t CreatorRevision;
}; };
struct RSDT{ struct RSDT{
struct ACPISDTHeader h; 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)); }__attribute__((packed));
struct RSDPDescriptor {
char signature[8];
uint8_t Checksum ;
char OEMID [6];
uint8_t Revision;
uint32_t RsdtAddress;
}__attribute__((packed));
struct RSCPDescriptor20{
RSDPDescriptor base;
uint32_t Length;
uint64_t XsdtAddress;
uint8_t ExtendedChecksum;
uint8_t reserved[3];
}__attribute__((packed));
RSDPDescriptor* FindRSD(); RSDPDescriptor* FindRSD();
void printRSD(RSDPDescriptor* rsd); void printRSD(RSDPDescriptor* rsd);

View File

@ -1,19 +1,52 @@
#include "serial.h" #include "serial.h"
#include "../../io/io.h"
Serial Serial::init() { // Initializes communication according to the spec given
// No clue what to setup yet! Serial::Serial(SerialConfig config) {
port = config.port;
// Disable interrupts
outb(config.port + 1, 0x00);
return Serial(); // Enable DLAB
outb(config.port + 3, 0x80);
// set the baudrate
outb(config.port + 0, 0x03);
outb(config.port + 1, 0x00);
// configure for 8bits, no parity, one stop bit
outb(config.port + 3, 0x03);
// Enable FIFO, clear them, with 14-byte threshhold
outb(config.port + 2, 0xC7);
// Enable IRQ's, RTS/DSR set
outb(config.port + 4, 0x0B );
// Set in loopback mode, test the serial chip.
outb(config.port + 4, 0x1E);
// TEST
outb(config.port + 0 , 0xAE);
if(inb(config.port + 0) != 0xAE)
return ; // FAIL
outb(config.port + 4, 0x0F);
return ;
} }
void Serial::print(){ void Serial::write(void* data, int len) {
// Do nothing! while (is_transmit_empty() == 0); // Wait for transmit queue to be free
for (int i = 0; i < len ; i++){
outb(port, ((uint8_t*)data)[i]);
}
} }
Serial::Serial(){ char Serial::read() {
// Do nothing! return inb(port);
} }
Serial::~Serial(){ int Serial::is_transmit_empty() {
// Do nothing! return inb(port + 5) & 0x20;
} }

View File

@ -1,19 +1,29 @@
#pragma once #pragma once
// For now these are the standard
// serial ports we can talk to
enum SERIALPORT {
COM1 = 0x3F8,
COM2 = 0x2F8,
COM3 = 0x3E8,
COM4 = 0x2E8
};
class Serial { struct SerialConfig {
SERIALPORT port;
char baud_rate_lo ;
char baud_rate_hi;
};
class Serial {
public: public:
static Serial init(); Serial (SerialConfig config );
void print();
private: char read();
const int COM1 = 0x3F8; void write(void* data, int length);
const int COM2 = 0x2F8;
const int COM3 = 0x3E8;
const int COM4 = 0x2E8;
private:
Serial(); SERIALPORT port;
~Serial(); int is_transmit_empty();
}; };

View File

@ -3,6 +3,9 @@
#include "../drivers/ps-2/keyboard.h" #include "../drivers/ps-2/keyboard.h"
#include "../i386/processor.h" #include "../i386/processor.h"
#include "../memory/VirtualMemoryManager.h" #include "../memory/VirtualMemoryManager.h"
#include "../syscalls.h"
IDT_entry idt_table[256]; IDT_entry idt_table[256];
IDT_ptr idt_ptr; 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) { void irs_handler (registers* regs) {
uint32_t FaultingAddress; 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) switch (regs->int_no)
{ {
case 0: case 0:
@ -188,7 +191,7 @@ void irs_handler (registers* regs) {
printf("* Page protection violation!\n"); printf("* Page protection violation!\n");
} else{ } else{
printf("* Page not-present!\n"); printf("* Page not-present!\n");
Immediate_Map(FaultingAddress, FaultingAddress - 0xC0000000); //Immediate_Map(FaultingAddress, FaultingAddress);
} }
@ -259,6 +262,29 @@ void irs_handler (registers* regs) {
printf("EBP: 0x%x\n", regs->ebp); printf("EBP: 0x%x\n", regs->ebp);
break; 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: default:
// PANIC!!! // PANIC!!!
break; break;
@ -269,9 +295,6 @@ void irs_handler (registers* regs) {
} }
void irq_handler (registers regs) { void irq_handler (registers regs) {
switch (regs.int_no) { switch (regs.int_no) {
case 0: case 0:
pit_tick++; pit_tick++;
@ -328,7 +351,7 @@ void irq_handler (registers regs) {
} }
void initidt(){ void initidt(){
// Initialise the IDT pointer // Initialize the IDT pointer
idt_ptr.length = sizeof(IDT_entry) * 255; idt_ptr.length = sizeof(IDT_entry) * 255;
idt_ptr.base = (uint32_t)&idt_table; 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(30, (uint32_t) irs30 , 0x08, 0x8E);
set_id_entry(31, (uint32_t) irs31 , 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"); //print_serial("Remapping PIC\n");
PIC_remap(0x20, 0x28); PIC_remap(0x20, 0x28);

View File

@ -70,6 +70,7 @@ extern "C" {
extern void irs29 (); extern void irs29 ();
extern void irs30 (); extern void irs30 ();
extern void irs31 (); extern void irs31 ();
extern void irs50();

View File

@ -1,115 +1,32 @@
.globl irq0 .globl irq0
irq0:
cli
push $0
push $0
jmp irq_common
.globl irq1 .macro IRQ NAME, VECTOR
irq1: .globl irq\NAME
cli irq\NAME:
push $0 cli
push $1 push $0
jmp irq_common push \VECTOR
jmp irq_common
.endm
.globl irq2 IRQ 0 $0
irq2: IRQ 1 $1
cli IRQ 2 $2
push $0 IRQ 3 $3
push $2 IRQ 4 $4
jmp irq_common IRQ 5 $5
IRQ 6 $6
.globl irq3 IRQ 7 $7
irq3: IRQ 8 $8
cli IRQ 9 $9
push $0 IRQ 10 $10
push $3 IRQ 11 $11
jmp irq_common IRQ 12 $12
IRQ 13 $13
.globl irq4 IRQ 14 $14
irq4: IRQ 15 $15
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: irq_common:
pusha pusha

View File

@ -53,7 +53,7 @@ ISR_NOERRORCODE 28 $28
ISR_NOERRORCODE 29 $29 ISR_NOERRORCODE 29 $29
ISR_NOERRORCODE 30 $30 ISR_NOERRORCODE 30 $30
ISR_NOERRORCODE 31 $31 ISR_NOERRORCODE 31 $31
ISR_NOERRORCODE 50 $50
irs_common: irs_common:
pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax pusha # Pushes edi,esi,ebp,esp,ebx,edx,ecx,eax
@ -74,7 +74,7 @@ irs_common:
call irs_handler call irs_handler
pop %eax pop %eax // pop stack pointer
pop %ebx // reload ther orignal data segment descriptor pop %ebx // reload ther orignal data segment descriptor
mov %bx, %ds mov %bx, %ds
mov %bx, %es mov %bx, %es
@ -82,6 +82,6 @@ irs_common:
mov %bx, %gs mov %bx, %gs
popa 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 iret # pops 5 things at once: CS, EIP, EFLAGS, SS, and ESP

View File

@ -9,42 +9,21 @@
#include "drivers/vga/VBE.h" #include "drivers/vga/VBE.h"
#include "pci/pci.h" #include "pci/pci.h"
#include "drivers/pit/pit.h" #include "drivers/pit/pit.h"
#include "acpi/acpi.h"
#include "i386/processor.h" #include "i386/processor.h"
#include "terminal/kterm.h" #include "terminal/kterm.h"
#include "interrupts/idt.h" #include "interrupts/idt.h"
#include "serial.h"
#include "storage/vfs/vfs.h" #include "storage/vfs/vfs.h"
#include "storage/filesystems/FAT/FAT.h" #include "storage/filesystems/FAT/FAT.h"
#include "acpi/acpi.h"
#include "memory/VirtualMemoryManager.h"
#include "klog.h"
extern BootInfoBlock* BIB;
extern "C" void LoadGlobalDescriptorTable(); extern "C" void LoadGlobalDescriptorTable();
extern "C" void jump_usermode(); extern "C" void jump_usermode();
extern BootInfoBlock* BIB;
extern "C" void kernel () void initBootDrive(){
{
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::Scan();
processor::initialize();
processor::enable_protectedMode();
printf("Boot device: 0x%x\n", BIB->bootDeviceID); printf("Boot device: 0x%x\n", BIB->bootDeviceID);
unsigned int part3 = BIB->bootDeviceID & 0xFF; unsigned int part3 = BIB->bootDeviceID & 0xFF;
unsigned int part2 = (BIB->bootDeviceID & 0xFF00) >> 8; unsigned int part2 = (BIB->bootDeviceID & 0xFF00) >> 8;
@ -57,92 +36,53 @@ extern "C" void kernel ()
printf("Part1: %d, Part2: %d, Part3: %d\n", part1, part2 , part3); printf("Part1: %d, Part2: %d, Part3: %d\n", part1, part2 , part3);
ATAPIO::Identify(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER); ATAPIO::Identify(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER);
auto* bpb = FAT::getBPB(false); }
auto* mbr = GetPartitions(false);
auto fsType = FAT::determineFATType(bpb); extern "C" void kernel ()
switch (fsType) { {
case FAT_TYPE::FAT12: kterm_init();
printf("FAT12 Disk!\n"); setup_tss();
break; initGDT();
case FAT_TYPE::FAT16: initidt();
printf("FAT16 Disk!\n"); LoadGlobalDescriptorTable();
break; flush_tss();
case FAT_TYPE::FAT32:
printf("FAT32 Disk!\n");
break;
}
// list files in root print_info("Memory setup complete!\n");
int total_sectors = bpb->TotSec32; // Enable interrupts
int fat_size = bpb->FATSz16; asm volatile("STI");
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);
}
}
initHeap();
//pit_initialise();
//ACPI::initialize();
//PCI::Scan();
processor::initialize();
processor::enable_protectedMode();
initBootDrive();
VirtualFileSystem::initialize();
// VirtualFileSystem::initialize(); print_dbg("Hello debug!\n");
print_info("Hello info!\n");
print_err("Hello error!\n");
// VirtualFileSystem::open("/hello.txt", 0); #define VFS_EXAMPLE
#ifdef VFS_EXAMPLE
auto fontFile = VirtualFileSystem::open("/FONT PSF", 0);
printf("Size of font file: %d bytes\n", fontFile->root->size); // COOL This Works like a charm
#endif
#ifdef USERMODE_RELEASE #ifdef USERMODE_RELEASE
// Lets jump into user mode // Lets jump into user mode
jump_usermode(); jump_usermode();
#else #else
startSuperVisorTerminal(); startSuperVisorTerminal();
#endif #endif
} }

58
kernel/klog.cpp Normal file
View File

@ -0,0 +1,58 @@
//
// Created by nigel on 10/28/23.
//
#include "klog.h"
#include "terminal/kterm.h"
#include <CoreLib/Memory.h>
const char* ForeGroundColourReset = "\e[39m";
void print_dbg(const char* message, ...){
auto **arg = (unsigned char**)&message;
// Send it to the VGA
printf(message, arg);
// Now send the message to the serial
Serial com1= Serial({
COM1,
0x03,
0x00
});
const char* ForeGroundColour = "\e[32m";
com1.write((void*)ForeGroundColour, strlen(ForeGroundColour));
com1.write((void*)message, strlen(message));
com1.write((void*)ForeGroundColourReset, strlen(ForeGroundColourReset));
}
void print_info(const char* message, ...){
auto **arg = (unsigned char**)&message;
// Send it to the VGA
printf(message, arg);
Serial com1 = Serial({
COM1,
0x03,
0x00
});
const char* ForeGroundColour = "\e[34m";
com1.write((void*)ForeGroundColour, strlen(ForeGroundColour));
com1.write((void*)message, strlen(message));
com1.write((void*)ForeGroundColourReset, strlen(ForeGroundColourReset));
}
void print_err(const char* message, ...){
auto **arg = (unsigned char**)&message;
// Send it to the VGA
printf(message, arg);
Serial com1 = Serial({
COM1,
0x03,
0x00
});
const char* ForeGroundColour = "\e[31m";
com1.write((void*)ForeGroundColour, strlen(ForeGroundColour));
com1.write((void*)message, strlen(message));
com1.write((void*)ForeGroundColourReset, strlen(ForeGroundColourReset));
}

12
kernel/klog.h Normal file
View File

@ -0,0 +1,12 @@
//
// Created by nigel on 10/28/23.
//
#pragma once
#include "drivers/serial/serial.h"
void print_dbg(const char* message, ...);
void print_info(const char* message, ...);
void print_err(const char* message, ...);

View File

@ -1,4 +1,6 @@
#include "VirtualMemoryManager.h" #include "VirtualMemoryManager.h"
#include "../../CoreLib/Memory.h"
#define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align)) #define ALIGN(addr, align) (((addr) & ~((align) - 1 )) + (align))
extern uint32_t boot_page_directory[1024] ; // points to the wrong location extern uint32_t boot_page_directory[1024] ; // points to the wrong location
@ -14,7 +16,7 @@ void flush_cr3(){
void AllocatePage(uint32_t vaddr) 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 // allocate a page at virtual address
int PageDirectoryEntryIndex = vaddr >> 22; int PageDirectoryEntryIndex = vaddr >> 22;
@ -54,16 +56,16 @@ void AllocatePage(uint32_t vaddr)
void FreePage(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 // allocate a page at virtual address
int PageDirectoryEntryIndex = vaddr >> 22; int PageDirectoryEntryIndex = vaddr >> 22;
int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; 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); free_block(physicalAddressToFree);
pageTable[PageTableEntryIndex] = 0x0; pageTable[PageTableEntryIndex] = 0x0;
@ -80,9 +82,9 @@ void Immediate_Map ( uint32_t vaddr, uint32_t paddr)
int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF;
printf("Map address at PDE 0x%x PTE 0x%x\n", PageDirectoryEntryIndex, PageTableEntryIndex); printf("Map address at PDE 0x%x PTE 0x%x\n", PageDirectoryEntryIndex, PageTableEntryIndex);
printf("boot pagedirectoy address: 0x%x\n", &boot_page_directory);
if ((boot_page_directory - 0xC0000000)[PageDirectoryEntryIndex] & 0x1 ) printf("PDE : 0x%x\n", boot_page_directory[PageTableEntryIndex]);
{ if (boot_page_directory[PageDirectoryEntryIndex] & 0x1 ) {
printf("Directory entry is marked as present\n"); printf("Directory entry is marked as present\n");
} else { } 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 // mark the page table as present and allocate a physical block for it
void* new_page_dir = allocate_block(); 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; boot_page_directory[PageDirectoryEntryIndex] = (uint32_t)new_page_dir | 0x3;
} }
printf("PDE found at : 0x%x\n", (uint32_t) &boot_page_directory[PageDirectoryEntryIndex]); printf("PDE found at : 0x%x\n", (uint32_t) &boot_page_directory[PageDirectoryEntryIndex]);
uint32_t* page_table = (uint32_t*)(boot_page_directory[PageDirectoryEntryIndex] & 0xFFFFE000) ; 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);
printf("Page table address: 0x%x\n", (uint32_t)page_table);
// check if the page table entry is marked as present // check if the page table entry is marked as present
if ( page_table[PageTableEntryIndex] & 0x1 ) if ( page_table[PageTableEntryIndex] & 0x1 )
{ {
printf("page already present!\n"); printf("page already present!\n");
printf("Entry found at addr: 0x%x\n", &(page_table[PageTableEntryIndex])); printf("Entry found at addr: 0x%x\n", &(page_table[PageTableEntryIndex]));
} else{ } else{
printf("Mapping a physical page.\n"); printf("Mapping a physical page.\n");
// Map the entry to a physical page // Map the entry to a physical page
page_table[PageTableEntryIndex] = (uint32_t)(paddr | 0x3); 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) void Immediate_Unmap(uint32_t vaddr)
{ {
// NOTE: I will implement lazy unmapping for now // 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 // allocate a page at virtual address
int PageDirectoryEntryIndex = vaddr >> 22; //int PageDirectoryEntryIndex = vaddr >> 22;
int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF; //int PageTableEntryIndex = (vaddr >> 12) & 0x1FFF;
} }

View File

@ -2,6 +2,8 @@
#include <stddef.h> #include <stddef.h>
#include "multiboot.h" #include "multiboot.h"
#include "../memory/PhysicalMemoryManager.h" #include "../memory/PhysicalMemoryManager.h"
#include "../memory/VirtualMemoryManager.h"
#include "../acpi/acpi.h"
#define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit))) #define CHECK_FLAG(flags, bit) ((flags) & (1 <<(bit)))
#define VADDR_TO_PADDR(vaddr) (vaddr - 0xC0000000) #define VADDR_TO_PADDR(vaddr) (vaddr - 0xC0000000)
@ -10,7 +12,6 @@ BootInfoBlock* BIB;
extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi) extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi)
{ {
/* /*
* Check Multiboot magic number * Check Multiboot magic number
*/ */
@ -21,18 +22,13 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi)
} }
mbi = PADDR_TO_VADDR(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 If we got a memory map from our bootloader we
should be parsing it to find out the memory regions available. should be parsing it to find out the memory regions available.
*/ */
if (CHECK_FLAG(mbi->flags, 6)) if (CHECK_FLAG(mbi->flags, 6))
{ {
// Calculate total memory size // Calculate total memory size
uint32_t RAM_size = 0; uint32_t RAM_size = 0;
for( for(
@ -56,6 +52,8 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi)
deallocate_region(mmap->addr, mmap->len); deallocate_region(mmap->addr, mmap->len);
if(mmap->type == MULTIBOOT_MEMORY_ACPI_RECLAIMABLE) if(mmap->type == MULTIBOOT_MEMORY_ACPI_RECLAIMABLE)
allocate_region(mmap->addr, mmap->len); allocate_region(mmap->addr, mmap->len);
// memory map
Immediate_Map(mmap->addr , mmap->addr);
if(mmap->type == MULTIBOOT_MEMORY_RESERVED) if(mmap->type == MULTIBOOT_MEMORY_RESERVED)
allocate_region(mmap->addr, mmap->len); allocate_region(mmap->addr, mmap->len);
if(mmap->type == MULTIBOOT_MEMORY_NVS) if(mmap->type == MULTIBOOT_MEMORY_NVS)
@ -99,8 +97,6 @@ extern "C" void prekernelSetup ( unsigned long magic, multiboot_info_t* mbi)
uint32_t i; uint32_t i;
BIB->GrubModuleCount = mbi->mods_count; BIB->GrubModuleCount = mbi->mods_count;
for(i = 0, mod = (multiboot_module_t *) mbi->mods_addr; i < mbi->mods_count; i++ , mod++){ 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...) // NOTE: Do something with it.. (Store it , process it etc...)
} else{ } else{
BIB->EnabledVBE; BIB->EnabledVBE = false;
} }
} }

View File

@ -1,58 +0,0 @@
#pragma once
#include "terminal/kterm.h"
#include "io/io.h"
#define PORT 0x3f8
static int init_serial() {
#ifdef __VERBOSE__
printf("Init Serial\n");
#endif
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;
}
inline int is_transmit_empty() {
return inb(PORT + 5) & 0x20;
}
inline void write_serial(char a) {
while (is_transmit_empty() == 0);
outb(PORT,a);
}
inline int serial_received() {
return inb(PORT + 5) & 1;
}
inline char read_serial() {
while (serial_received() == 0);
return inb(PORT);
}
inline void print_serial(const char* string ){
for(size_t i = 0; i < strlen(string); i ++){
write_serial(string[i]);
}
}

View File

@ -4,10 +4,14 @@
#include "FAT.h" #include "FAT.h"
#include "../../ata pio/ATAPIO.h" #include "../../ata pio/ATAPIO.h"
#include "../../../memory/KernelHeap.h" #include "../../../memory/KernelHeap.h"
#include "../../../../CoreLib/Memory.h"
#include "../../partitiontables/mbr/MasterBootRecord.h" #include "../../partitiontables/mbr/MasterBootRecord.h"
#include "../../../../CoreLib/ctype.h"
#include "../../../../CoreLib/Memory.h"
#include <CoreLib/Memory.h> #include <CoreLib/Memory.h>
superblock* FAT::Mount(filesystem *fs, const char* name ,vfsmount *mnt) #include <CoreLib/ctype.h>
// exposed driver API
FS_SUPER* FAT::Mount(filesystem *fs, const char* name , vfsmount *mnt)
{ {
if( strncmp (fs->name, "fat", 3 ) != 0 ) if( strncmp (fs->name, "fat", 3 ) != 0 )
@ -15,58 +19,152 @@ superblock* FAT::Mount(filesystem *fs, const char* name ,vfsmount *mnt)
printf("Can't mount filesystem with none fat type!\n"); printf("Can't mount filesystem with none fat type!\n");
return nullptr; return nullptr;
} }
auto* bpb = GetBiosParameterBlock();
auto fat_type = DetermineFATType(bpb);
superblock* sb = (superblock*) malloc(sizeof(superblock)); if(fat_type != FAT_TYPE::FAT16)
directoryEntry* root = (directoryEntry*) malloc(sizeof (directoryEntry)); 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->name = (char*) name;
root->node = nullptr; root->node = node;
root->parent = nullptr; root->parent = nullptr;
root->compare = FAT::Compare;
dentry_operations* op = (dentry_operations*) malloc(sizeof(dentry_operations));
op->compare = FAT::compare;
root->op = op;
mnt->mnt_count =1; mnt->mnt_count =1;
mnt->mnt_devname = "QEMU HDD"; mnt->mnt_devname = "QEMU HDD";
mnt->mnt_flags = 0; mnt->mnt_flags = 0;
mnt->mnt_parent = nullptr; mnt->mnt_parent = nullptr;
mnt->root = root; mnt->root = root;
mnt->sb = sb; mnt->sb = sb;
sb->type = fs; sb->type = fs;
sb->root = root; sb->root = root;
//sb->fs_info = getBPB(); sb->fs_info = bpb;
return sb; return sb;
} }
int FAT::Read(file* file, void* buffer , int length) FILE FAT::Open(char* filename){
{
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);
if( a == b ){ return (FILE){nullptr, 0, nullptr, nullptr, 1} ;
return strncmp(filename, filename2, a); }
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)));
FAT_TYPE FAT::determineFATType(BiosParameterBlock* bpb){ if(
entry->Name[0] == FAT::FREE_DIR ||
entry->ATTR & FAT::ATTRIBUTES::ATTR_VOLUME_ID ||
entry->ATTR & FAT::ATTRIBUTES::ATTR_SYSTEM ||
entry->ATTR & FAT::ATTRIBUTES::ATTR_HIDDEN
){
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]));
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;
}
return (DirectoryNode*)dir;
}
// internal functions
FAT_TYPE FAT::DetermineFATType(BiosParameterBlock* bpb){
int RootDirSector = ((bpb->RootEntCnt * 32) + (bpb->BytsPerSec -1)) / bpb->BytsPerSec; int RootDirSector = ((bpb->RootEntCnt * 32) + (bpb->BytsPerSec -1)) / bpb->BytsPerSec;
int FATSz = 0; int FATSz = 0;
if(bpb->FATSz16 != 0){ if(bpb->FATSz16 != 0){
@ -93,7 +191,7 @@ FAT_TYPE FAT::determineFATType(BiosParameterBlock* bpb){
return FAT_TYPE::FAT32; return FAT_TYPE::FAT32;
} }
}; };
BiosParameterBlock* FAT::getBPB( bool DEBUG ){ BiosParameterBlock* FAT::GetBiosParameterBlock(bool DEBUG ){
BiosParameterBlock* bpb = (BiosParameterBlock*) malloc(sizeof(BiosParameterBlock)); BiosParameterBlock* bpb = (BiosParameterBlock*) malloc(sizeof(BiosParameterBlock));
uint16_t StartAddress = 0x00 ; uint16_t StartAddress = 0x00 ;
ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, StartAddress, (uint16_t*) bpb); ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, StartAddress, (uint16_t*) bpb);
@ -114,24 +212,20 @@ BiosParameterBlock* FAT::getBPB( bool DEBUG ){
} }
uint16_t FAT::GetFATEntry (BiosParameterBlock* bpb, unsigned int cluster){ uint16_t FAT::GetFATEntry (BiosParameterBlock* bpb, unsigned int cluster){
int FATSz = bpb->FATSz16; int FATSz = bpb->FATSz16;
int FATOffset = 0; int FATOffset = 0;
FAT_TYPE type = FAT::determineFATType(bpb); FAT_TYPE type = FAT::DetermineFATType(bpb);
if( type == FAT_TYPE::FAT16){ if( type == FAT_TYPE::FAT16){
FATOffset = cluster *2; FATOffset = cluster *2;
} else if( type == FAT_TYPE::FAT32){ } else if( type == FAT_TYPE::FAT32){
FATOffset = cluster * 4; FATOffset = cluster * 4;
} }
int thisFATSecNum = bpb->RsvdSecCnt + (FATOffset / bpb->BytsPerSec); // Sector number containing the entry for the cluster int thisFATSecNum = bpb->RsvdSecCnt + (FATOffset / bpb->BytsPerSec); // Sector number containing the entry for the cluster
// For any other FAT other than the default // For any other FAT other than the default
// SectorNumber = (FATNumber * FATSz) + ThisFATSecNum // SectorNumber = (FATNumber * FATSz) + ThisFATSecNum
uint16_t buff[bpb->BytsPerSec]; uint16_t buff[bpb->BytsPerSec];
ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, thisFATSecNum, buff ); 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 int thisFATEntOffset = FATOffset % bpb->BytsPerSec; // offset for the entry in the sector containing the entry for the cluster
uint16_t ClusterEntryValue = 0; uint16_t ClusterEntryValue = 0;
// Get the FATEntry // Get the FATEntry
@ -145,7 +239,6 @@ uint16_t FAT::GetFATEntry (BiosParameterBlock* bpb, unsigned int cluster){
} }
} }
uint16_t FAT::DetermineFreeSpace() uint16_t FAT::DetermineFreeSpace()
{ {
// Loop through all FAT entries in all FAT's // Loop through all FAT entries in all FAT's
@ -166,35 +259,15 @@ the FAT entry for the last cluster) must be set to 0x0 during volume initializat
} }
int FAT::GetSectorOfRootDirectory (BiosParameterBlock* bpb) int FAT::GetSectorOfRootDirectory (BiosParameterBlock* bpb)
{ {
return (bpb->RsvdSecCnt + (bpb->NumFATs * bpb->FATSz16)); return (bpb->RsvdSecCnt + (bpb->NumFATs * bpb->FATSz16));
} }
unsigned int FAT::RootDirSize(BiosParameterBlock* bpb) unsigned int FAT::RootDirSize(BiosParameterBlock* bpb)
{ {
return ((bpb->RootEntCnt * 32) + (bpb->BytsPerSec -1)) /bpb->BytsPerSec; 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 ){ void FAT::OpenSubdir(DIR* directory, BiosParameterBlock* bpb ){
unsigned int cluster = directory->FstClusLo; unsigned int cluster = directory->FstClusLo;
@ -252,9 +325,9 @@ void FAT::OpenSubdir(DIR* directory, BiosParameterBlock* bpb ){
} }
} }
void FAT::ReadFileContents(DIR* fileEntry , BiosParameterBlock* bpb){
void FAT::readFile(DIR* fileEntry , BiosParameterBlock* bpb){
unsigned int cluster = fileEntry->FstClusLo; unsigned int cluster = fileEntry->FstClusLo;
printf("cluster NR: %x\n", cluster);
unsigned int FATEntry = FAT::GetFATEntry(bpb, cluster); unsigned int FATEntry = FAT::GetFATEntry(bpb, cluster);
unsigned int root_dir_sectors = FAT::RootDirSize(bpb); unsigned int root_dir_sectors = FAT::RootDirSize(bpb);
unsigned int fat_size = bpb->FATSz16; unsigned int fat_size = bpb->FATSz16;
@ -269,140 +342,63 @@ void FAT::readFile(DIR* fileEntry , BiosParameterBlock* bpb){
kterm_put(n & 0x00ff); kterm_put(n & 0x00ff);
kterm_put(n >> 8); 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]; int first_root_dir_sector = first_data_sector - root_dir_sectors;
//ToDosFileName(DirectoryName, DosFileName, 11); //int first_sector_of_cluster = ((cluster - 2) * bpb->SecPerClus) + first_data_sector;
DosFileName[11] =0; uint16_t data[256];
ATAPIO::Read(ATAPIO_PORT::Primary, DEVICE_DRIVE::MASTER, first_root_dir_sector, data);
for (int sector=0; sector <14 ; sector++){ auto* RootDirectory = (DIR*)data;
ATAPIO::Read(BUS_PORT::Primary, DEVICE_DRIVE::MASTER, mountInfo.rootOffset + sector, (uint16_t*)buf); for(int i = 0; i < sizeof(data) / sizeof (DIR); i++)
directory = (PDIRECTORY) buf; {
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){ if(entry->Name[0] == FAT::FREE_DIR || entry->Name[0] == FAT::FREE_DIR_2 || entry->Name[0] == 0xE5){
strcpy(file.name, DirectoryName); continue;
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++;
} }
}
// Can't find file
file.flags = -1;
return file;
}
void fsysFATRead(PFILE file, unsigned char* buffer, unsigned int length){ if(entry->ATTR & FAT::ATTRIBUTES::ATTR_HIDDEN){
if(file){ continue;
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); if(entry->ATTR & FAT::ATTRIBUTES::ATTR_SYSTEM)
unsigned int FAT_Sector = 1 + (FAT_Offset / SECTOR_SIZE); continue;
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); if(entry->ATTR & FAT::ATTRIBUTES::ATTR_VOLUME_ID){
continue;
// read entry for next cluster }
uint16_t nextCluster = *(uint16_t*) &FAT[entryOffset]; if (!(entry->ATTR & FAT::ATTRIBUTES::ATTR_LONG_NAME)){
for(char n : entry->Name){
// test if entry is odd or even if(n == 0x20)
if(file->currentCluster & 0x0001){ continue;
nextCluster>>= 4; // grab the high 12 bits kterm_put(n);
}
}else{ }else{
nextCluster &= 0x0FFF; // grab the low 12 bits printf("Long file name detected!");
} }
// test for end of file printf(" [Size: %d bytes, Attributes: %d]\n", entry->ATTR, entry->FileSize);
if(nextCluster >= 0xff8){ if(entry->ATTR & FAT::ATTRIBUTES::ATTR_DIRECTORY ){
file->eof -1; FAT::OpenSubdir(entry, bpb);
return; } 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;
}
*/

View File

@ -63,32 +63,18 @@ enum struct FAT_TYPE{
class FAT { class FAT {
public: public:
// Wanted API for vfs // Wanted API for vfs
static file Open(char* filename); static FILE Open(char* filename);
static int close(file* file); static int close(FILE* file);
static int Read(file* file, void* buffer , int length); static int Read(FILE* file, void* buffer , unsigned int length);
static int Write(file* file, const void* buffer, 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 int Create(inode* dir_node, inode** target, const char* component_name);
static int lookup(inode* , inode**, const char*); static DirectoryNode* Lookup(inode* , DirectoryNode*);
static int compare(directoryEntry* , char* , char*); static int Compare(DirectoryNode* , char *filename, char *filename2);
static superblock* Mount(filesystem* fs, const char* name ,vfsmount* mount); static FS_SUPER* Mount(filesystem* fs, const char* name , vfsmount* mount);
// TEMP static const int FREE = 0x0000;
static void listFilesInRoot(MBR* mbr, BiosParameterBlock* bpb ); static const int ALLOCATED = 0x0002;
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 BAD = 0xFFF7; static const int BAD = 0xFFF7;
static const int EOF = 0xFFFF; static const int EOF = 0xFFFF;
@ -98,6 +84,9 @@ public:
static const char DOS_TRAILING_SPACE = 0x20; static const char DOS_TRAILING_SPACE = 0x20;
static const char FREE_DIR = 0xE5; // If KANJI charset 0x05 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 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 { enum ATTRIBUTES {
ATTR_READ_ONLY = 0x01, ATTR_READ_ONLY = 0x01,
@ -111,6 +100,13 @@ public:
private: 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 { enum ENTRY_SIZE {
FAT12 = 12, FAT12 = 12,

View File

@ -5,6 +5,8 @@
#pragma once #pragma once
#include "../../../terminal/kterm.h" #include "../../../terminal/kterm.h"
#include "../../../memory/KernelHeap.h"
#include "../../../../CoreLib/Memory.h"
// Date Format // Date Format
// [0..4] Day // [0..4] Day

View File

@ -22,22 +22,22 @@ inline MBR* GetPartitions(bool DEBUG = false){
int S =1; int S =1;
uint32_t LBA = (C*HPC+H) * SPT + (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", bootRecord, sizeof (MBR));
printf("MBR (In Memory) Address 0x%x, Size = %d\n", mbr, sizeof (MBR));
if(DEBUG){ if(DEBUG){
printf("BootSector: 0x%x\n", mbr->ValidBootsector ); printf("BootSector: 0x%x\n", bootRecord->ValidBootsector );
for( int i = 0 ; i < 4 ; i ++){ 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" , 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;
} }

View File

@ -14,17 +14,21 @@ int VirtualFileSystem::superblock_number =0;
int VirtualFileSystem::filesystem_number =0; int VirtualFileSystem::filesystem_number =0;
filesystem* VirtualFileSystem::filesystems[4]; filesystem* VirtualFileSystem::filesystems[4];
superblock* VirtualFileSystem::superblocks[8]; FS_SUPER* VirtualFileSystem::superblocks[8];
vfsmount* VirtualFileSystem::mounts[12]; vfsmount* VirtualFileSystem::mounts[12];
void VirtualFileSystem::Mount(filesystem* fs, const char* name) 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; mounts[mount_number++] = mnt_point;
superblocks[superblock_number++] = sb; superblocks[superblock_number++] = sb;
mnt_point->mnt_count = 1;
rootfs = mnt_point; rootfs = mnt_point;
} }
@ -54,64 +58,75 @@ 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 // 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. // 3. Create a new file if O_CREATE is specified in the flags.
FILE* file = (FILE*) malloc(sizeof (FILE)) ;
// See reference material (1) https://man7.org/linux/man-pages/man7/path_resolution.7.html auto* rootentry = rootfs->root;
// 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;
}
char* tokstate = nullptr; char* tokstate = nullptr;
auto nextdir = strtok ((char*)pathname, "/", &tokstate ); 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; if(rootentry->children == nullptr)
file.flags = 1; {
return &file; file->flags =1;
return file;
}
// 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;
}
}
file->flags = 1;
return file;
} }
int VirtualFileSystem::close (struct file* file){ int VirtualFileSystem::close (struct FILE* file){
// 1. release the file descriptor // 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. // 1. Write len bytes from buf to the opened file.
// 2. return written size or error code if an error occurs // 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. // 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 // 2. return read size or error code if an error occurs
} }

View File

@ -11,10 +11,10 @@
static int register_filesystem(struct filesystem* fs); static int register_filesystem(struct filesystem* fs);
static struct file* open(const char* pathname, int flags); static FILE* open(const char* pathname, int flags);
static int close(struct file* file); static int close(struct FILE* file);
static int write(struct file* file, const void* buf, size_t len); static int write(struct FILE* file, const void* buf, unsigned int len);
static int read(struct file* file, void* buf, size_t len); static int read(struct FILE* file, void* buf, unsigned int len);
private: private:
static vfsmount* rootfs; static vfsmount* rootfs;
@ -25,7 +25,7 @@
static int filesystem_number; static int filesystem_number;
static filesystem* filesystems[]; static filesystem* filesystems[];
static superblock* superblocks[]; static FS_SUPER* superblocks[];
static vfsmount* mounts[]; static vfsmount* mounts[];
}; };

View File

@ -5,55 +5,52 @@
// grasslab.github.io/osdi/en/labs/lab7.html // grasslab.github.io/osdi/en/labs/lab7.html
#include <stddef.h> #include <stddef.h>
#include <stdint.h> #include <stdint.h>
#include "../../../CoreLib/List.h"
struct inode_operations; struct inode_operations;
struct vfsmount; struct vfsmount;
struct superblock; struct FS_SUPER;
struct inode; struct inode;
struct dentry_operations; struct dentry_operations;
struct directoryEntry; struct DirectoryNode;
struct filesystem; struct filesystem;
struct superblock; struct FS_SUPER;
struct file; 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 // Describes a mount
struct vfsmount { struct vfsmount {
vfsmount* mnt_parent; // fs we are mounted on vfsmount* mnt_parent; // fs we are mounted on
directoryEntry* mountpoint; // dentry of mount point DirectoryNode* mountpoint; // dentry of mount point
directoryEntry* root; // root of the mounted tree DirectoryNode* root; // root of the mounted tree
superblock* sb; // pointer to the superblock FS_SUPER* sb; // pointer to the superblock
unsigned int mnt_count; // keep track of users of this structure unsigned int mnt_count; // keep track of users of this structure
int mnt_flags; int mnt_flags;
char* mnt_devname; // name of device eg /dev/dsk/hda1 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) // Represents a filesystem object (i.e. a file or directory or device)
struct inode { struct inode {
unsigned long mode; // access permissions unsigned long mode; // access permissions
unsigned long uid; // user id owner unsigned long uid; // user id owner
unsigned long gid; // group id owner unsigned long gid; // group id owner
unsigned int flags; unsigned int flags;
inode_operations* i_op; // operations possible on inode // operations possible on inode
superblock* sb; 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 long ino; // unique number of this inode
unsigned int links; // number of hard links unsigned int links; // number of hard links
void* device; void* device;
@ -62,43 +59,39 @@ struct inode {
unsigned long mtime; // Modify time unsigned long mtime; // Modify time
unsigned long ctime; // Creation time unsigned long ctime; // Creation time
unsigned short bytes; // bytes consumed 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) 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 // Represents the name of files in the filesystem
// it identifies the file that an inode represents // it identifies the file that an inode represents
struct directoryEntry { struct DirectoryNode {
char* name; // name of the file on the disk 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... inode* node; // node belongs to...
dentry_operations* op; int (*compare)(DirectoryNode*, char*, char* );
directoryEntry* children[]; int (*o_delete)(DirectoryNode*);
void (*release)(DirectoryNode*);
void (*iput)(DirectoryNode*, inode*);
List* children;
}; };
// Represents a filesystem type // Represents a filesystem type
struct filesystem { struct filesystem {
const char* name; 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 // Represents a mounted filesystem
struct superblock { struct FS_SUPER {
void* device; // device associated with the filesystem void* device; // device associated with the filesystem
unsigned long blocksize; unsigned long blocksize;
unsigned long maxbytes; unsigned long maxbytes;
filesystem* type; filesystem* type;
unsigned long magic; // IDK unsigned long magic; // IDK
directoryEntry* root; // Root dentry DirectoryNode* root; // Root dentry
int count; // IDK int count; // IDK
void* fs_info; // pointer to raw filesystem info void* fs_info; // pointer to raw filesystem info
dentry_operations* d_op; dentry_operations* d_op;
@ -106,10 +99,11 @@ struct superblock {
}; };
// Represents an opened file // Represents an opened file
struct file { struct FILE {
inode* root; inode* root;
size_t f_pos; // The next read/write position of this file descriptor; unsigned int f_pos; // The next read/write position of this file descriptor;
file_operations* f_ops; int(*write) (FILE* file, const void* buf, unsigned int len);
int(*read) (FILE* file, void* buf, unsigned int len);
int flags; int flags;
}; };

View File

@ -6,6 +6,8 @@
bool isRunning = true; bool isRunning = true;
extern "C" void startSuperVisorTerminal() extern "C" void startSuperVisorTerminal()
{ {
/* /*
* Show a little banner for cuteness * Show a little banner for cuteness
*/ */
@ -62,7 +64,8 @@ extern "C" void startSuperVisorTerminal()
{ {
// Show version information // Show version information
printf("========= Version ========\n"); printf("========= Version ========\n");
printf("Kernel v%d\n", 0);
asm volatile ("movl $0x666, %eax; int $0x50");
} }
if(strncmp("CLEAR", command, characterCount) == 0) if(strncmp("CLEAR", command, characterCount) == 0)

52
kernel/syscalls.h Normal file
View File

@ -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;
}
}

View File

@ -21,7 +21,14 @@ void kterm_init () {
kterm_row = 0; kterm_row = 0;
kterm_column = 0; kterm_column = 0;
kterm_color = vga_entry_color ( VGA_COLOR_LIGHT_GREY , VGA_COLOR_BLACK); 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 y = 0; y < VGA_HEIGHT; y++ ){
for( size_t x = 0; x < VGA_WIDTH; x++){ for( size_t x = 0; x < VGA_WIDTH; x++){
@ -59,7 +66,6 @@ void disable_cursor()
outb(0x3D5, 0x20); outb(0x3D5, 0x20);
} }
void update_cursor(int x, int y){ void update_cursor(int x, int y){
uint16_t pos = y * VGA_WIDTH + x; uint16_t pos = y * VGA_WIDTH + x;
@ -86,8 +92,6 @@ int get_cursor_y (uint16_t cursor_pos ) {
return cursor_pos / VGA_WIDTH; return cursor_pos / VGA_WIDTH;
} }
/** /**
* With the help from: * With the help from:
* https://whiteheadsoftware.dev/operating-systems-development-for-dummies/ * https://whiteheadsoftware.dev/operating-systems-development-for-dummies/
@ -134,7 +138,6 @@ void kterm_writestring(const char* data ){
kterm_write(data, strlen(data)); kterm_write(data, strlen(data));
} }
static void itoa (char *buf, int base, int d) { static void itoa (char *buf, int base, int d) {
char *p = buf; char *p = buf;
char *p1, *p2; char *p1, *p2;
@ -173,28 +176,28 @@ static void itoa (char *buf, int base, int d) {
void printf ( const char *format, ...) { void printf ( const char *format, ...) {
char **arg = (char **)&format; auto **arg = (unsigned char **)&format;
int c; int c;
char buf[20]; char buf[20];
arg++; arg++;
while ((c = *format++) != 0){ while ((c = *(const unsigned char*)format++) != 0){
if( c != '%') if( c != '%')
kterm_put(c); kterm_put(c);
else{ else{
char *p, *p2; char const *p, *p2;
int pad0 = 0, pad = 0; int pad0 = 0, pad = 0;
c = *format++; c = *(const unsigned char*)format++;
if(c =='0'){ if(c =='0'){
pad0 = 1; pad0 = 1;
c = *format++; c = *(const unsigned char*)format++;
} }
if ( c >= '0' && c <= '9'){ if ( c >= '0' && c <= '9'){
pad = c - '0'; pad = c - '0';
c = *format++; c = *(const unsigned char*)format++;
} }
switch (c) switch (c)
@ -210,7 +213,7 @@ void printf ( const char *format, ...) {
break; break;
case 's': case 's':
p = *arg++; p = (char const *)*arg++;
if(!p) if(!p)
p = "(null)"; p = "(null)";
@ -224,7 +227,7 @@ void printf ( const char *format, ...) {
default: default:
kterm_put(*((int *)arg++)); kterm_put(*(int *) arg++); // NOLINT(cppcoreguidelines-narrowing-conversions)
break; break;
} }
} }

22
run.sh
View File

@ -3,23 +3,25 @@ PROC=$$
# Build the Corelib static library # Build the Corelib static library
(cd CoreLib (cd CoreLib
if ! make; then if ! make 2> warnings.log 1> /dev/null ; then
echo "Build failed!" echo "Build Corelib failed!"
kill -10 $PROC kill -10 $PROC
fi) fi)
# Build the kernel image # Build the kernel image
(cd kernel (cd kernel
make clean # make clean
make if ! make 2> warnings.log 1> /dev/null ; then
if ! make; then echo "Build kernel failed!"
echo "Build failed!"
kill -10 $PROC kill -10 $PROC
fi) fi)
./scripts/update_harddrive.sh ./scripts/update_harddrive.sh
./scripts/create_symbol_lookup.sh
args="";
if [[ $1 == "-d" ]]
./scripts/run_qemu.sh then
args="debug"
fi
./scripts/run_qemu.sh $args

View File

@ -1,3 +1,4 @@
#!/bin/bash #!/bin/bash
echo "creating symbols file"
objcopy --only-keep-debug build/kernel/myos.bin kernel.sym echo $(pwd)
objcopy --only-keep-debug root/boot/myos.bin kernel.sym

View File

@ -1,7 +1,13 @@
#!/bin/bash #!/bin/bash
if [[ $1 == "debug" ]]
then
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 -s -boot d -drive format=raw,file=disk.img -serial stdio -vga std -display gtk -m 2G -cpu core2duo
fi
# Run from harddisk # 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 # 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 # qemu-system-i386 -cdrom barinkOS.iso -serial stdio -vga std -display gtk -m 2G -cpu core2duo -s -d int -no-shutdown -no-reboot

View File

@ -4,7 +4,7 @@
This list keeps me focused and organised so I don't forget what 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. to do on a more in depth level.
## -- ## --