KFS_3 — Memory Paging
Now we are getting serious. You know how to use malloc? Do you know how it really works?
Last round we declared the memory space into the BIOS, and now it’s time to use it. It’s time to code memory paging, allocation, and free.
To remind yourself what dynamic memory allocation is:
The task of fulfilling an allocation request consists of locating a block of unused memory of sufficient size. Memory requests are satisfied by allocating portions from a large pool of memory called the heap or free store. At any given time, some parts of the heap are in use, while some are “free” (unused) and thus available for future allocations.
This is more than malloc — this is memory paging, physical and virtual memory, and memory code structures.
This subject is one of the more important of the Kernel From Scratch series. Take your time, learn everything.
What to Achieve
To consider KFS_3 complete, the kernel will have:
- A complete memory code structure with pagination handling
- Read and write permissions on memory
- User space memory and kernel space memory
- Physical and virtual memory
- Code helpers for physical memory:
kmalloc,kfree,ksize,kbrk - Code helpers for virtual memory:
vmalloc,vfree,vsize,vbrk - Kernel panic handling
The memory must be a complete, stable, and functional memory system in the kernel.
Specific Requirements
- Enable memory paging in the kernel
- Code a memory structure that handles paging and memory rights
- Define kernel and user space
- Implement a function to create/get memory pages
- Implement a function to allocate, free, and get size of a variable
- Implement those functions for both virtual and physical memory
- Handle kernel panics (print, stop the kernel)
- Keep it under 10MB
Extra Fun
- Implement memory dumping and debug in NPS
Module Structure
kfs_3/kfs/src/
├── lib.rs
├── gdt.rs
├── shell.rs
├── drivers/
│ ├── mod.rs
│ ├── vga.rs
│ └── keyboard.rs
├── interrupts/
│ ├── mod.rs
│ ├── idt.rs
│ ├── pic.rs
│ └── handlers.rs
└── memory/
├── mod.rs
├── paging.rs ← Frame allocator, page tables, init
├── physical_mem.rs ← kmalloc, kfree, ksize (TODO)
└── virtual_mem.rs ← vmalloc, vfree, vsize (TODO)
Current Status
| Component | Status |
|---|---|
| Frame allocator | ✅ Bump allocator |
| Page directory | ✅ Allocated and zeroed |
| Identity mapping (4MB) | ✅ Working |
| Recursive mapping | ✅ Set up |
| Paging enabled | ✅ CR3 + CR0 PG bit |
map_page / unmap_page | ✅ Implemented |
get_physaddr | ✅ Implemented |
kmalloc / kfree / ksize | ❌ Not yet implemented |
vmalloc / vfree / vsize | ❌ Not yet implemented |