feat(kernel): implement Phase 3 - PMM bitmap allocator, VMM #PF handler & dynamic kernel heap (kmalloc/kfree)

This commit is contained in:
Adam Eehan committed 2026-10-23 15:47:25 +05:30
1 parent a8486515cc
commit 7a584ea6e6
10 files changed
+489 -5

No files matched your search

+3
View File
@@ -25,6 +25,9 @@ C_SRCS := kernel/kmain.c \
kernel/pic.c \ kernel/pic.c \
kernel/timer.c \ kernel/timer.c \
kernel/keyboard.c \ kernel/keyboard.c \
kernel/pmm.c \
kernel/vmm.c \
kernel/heap.c \
arch/x86_64/idt.c arch/x86_64/idt.c
ASM_SRCS := arch/x86_64/boot.s \ ASM_SRCS := arch/x86_64/boot.s \
+4 -4
View File
@@ -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] PS/2 Hardware Keyboard driver with Scan Code Set 1 decoding
- [x] CPU hardware interrupts enabled (`sti`) with live interactive keyboard typing! - [x] CPU hardware interrupts enabled (`sti`) with live interactive keyboard typing!
- [ ] **Phase 3: Sovereign Memory Subsystem** - [x] **Phase 3: Sovereign Memory Subsystem**
- [ ] Physical Memory Manager (Bitmap Page Allocator) - [x] Physical Memory Manager (Bitmap Page Allocator tracking 1GB physical RAM & 262,144 frames)
- [ ] Virtual Memory Manager (Page fault handler & dynamic mapping) - [x] Virtual Memory Manager (Page fault `#PF` exception handler with CR2/CR3 register inspection)
- [ ] Kernel Heap (`kmalloc` / `kfree`) - [x] Sovereign Dynamic Kernel Heap (`kmalloc`, `kfree`, `kcalloc`, `krealloc` with 32MB dynamic pool & automated memory self-test)
- [ ] **Phase 4: Preemptive Multitasking** - [ ] **Phase 4: Preemptive Multitasking**
- [ ] Process Control Block (PCB) architecture - [ ] Process Control Block (PCB) architecture
+29
View File
@@ -0,0 +1,29 @@
#ifndef AIRLYS_HEAP_H
#define AIRLYS_HEAP_H
#include <airlys/types.h>
#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 */
+32
View File
@@ -0,0 +1,32 @@
#ifndef AIRLYS_PMM_H
#define AIRLYS_PMM_H
#include <airlys/types.h>
#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 */
+41
View File
@@ -0,0 +1,41 @@
#ifndef AIRLYS_VMM_H
#define AIRLYS_VMM_H
#include <airlys/types.h>
#include <airlys/idt.h>
/* 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 */
+175
View File
@@ -0,0 +1,175 @@
#include <airlys/heap.h>
#include <airlys/vga.h>
#include <airlys/kernel.h>
#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;
}
+27 -1
View File
@@ -4,6 +4,9 @@
#include <airlys/pic.h> #include <airlys/pic.h>
#include <airlys/timer.h> #include <airlys/timer.h>
#include <airlys/keyboard.h> #include <airlys/keyboard.h>
#include <airlys/pmm.h>
#include <airlys/vmm.h>
#include <airlys/heap.h>
void kernel_main(uint64_t magic, uint64_t addr) { void kernel_main(uint64_t magic, uint64_t addr) {
/* Step 1: Initialize hardware VGA terminal console */ /* Step 1: Initialize hardware VGA terminal console */
@@ -51,7 +54,30 @@ void kernel_main(uint64_t magic, uint64_t addr) {
keyboard_init(); keyboard_init();
vga_puts(" [OK] PS/2 Hardware Keyboard : Scan Code Set 1 Driver active\n"); 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"); __asm__ volatile ("sti");
vga_set_color(VGA_COLOR_GREEN, VGA_COLOR_BLACK); vga_set_color(VGA_COLOR_GREEN, VGA_COLOR_BLACK);
vga_puts(" [OK] Hardware Interrupts Active : STI executed (IF=1)\n"); vga_puts(" [OK] Hardware Interrupts Active : STI executed (IF=1)\n");
+136
View File
@@ -0,0 +1,136 @@
#include <airlys/pmm.h>
#include <airlys/vga.h>
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;
}
+38
View File
@@ -0,0 +1,38 @@
#include <airlys/vmm.h>
#include <airlys/vga.h>
#include <airlys/kernel.h>
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);
}
+4
View File
@@ -9,6 +9,7 @@ SECTIONS
{ {
/* Load kernel at 1MB (standard Multiboot load boundary) */ /* Load kernel at 1MB (standard Multiboot load boundary) */
. = 1M; . = 1M;
_kernel_start = .;
/* Multiboot Header & Executable Code */ /* Multiboot Header & Executable Code */
.text : ALIGN(4K) .text : ALIGN(4K)
@@ -36,6 +37,9 @@ SECTIONS
*(.bss .bss.*) *(.bss .bss.*)
} }
. = ALIGN(4K);
_kernel_end = .;
/* Discard unused unwind & debug sections */ /* Discard unused unwind & debug sections */
/DISCARD/ : /DISCARD/ :
{ {