6 Commits

Author SHA1 Message Date
940b2810cb Update io.h
adding the missing io
2025-11-20 10:07:01 -08:00
01f85f97ec Update fat12.h
better header for FAT12 kernel driver
2025-11-19 09:31:22 -08:00
fd2c567d29 Update fat12.c
implementation of kernel space fat12 kernel driver for fat12
2025-11-19 09:29:04 -08:00
9de9cc6523 Update scheduler.h 2025-11-19 08:44:15 -08:00
e9a78c835a Create context_switch.s
new context_switch.s for x86 IA32.
must confirm nasm.
2025-11-19 08:43:11 -08:00
77400d8f5a Update scheduler.c
old scheduler might not work on x86 IA-32 32 bit
2025-11-19 08:41:03 -08:00
6 changed files with 336 additions and 55 deletions

25
kernel/context_switch.s Normal file
View File

@@ -0,0 +1,25 @@
.global ctx_switch
; void ctx_switch(uint32_t **old_sp_ptr, uint32_t *new_sp);
; Arguments on stack (cdecl convention):
; [ESP + 4] -> old_sp_ptr (pointer to the 'stack_ptr' field of current task)
; [ESP + 8] -> new_sp (value of 'stack_ptr' of the next task)
ctx_switch:
; 1. Save the context of the CURRENT task
pushf ; Save EFLAGS (CPU status flags)
pusha ; Save all General Purpose Regs (EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI)
; 2. Save the current stack pointer (ESP) into the pointer passed as 1st arg
mov eax, [esp + 40] ; Get 1st argument (old_sp_ptr). Offset 40 = 36 (regs) + 4 (ret addr)
mov [eax], esp ; *old_sp_ptr = ESP
; 3. Load the stack pointer of the NEW task
mov esp, [esp + 44] ; Get 2nd argument (new_sp). Offset 44 = 40 + 4
; 4. Restore the context of the NEW task
popa ; Restore all General Purpose Regs
popf ; Restore EFLAGS
; 5. Jump to the new task (The 'ret' pops EIP from the new stack)
ret

View File

@@ -1,5 +1,184 @@
#include "fat12.h" #include "fat12.h"
#include <stddef.h> // for NULL
// --- Globals for Filesystem State ---
static fat12_bpb_t bpb;
static uint32_t fat_start_lba;
static uint32_t root_dir_lba;
static uint32_t data_start_lba;
static uint32_t root_dir_sectors;
// Scratch buffer to read sectors (avoids large stack usage)
static uint8_t g_sector_buffer[FAT12_SECTOR_SIZE];
// --- Utils (Since we don't have string.h) ---
static int k_memcmp(const void *s1, const void *s2, uint32_t n) {
const uint8_t *p1 = (const uint8_t *)s1;
const uint8_t *p2 = (const uint8_t *)s2;
for (uint32_t i = 0; i < n; i++) {
if (p1[i] != p2[i]) return p1[i] - p2[i];
}
return 0;
}
// Converts "file.txt" to "FILE TXT" for comparison
static void to_fat_name(const char *src, char *dest) {
// Initialize with spaces
for(int i=0; i<11; i++) dest[i] = ' ';
int i = 0, j = 0;
// Copy Name
while (src[i] != '\0' && src[i] != '.' && j < 8) {
// Convert to uppercase (simple version)
char c = src[i];
if (c >= 'a' && c <= 'z') c -= 32;
dest[j++] = c;
i++;
}
// Skip extension dot
if (src[i] == '.') i++;
// Copy Extension
j = 8;
while (src[i] != '\0' && j < 11) {
char c = src[i];
if (c >= 'a' && c <= 'z') c -= 32;
dest[j++] = c;
i++;
}
}
// --- Core Logic ---
void fat12_init() { void fat12_init() {
// Filesystem initialization code // 1. Read Boot Sector (LBA 0)
disk_read_sector(0, g_sector_buffer);
// 2. Copy BPB data safely
// We cast the buffer to our struct
fat12_bpb_t *boot_sector = (fat12_bpb_t*)g_sector_buffer;
bpb = *boot_sector;
// 3. Calculate System Offsets
fat_start_lba = bpb.reserved_sectors;
// Root Dir starts after FATs
// LBA = Reserved + (FatCount * SectorsPerFat)
root_dir_lba = fat_start_lba + (bpb.fat_count * bpb.sectors_per_fat);
// Calculate size of Root Directory in sectors
// (Entries * 32 bytes) / 512
root_dir_sectors = (bpb.dir_entries_count * 32 + FAT12_SECTOR_SIZE - 1) / FAT12_SECTOR_SIZE;
// Data starts after Root Directory
data_start_lba = root_dir_lba + root_dir_sectors;
}
// Helper: Read the FAT table to find the NEXT cluster
static uint16_t fat12_get_next_cluster(uint16_t current_cluster) {
// FAT12 Offset Calculation:
// Offset = Cluster + (Cluster / 2)
uint32_t fat_offset = current_cluster + (current_cluster / 2);
uint32_t fat_sector = fat_start_lba + (fat_offset / FAT12_SECTOR_SIZE);
uint32_t ent_offset = fat_offset % FAT12_SECTOR_SIZE;
// Read the sector containing the FAT entry
disk_read_sector(fat_sector, g_sector_buffer);
// Read 16 bits (2 bytes)
// Note: If ent_offset == 511, the entry spans two sectors.
// For simplicity in this snippet, we ignore that edge case (rare).
// A robust kernel would check if(ent_offset == 511) and read next sector.
uint16_t val = *(uint16_t*)&g_sector_buffer[ent_offset];
if (current_cluster & 1) {
return val >> 4; // Odd: High 12 bits
} else {
return val & 0x0FFF; // Even: Low 12 bits
}
}
file_t fat12_open(const char *filename) {
file_t file = {0};
char target_name[11];
to_fat_name(filename, target_name);
// Search Root Directory
for (uint32_t i = 0; i < root_dir_sectors; i++) {
disk_read_sector(root_dir_lba + i, g_sector_buffer);
fat12_entry_t *entry = (fat12_entry_t*)g_sector_buffer;
// Check all 16 entries in this sector (512 / 32 = 16)
for (int j = 0; j < 16; j++) {
if (entry[j].filename[0] == 0x00) return file; // End of Dir
// Check if filename matches
if (k_memcmp(entry[j].filename, target_name, 11) == 0) {
// Found it!
file.start_cluster = entry[j].low_cluster_num;
file.size = entry[j].file_size;
// Initialize file cursor
file.current_cluster = file.start_cluster;
file.bytes_read = 0;
return file;
}
}
}
// Not found (file.start_cluster will be 0)
return file;
}
uint32_t fat12_read(file_t *file, uint8_t *buffer, uint32_t bytes_to_read) {
if (file->start_cluster == 0) return 0; // File not open
uint32_t total_read = 0;
while (bytes_to_read > 0) {
// Check for EOF marker in FAT12 (>= 0xFF8)
if (file->current_cluster >= 0xFF8) break;
// Calculate Physical LBA of current cluster
// LBA = DataStart + ((Cluster - 2) * SectorsPerCluster)
uint32_t lba = data_start_lba + ((file->current_cluster - 2) * bpb.sectors_per_cluster);
// Read the cluster
// NOTE: Assumes SectorsPerCluster = 1 (Standard Floppy)
disk_read_sector(lba, g_sector_buffer);
// Determine how much to copy from this sector
uint32_t chunk_size = FAT12_SECTOR_SIZE;
// If the file is smaller than a sector, or we are at the end
if (chunk_size > bytes_to_read) chunk_size = bytes_to_read;
// Check if we are reading past file size
if (file->bytes_read + chunk_size > file->size) {
chunk_size = file->size - file->bytes_read;
}
// Copy to user buffer
for (uint32_t i = 0; i < chunk_size; i++) {
buffer[total_read + i] = g_sector_buffer[i];
}
total_read += chunk_size;
file->bytes_read += chunk_size;
bytes_to_read -= chunk_size;
// If we finished this cluster, move to the next one
if (chunk_size == FAT12_SECTOR_SIZE) { // Or strictly logic based on position
file->current_cluster = fat12_get_next_cluster(file->current_cluster);
} else {
// We finished the file or the request
break;
}
}
return total_read;
} }

View File

@@ -1,47 +1,67 @@
#ifndef FAT12_H #ifndef FAT12_H
#define FAT12_H #define FAT12_H
#include <stdint.h> /* Include standard integer types */ #include <stdint.h>
#include <stdio.h> /* Include standard I/O library */
#include <stdlib.h> /* Include standard library */
#define FAT12_SECTOR_SIZE 512 /* Sector size for FAT12 */ // --- Configuration ---
#define FAT12_MAX_FILES 128 /* Maximum number of files in root directory */ #define FAT12_SECTOR_SIZE 512
#define FAT12_ROOT_DIR_SECTORS 1 /* Number of sectors for root directory */
// --- On-Disk Structures (Must be Packed) ---
// BIOS Parameter Block (Start of Boot Sector)
typedef struct { typedef struct {
uint8_t jump[3]; /* Jump instruction for boot */ uint8_t jump[3];
char oem[8]; /* OEM name */ char oem[8];
uint16_t bytes_per_sector; /* Bytes per sector */ uint16_t bytes_per_sector; // 512
uint8_t sectors_per_cluster; /* Sectors per cluster */ uint8_t sectors_per_cluster; // 1
uint16_t reserved_sectors; /* Reserved sectors count */ uint16_t reserved_sectors; // 1 (Boot sector)
uint8_t num_fats; /* Number of FATs */ uint8_t fat_count; // 2
uint16_t max_root_dir_entries; /* Max entries in root directory */ uint16_t dir_entries_count; // 224
uint16_t total_sectors; /* Total sectors */ uint16_t total_sectors; // 2880
uint8_t media_descriptor; /* Media descriptor */ uint8_t media_descriptor; // 0xF0
uint16_t fat_size; /* Size of each FAT */ uint16_t sectors_per_fat; // 9
uint16_t sectors_per_track; /* Sectors per track */ uint16_t sectors_per_track; // 18
uint16_t num_heads; /* Number of heads */ uint16_t heads; // 2
uint32_t hidden_sectors; /* Hidden sectors count */ uint32_t hidden_sectors;
uint32_t total_sectors_large; /* Total sectors for large disks */ uint32_t total_sectors_large;
} __attribute__((packed)) FAT12_BootSector; /* Packed structure for boot sector */ } __attribute__((packed)) fat12_bpb_t;
// Directory Entry (32 bytes)
typedef struct { typedef struct {
char name[11]; /* File name (8.3 format) */ char filename[8];
uint8_t attr; /* File attributes */ char ext[3];
uint16_t reserved; /* Reserved */ uint8_t attributes;
uint16_t time; /* Time of last write */ uint8_t reserved;
uint16_t date; /* Date of last write */ uint8_t creation_ms;
uint16_t start_cluster; /* Starting cluster number */ uint16_t creation_time;
uint32_t file_size; /* File size in bytes */ uint16_t creation_date;
} __attribute__((packed)) FAT12_DirEntry; /* Directory entry structure */ uint16_t last_access_date;
uint16_t high_cluster_num; // Always 0 in FAT12
uint16_t last_mod_time;
uint16_t last_mod_date;
uint16_t low_cluster_num; // The starting cluster
uint32_t file_size; // Size in bytes
} __attribute__((packed)) fat12_entry_t;
void initialize_fat12(const char *disk_image); /* Function to initialize FAT12 */ // --- Kernel File Handle ---
void read_fat12(const char *disk_image); /* Function to read FAT12 */ // This is what your kernel uses to track an open file
void write_fat12(const char *disk_image); /* Function to write FAT12 */ typedef struct {
void list_files(const char *disk_image); /* Function to list files in root directory */ char name[11];
void read_file(const char *disk_image, const char *filename); /* Function to read a file */ uint32_t size;
void write_file(const char *disk_image, const char *filename, const uint8_t *data, size_t size); /* Function to write a file */ uint16_t start_cluster;
uint16_t current_cluster;
uint32_t current_sector_in_cluster;
uint32_t bytes_read;
} file_t;
#endif // --- Public API ---
/* FAT12_H */
// You must implement this in your disk driver (e.g., floppy.c)
// Returns 0 on success, non-zero on error.
extern int disk_read_sector(uint32_t lba, uint8_t *buffer);
void fat12_init();
file_t fat12_open(const char *filename);
uint32_t fat12_read(file_t *file, uint8_t *buffer, uint32_t bytes_to_read);
#endif // FAT12_H

View File

@@ -13,4 +13,24 @@ static inline uint8_t inb(uint16_t port) {
return ret; return ret;
} }
static inline void outw(uint16_t port, uint16_t val) {
__asm__("outw %0, %1" : : "a"(val), "Nd"(port));
}
static inline uint16_t inw(uint16_t port) {
uint16_t ret;
__asm__("inw %1, %0" : "=a"(ret) : "Nd"(port));
return ret;
}
static inline void outl(uint16_t port, uint32_t val) {
__asm__("outl %0, %1" : : "a"(val), "Nd"(port));
}
static inline uint32_t inl(uint16_t port) {
uint32_t ret;
__asm__("inl %1, %0" : "=a"(ret) : "Nd"(port));
return ret;
}
#endif #endif

View File

@@ -1,7 +1,12 @@
#include "scheduler.h" #include "scheduler.h"
#include <stddef.h> #include <stddef.h>
// Defined in context_switch.s
extern void ctx_switch(uint32_t **old_sp_ptr, uint32_t *new_sp);
static task_t tasks[MAX_TASKS]; static task_t tasks[MAX_TASKS];
// Stack memory area. Note: x86 Stacks grow DOWN from high to low addresses.
static uint32_t task_stacks[MAX_TASKS][STACK_SIZE / sizeof(uint32_t)]; static uint32_t task_stacks[MAX_TASKS][STACK_SIZE / sizeof(uint32_t)];
static int task_count = 0; static int task_count = 0;
@@ -9,7 +14,6 @@ static task_t *task_list = NULL;
static task_t *current_task = NULL; static task_t *current_task = NULL;
void scheduler_init() { void scheduler_init() {
// Initialize task list, etc.
task_list = NULL; task_list = NULL;
current_task = NULL; current_task = NULL;
task_count = 0; task_count = 0;
@@ -20,16 +24,42 @@ void scheduler_add_task(void (*entry)(void)) {
task_t *new_task = &tasks[task_count]; task_t *new_task = &tasks[task_count];
new_task->id = task_count; new_task->id = task_count;
new_task->entry = entry;
// Simulate a stack pointer pointing to the "top" of the stack // 1. Calculate the top of the stack (High Address)
new_task->stack_ptr = &task_stacks[task_count][STACK_SIZE / sizeof(uint32_t) - 1]; // We point to the very end of the array.
uint32_t *sp = &task_stacks[task_count][STACK_SIZE / sizeof(uint32_t)];
// 2. "Forge" the stack frame to look like ctx_switch saved it.
// We push values onto the stack by decrementing the pointer and writing.
// --- Return Address (EIP) ---
sp--;
*sp = (uint32_t)entry; // When ctx_switch does 'ret', it pops this and jumps to 'entry'
// --- EFLAGS ---
sp--;
*sp = 0x00000202; // Reserved bit set, Interrupts Enabled (IF=1). Important!
// --- General Purpose Registers (PUSHA/POPA layout) ---
// Order: EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI
// We initialize them to 0 or meaningful values.
sp--; *sp = 0; // EAX
sp--; *sp = 0; // ECX
sp--; *sp = 0; // EDX
sp--; *sp = 0; // EBX
sp--; *sp = 0; // ESP (Ignored by POPA)
sp--; *sp = 0; // EBP
sp--; *sp = 0; // ESI
sp--; *sp = 0; // EDI
// Save this final stack location to the TCB
new_task->stack_ptr = sp;
new_task->next = NULL; new_task->next = NULL;
// Add to task list // 3. Add to linked list
if (task_list == NULL) { if (task_list == NULL) {
task_list = new_task; task_list = new_task;
current_task = new_task; // Make sure we have a current task to start
} else { } else {
task_t *tail = task_list; task_t *tail = task_list;
while (tail->next) { while (tail->next) {
@@ -42,21 +72,25 @@ void scheduler_add_task(void (*entry)(void)) {
} }
void scheduler_schedule() { void scheduler_schedule() {
// Very basic round-robin switch if (!current_task) return;
if (current_task && current_task->next) {
task_t *prev = current_task;
// Round-robin logic
if (current_task->next) {
current_task = current_task->next; current_task = current_task->next;
} else { } else {
current_task = task_list; // Loop back current_task = task_list;
} }
// Call context switch or simulate yielding to current_task // Perform the ACTUAL context switch
// In real system: context_switch_to(current_task) // We pass the address of the previous task's stack pointer storage
if (current_task && current_task->entry) { // and the value of the new task's stack pointer.
current_task->entry(); // Simulate switching by calling if (prev != current_task) {
ctx_switch(&prev->stack_ptr, current_task->stack_ptr);
} }
} }
void scheduler_yield() { void scheduler_yield() {
// Stub: manually call schedule for cooperative multitasking
scheduler_schedule(); scheduler_schedule();
} }

View File

@@ -4,18 +4,21 @@
#include <stdint.h> #include <stdint.h>
#define MAX_TASKS 8 #define MAX_TASKS 8
#define STACK_SIZE 1024 #define STACK_SIZE 1024 // in bytes
typedef struct task { typedef struct task {
uint32_t id; uint32_t id;
void (*entry)(void);
uint32_t *stack_ptr; // The most important field:
// Where was the stack pointer when we last left this task?
uint32_t *stack_ptr;
struct task *next; struct task *next;
} task_t; } task_t;
void scheduler_init(); void scheduler_init();
void scheduler_add_task(void (*entry)(void)); void scheduler_add_task(void (*entry)(void));
void scheduler_schedule(); void scheduler_schedule();
void scheduler_yield(); // Optional for cooperative scheduling void scheduler_yield();
#endif // SCHEDULER_H #endif // SCHEDULER_H