From 7a584ea6e622d0dfcfcfa40cd334718bbae5954c Mon Sep 17 00:00:00 2001 From: Adam Eehan Date: Fri, 23 Oct 2026 15:47:25 +0530 Subject: [PATCH] feat(kernel): implement Phase 3 - PMM bitmap allocator, VMM #PF handler & dynamic kernel heap (kmalloc/kfree) --- Makefile | 3 + README.md | 8 +- include/airlys/heap.h | 29 +++++++ include/airlys/pmm.h | 32 ++++++++ include/airlys/vmm.h | 41 ++++++++++ kernel/heap.c | 175 ++++++++++++++++++++++++++++++++++++++++++ kernel/kmain.c | 28 ++++++- kernel/pmm.c | 136 ++++++++++++++++++++++++++++++++ kernel/vmm.c | 38 +++++++++ linker.ld | 4 + 10 files changed, 489 insertions(+), 5 deletions(-) create mode 100644 include/airlys/heap.h create mode 100644 include/airlys/pmm.h create mode 100644 include/airlys/vmm.h create mode 100644 kernel/heap.c create mode 100644 kernel/pmm.c create mode 100644 kernel/vmm.c diff --git a/Makefile b/Makefile index 727a601..6b8d162 100644 --- a/Makefile +++ b/Makefile @@ -25,6 +25,9 @@ C_SRCS := kernel/kmain.c \ kernel/pic.c \ kernel/timer.c \ kernel/keyboard.c \ + kernel/pmm.c \ + kernel/vmm.c \ + kernel/heap.c \ arch/x86_64/idt.c ASM_SRCS := arch/x86_64/boot.s \ diff --git a/README.md b/README.md index edd1260..5a1d3b0 100644 --- a/README.md +++ b/README.md @@ -123,10 +123,10 @@ qemu-system-x86_64 -kernel bin/airlys.elf - [x] PS/2 Hardware Keyboard driver with Scan Code Set 1 decoding - [x] CPU hardware interrupts enabled (`sti`) with live interactive keyboard typing! -- [ ] **Phase 3: Sovereign Memory Subsystem** - - [ ] Physical Memory Manager (Bitmap Page Allocator) - - [ ] Virtual Memory Manager (Page fault handler & dynamic mapping) - - [ ] Kernel Heap (`kmalloc` / `kfree`) +- [x] **Phase 3: Sovereign Memory Subsystem** + - [x] Physical Memory Manager (Bitmap Page Allocator tracking 1GB physical RAM & 262,144 frames) + - [x] Virtual Memory Manager (Page fault `#PF` exception handler with CR2/CR3 register inspection) + - [x] Sovereign Dynamic Kernel Heap (`kmalloc`, `kfree`, `kcalloc`, `krealloc` with 32MB dynamic pool & automated memory self-test) - [ ] **Phase 4: Preemptive Multitasking** - [ ] Process Control Block (PCB) architecture diff --git a/include/airlys/heap.h b/include/airlys/heap.h new file mode 100644 index 0000000..707ebc5 --- /dev/null +++ b/include/airlys/heap.h @@ -0,0 +1,29 @@ +#ifndef AIRLYS_HEAP_H +#define AIRLYS_HEAP_H + +#include + +#define KERNEL_HEAP_START 0x01000000ULL /* 16 MB boundary */ +#define KERNEL_HEAP_SIZE (32ULL * 1024 * 1024) /* 32 MB heap pool */ + +/* Initialize dynamic kernel heap allocator */ +void heap_init(uintptr_t start_addr, size_t size); + +/* Allocate dynamic heap memory */ +void* kmalloc(size_t size); + +/* Free previously allocated heap memory */ +void kfree(void* ptr); + +/* Allocate zero-initialized dynamic heap memory */ +void* kcalloc(size_t num, size_t size); + +/* Reallocate dynamic heap memory with new size */ +void* krealloc(void* ptr, size_t new_size); + +/* Heap Statistics */ +size_t heap_get_total_bytes(void); +size_t heap_get_used_bytes(void); +size_t heap_get_free_bytes(void); + +#endif /* AIRLYS_HEAP_H */ diff --git a/include/airlys/pmm.h b/include/airlys/pmm.h new file mode 100644 index 0000000..3b2db4d --- /dev/null +++ b/include/airlys/pmm.h @@ -0,0 +1,32 @@ +#ifndef AIRLYS_PMM_H +#define AIRLYS_PMM_H + +#include + +#define PAGE_SIZE 4096 +#define PMM_MAX_MEMORY (1024ULL * 1024 * 1024) /* 1 GB */ +#define PMM_MAX_FRAMES (PMM_MAX_MEMORY / PAGE_SIZE) /* 262,144 frames */ +#define PMM_BITMAP_SIZE (PMM_MAX_FRAMES / 8) /* 32,768 bytes */ + +/* Initialize Physical Memory Manager above kernel image */ +void pmm_init(uintptr_t mem_size); + +/* Allocate a single 4KB physical frame (returns physical address or 0 on failure) */ +void* pmm_alloc_frame(void); + +/* Free an allocated 4KB physical frame */ +void pmm_free_frame(void* frame); + +/* Allocate multiple contiguous physical frames */ +void* pmm_alloc_frames(size_t count); + +/* Free multiple contiguous physical frames */ +void pmm_free_frames(void* frame, size_t count); + +/* Statistics */ +size_t pmm_get_total_frames(void); +size_t pmm_get_used_frames(void); +size_t pmm_get_free_frames(void); +uint64_t pmm_get_free_memory_kb(void); + +#endif /* AIRLYS_PMM_H */ diff --git a/include/airlys/vmm.h b/include/airlys/vmm.h new file mode 100644 index 0000000..8626e3f --- /dev/null +++ b/include/airlys/vmm.h @@ -0,0 +1,41 @@ +#ifndef AIRLYS_VMM_H +#define AIRLYS_VMM_H + +#include +#include + +/* Page Table Entry Flags (x86_64) */ +#define PAGE_PRESENT (1ULL << 0) +#define PAGE_WRITABLE (1ULL << 1) +#define PAGE_USER (1ULL << 2) +#define PAGE_WRITETHROUGH (1ULL << 3) +#define PAGE_NOCACHE (1ULL << 4) +#define PAGE_ACCESSED (1ULL << 5) +#define PAGE_DIRTY (1ULL << 6) +#define PAGE_HUGE (1ULL << 7) +#define PAGE_GLOBAL (1ULL << 8) +#define PAGE_NOEXECUTE (1ULL << 63) + +/* Read CR2 register (Linear faulting virtual address) */ +static inline uintptr_t read_cr2(void) { + uintptr_t val; + __asm__ volatile ("mov %%cr2, %0" : "=r"(val)); + return val; +} + +/* Read CR3 register (PML4 base address) */ +static inline uintptr_t read_cr3(void) { + uintptr_t val; + __asm__ volatile ("mov %%cr3, %0" : "=r"(val)); + return val; +} + +/* Invalidate TLB entry for a single virtual address */ +static inline void invlpg(uintptr_t vaddr) { + __asm__ volatile ("invlpg (%0)" : : "r"(vaddr) : "memory"); +} + +/* Initialize Virtual Memory Manager & register #PF handler */ +void vmm_init(void); + +#endif /* AIRLYS_VMM_H */ diff --git a/kernel/heap.c b/kernel/heap.c new file mode 100644 index 0000000..6a22389 --- /dev/null +++ b/kernel/heap.c @@ -0,0 +1,175 @@ +#include +#include +#include + +#define HEAP_MAGIC 0xA18A3644ULL + +typedef struct heap_block { + size_t size; /* Payload size in bytes */ + bool is_free; /* True if block is free */ + uint32_t magic; /* Integrity guard */ + struct heap_block* next; /* Next block in list */ + struct heap_block* prev; /* Previous block */ +} __attribute__((aligned(16))) heap_block_t; + +static uintptr_t heap_start = 0; +static size_t heap_total_size = 0; +static heap_block_t* heap_head = NULL; + +static inline size_t align16(size_t size) { + return (size + 15) & ~15ULL; +} + +void heap_init(uintptr_t start_addr, size_t size) { + heap_start = (start_addr + 15) & ~15ULL; + heap_total_size = size; + + heap_head = (heap_block_t*)heap_start; + heap_head->size = size - sizeof(heap_block_t); + heap_head->is_free = true; + heap_head->magic = HEAP_MAGIC; + heap_head->next = NULL; + heap_head->prev = NULL; +} + +void* kmalloc(size_t size) { + if (size == 0 || heap_head == NULL) { + return NULL; + } + + size_t aligned_size = align16(size); + heap_block_t* curr = heap_head; + + while (curr) { + if (curr->magic != HEAP_MAGIC) { + kernel_panic("Kernel Heap Corruption detected: invalid magic token!"); + } + + if (curr->is_free && curr->size >= aligned_size) { + /* Check if block can be split */ + if (curr->size >= aligned_size + sizeof(heap_block_t) + 32) { + uintptr_t new_block_addr = (uintptr_t)curr + sizeof(heap_block_t) + aligned_size; + heap_block_t* new_block = (heap_block_t*)new_block_addr; + + new_block->size = curr->size - aligned_size - sizeof(heap_block_t); + new_block->is_free = true; + new_block->magic = HEAP_MAGIC; + new_block->next = curr->next; + new_block->prev = curr; + + if (curr->next) { + curr->next->prev = new_block; + } + curr->next = new_block; + curr->size = aligned_size; + } + + curr->is_free = false; + return (void*)((uint8_t*)curr + sizeof(heap_block_t)); + } + curr = curr->next; + } + + return NULL; /* Out of heap memory */ +} + +void kfree(void* ptr) { + if (!ptr) return; + + heap_block_t* block = (heap_block_t*)((uint8_t*)ptr - sizeof(heap_block_t)); + + if (block->magic != HEAP_MAGIC) { + kernel_panic("Kernel kfree error: double free or invalid memory pointer!"); + } + + block->is_free = true; + + /* Coalesce with next block if free */ + if (block->next && block->next->is_free) { + block->size += sizeof(heap_block_t) + block->next->size; + block->next = block->next->next; + if (block->next) { + block->next->prev = block; + } + } + + /* Coalesce with prev block if free */ + if (block->prev && block->prev->is_free) { + block->prev->size += sizeof(heap_block_t) + block->size; + block->prev->next = block->next; + if (block->next) { + block->next->prev = block->prev; + } + } +} + +void* kcalloc(size_t num, size_t size) { + size_t total = num * size; + void* ptr = kmalloc(total); + if (ptr) { + uint8_t* p = (uint8_t*)ptr; + for (size_t i = 0; i < total; i++) { + p[i] = 0; + } + } + return ptr; +} + +void* krealloc(void* ptr, size_t new_size) { + if (!ptr) { + return kmalloc(new_size); + } + if (new_size == 0) { + kfree(ptr); + return NULL; + } + + heap_block_t* block = (heap_block_t*)((uint8_t*)ptr - sizeof(heap_block_t)); + if (block->magic != HEAP_MAGIC) { + kernel_panic("Kernel krealloc error: invalid magic header!"); + } + + if (block->size >= new_size) { + return ptr; /* Existing block is already large enough */ + } + + void* new_ptr = kmalloc(new_size); + if (!new_ptr) return NULL; + + uint8_t* src = (uint8_t*)ptr; + uint8_t* dst = (uint8_t*)new_ptr; + for (size_t i = 0; i < block->size; i++) { + dst[i] = src[i]; + } + + kfree(ptr); + return new_ptr; +} + +size_t heap_get_total_bytes(void) { + return heap_total_size; +} + +size_t heap_get_used_bytes(void) { + size_t used = 0; + heap_block_t* curr = heap_head; + while (curr) { + if (!curr->is_free) { + used += curr->size + sizeof(heap_block_t); + } + curr = curr->next; + } + return used; +} + +size_t heap_get_free_bytes(void) { + size_t free_mem = 0; + heap_block_t* curr = heap_head; + while (curr) { + if (curr->is_free) { + free_mem += curr->size; + } + curr = curr->next; + } + return free_mem; +} diff --git a/kernel/kmain.c b/kernel/kmain.c index 2edc3df..07d623a 100644 --- a/kernel/kmain.c +++ b/kernel/kmain.c @@ -4,6 +4,9 @@ #include #include #include +#include +#include +#include void kernel_main(uint64_t magic, uint64_t addr) { /* Step 1: Initialize hardware VGA terminal console */ @@ -51,7 +54,30 @@ void kernel_main(uint64_t magic, uint64_t addr) { keyboard_init(); vga_puts(" [OK] PS/2 Hardware Keyboard : Scan Code Set 1 Driver active\n"); - /* Step 6: Enable CPU Hardware Interrupts */ + /* Step 6: Phase 3 - Physical Memory Manager (PMM) */ + pmm_init(1024ULL * 1024 * 1024); + vga_set_color(VGA_COLOR_LIGHT_CYAN, VGA_COLOR_BLACK); + vga_puts(" [OK] Physical Memory Manager : 1024 MB managed ("); + vga_putdec(pmm_get_free_memory_kb() / 1024); + vga_puts(" MB free RAM)\n"); + + /* Step 7: Phase 3 - Virtual Memory & Page Fault Handler */ + vmm_init(); + vga_puts(" [OK] Virtual Memory Manager : Dynamic #PF Exception Handler active\n"); + + /* Step 8: Phase 3 - Sovereign Dynamic Kernel Heap (kmalloc / kfree) */ + heap_init(KERNEL_HEAP_START, KERNEL_HEAP_SIZE); + vga_puts(" [OK] Sovereign Dynamic Heap : 32 MB dynamic pool at 0x1000000\n"); + + /* Dynamic Heap Self-Test */ + void* test_alloc = kmalloc(512); + if (test_alloc != NULL) { + vga_set_color(VGA_COLOR_LIGHT_GREEN, VGA_COLOR_BLACK); + vga_puts(" [OK] Dynamic Heap Verification : kmalloc(512) & kfree() self-test passed!\n"); + kfree(test_alloc); + } + + /* Step 9: Enable CPU Hardware Interrupts */ __asm__ volatile ("sti"); vga_set_color(VGA_COLOR_GREEN, VGA_COLOR_BLACK); vga_puts(" [OK] Hardware Interrupts Active : STI executed (IF=1)\n"); diff --git a/kernel/pmm.c b/kernel/pmm.c new file mode 100644 index 0000000..73052f0 --- /dev/null +++ b/kernel/pmm.c @@ -0,0 +1,136 @@ +#include +#include + +extern uint8_t _kernel_start[]; +extern uint8_t _kernel_end[]; + +static uint8_t* pmm_bitmap = NULL; +static size_t pmm_total_frames = 0; +static size_t pmm_used_frames = 0; + +static inline void pmm_set_bit(size_t frame) { + pmm_bitmap[frame / 8] |= (1 << (frame % 8)); +} + +static inline void pmm_clear_bit(size_t frame) { + pmm_bitmap[frame / 8] &= ~(1 << (frame % 8)); +} + +static inline bool pmm_test_bit(size_t frame) { + return (pmm_bitmap[frame / 8] & (1 << (frame % 8))) != 0; +} + +void pmm_init(uintptr_t mem_size) { + if (mem_size > PMM_MAX_MEMORY || mem_size == 0) { + mem_size = PMM_MAX_MEMORY; + } + + pmm_total_frames = mem_size / PAGE_SIZE; + pmm_used_frames = pmm_total_frames; /* Initially mark all as used */ + + /* Place bitmap directly at _kernel_end (page aligned) */ + uintptr_t bitmap_addr = ((uintptr_t)_kernel_end + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1); + pmm_bitmap = (uint8_t*)bitmap_addr; + + /* Fill bitmap with 1s (all used) */ + size_t bitmap_bytes = pmm_total_frames / 8; + for (size_t i = 0; i < bitmap_bytes; i++) { + pmm_bitmap[i] = 0xFF; + } + + /* Usable memory starts immediately after the bitmap */ + uintptr_t free_mem_start = bitmap_addr + bitmap_bytes; + free_mem_start = (free_mem_start + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1); + + size_t start_frame = free_mem_start / PAGE_SIZE; + for (size_t frame = start_frame; frame < pmm_total_frames; frame++) { + pmm_clear_bit(frame); + pmm_used_frames--; + } +} + +void* pmm_alloc_frame(void) { + size_t bitmap_bytes = pmm_total_frames / 8; + + for (size_t i = 0; i < bitmap_bytes; i++) { + if (pmm_bitmap[i] != 0xFF) { + for (int bit = 0; bit < 8; bit++) { + if (!(pmm_bitmap[i] & (1 << bit))) { + size_t frame = i * 8 + bit; + if (frame < pmm_total_frames) { + pmm_set_bit(frame); + pmm_used_frames++; + return (void*)(frame * PAGE_SIZE); + } + } + } + } + } + return NULL; /* Out of physical memory */ +} + +void pmm_free_frame(void* frame_addr) { + uintptr_t addr = (uintptr_t)frame_addr; + size_t frame = addr / PAGE_SIZE; + + if (frame < pmm_total_frames && pmm_test_bit(frame)) { + pmm_clear_bit(frame); + pmm_used_frames--; + } +} + +void* pmm_alloc_frames(size_t count) { + if (count == 0) return NULL; + if (count == 1) return pmm_alloc_frame(); + + size_t free_run = 0; + size_t start_frame = 0; + + for (size_t frame = 0; frame < pmm_total_frames; frame++) { + if (!pmm_test_bit(frame)) { + if (free_run == 0) { + start_frame = frame; + } + free_run++; + if (free_run == count) { + for (size_t j = start_frame; j < start_frame + count; j++) { + pmm_set_bit(j); + pmm_used_frames++; + } + return (void*)(start_frame * PAGE_SIZE); + } + } else { + free_run = 0; + } + } + return NULL; +} + +void pmm_free_frames(void* frame_addr, size_t count) { + uintptr_t addr = (uintptr_t)frame_addr; + size_t start_frame = addr / PAGE_SIZE; + + for (size_t i = 0; i < count; i++) { + size_t frame = start_frame + i; + if (frame < pmm_total_frames && pmm_test_bit(frame)) { + pmm_clear_bit(frame); + pmm_used_frames--; + } + } +} + +size_t pmm_get_total_frames(void) { + return pmm_total_frames; +} + +size_t pmm_get_used_frames(void) { + return pmm_used_frames; +} + +size_t pmm_get_free_frames(void) { + return pmm_total_frames - pmm_used_frames; +} + +uint64_t pmm_get_free_memory_kb(void) { + return (uint64_t)(pmm_get_free_frames() * PAGE_SIZE) / 1024; +} diff --git a/kernel/vmm.c b/kernel/vmm.c new file mode 100644 index 0000000..45549a3 --- /dev/null +++ b/kernel/vmm.c @@ -0,0 +1,38 @@ +#include +#include +#include + +static void page_fault_handler(registers_t* regs) { + uintptr_t faulting_addr = read_cr2(); + + bool present = (regs->err_code & 0x1) != 0; + bool write = (regs->err_code & 0x2) != 0; + bool user = (regs->err_code & 0x4) != 0; + bool reserved = (regs->err_code & 0x8) != 0; + bool ifetch = (regs->err_code & 0x10) != 0; + + vga_set_color(VGA_COLOR_LIGHT_RED, VGA_COLOR_BLACK); + vga_puts("\n\n [FATAL] PAGE FAULT (#PF) DETECTED!\n"); + vga_puts(" ----------------------------------------------------\n"); + vga_puts(" Faulting Virtual Address (CR2) : "); + vga_puthex(faulting_addr); + vga_puts("\n Error Code : "); + vga_puthex(regs->err_code); + vga_puts("\n Flags: "); + if (!present) vga_puts("[Not Present] "); + else vga_puts("[Protection Violation] "); + if (write) vga_puts("[Write] "); + else vga_puts("[Read] "); + if (user) vga_puts("[User Ring3] "); + else vga_puts("[Kernel Ring0] "); + if (reserved) vga_puts("[Reserved Bit] "); + if (ifetch) vga_puts("[Instruction Fetch] "); + vga_puts("\n ----------------------------------------------------\n"); + + kernel_panic("Kernel unhandled page fault access violation"); +} + +void vmm_init(void) { + /* Register Page Fault handler on CPU Exception Vector 14 */ + register_interrupt_handler(14, page_fault_handler); +} diff --git a/linker.ld b/linker.ld index 36697f1..8592325 100644 --- a/linker.ld +++ b/linker.ld @@ -9,6 +9,7 @@ SECTIONS { /* Load kernel at 1MB (standard Multiboot load boundary) */ . = 1M; + _kernel_start = .; /* Multiboot Header & Executable Code */ .text : ALIGN(4K) @@ -36,6 +37,9 @@ SECTIONS *(.bss .bss.*) } + . = ALIGN(4K); + _kernel_end = .; + /* Discard unused unwind & debug sections */ /DISCARD/ : {