I'm starting to home in on the user's need for a VMM. It's for a small OS, so I'm immediately focused on constraints. I'm taking a close look at the existing kernel code to figure out how to best integrate it. What are the major memory-related components?
Detailing the Architecture
I'm now diving deep into the technical specifications. My focus is on x86, specifically 32-bit paging. I'm outlining the core structures like the page directory and page tables, along with essential flags. I'm identifying key functions such as vmm_init(), vmm_map_page(), and vmm_unmap_page() as the core building blocks for this VMM.
Planning the Implementation
I'm now detailing the implementation steps. The physical memory manager is a necessary component, so I'll create a basic interface for it. Defining page directory entries, page table entries, and the relevant x86 flags will be next. After that, I'll tackle the mapping, unmapping, and context-switching functions.
Evaluating Refinements
I'm now iterating on the implementation, with crucial refinements taking shape. My thoughts center on identity mapping the kernel pages during initialization, a critical step for preventing crashes when paging is enabled. Furthermore, I'm thinking through where to store page tables; the physical memory manager's role is becoming more defined.
Analyzing the Implementation
Now I'm focusing on the implementation's corner cases and potential pitfalls. Identity mapping is complete, and the role of the PMM is well-defined. My biggest concern is making sure to flush the TLB correctly after every page mapping or unmapping to guarantee correctness. I'm also ensuring the provided code adheres to all of the project constraints.
Reviewing for Compilation
I'm now carefully checking the code to ensure it meets all design constraints. I'm especially focused on the TLB flushes and confirming they happen correctly. Further, the PMM's interaction is fully encapsulated. I have performed a basic code review to ensure that all requirements are met.
This is an implementation of a Virtual Memory Manager (VMM) for a 32-bit x86 protected mode kernel. This architecture uses a 2-level paging hierarchy (Page Directory → Page Tables → Physical Memory).
For this code to work in a real kernel, you need a Physical Memory Manager (PMM) to allocate raw blocks of RAM (frames). I have included a stub for the PMM at the top so the logic is clear.
1. header.h (Definitions)
First, we define standard x86 paging flags and types.
This file contains the logic to map virtual addresses to physical addresses.
Prerequisite: Physical Memory Manager Stub
In a real OS, these functions return the physical address of a free 4KB block of RAM.
c
// --- START PMM STUB (Replace with your actual frame allocator) ---
void* pmm_alloc_block() {
// REAL IMPLEMENTATION: Return a free physical frame from bitmap/stack
return (void*)0x100000; // Dummy return
}
void pmm_free_block(void* p) {
// REAL IMPLEMENTATION: Mark frame as free
}
// --- END PMM STUB ---
The Virtual Memory Manager
c
How it works
Addressing: x86 splits a 32-bit Virtual Address into three parts:
Top 10 bits: Index in the Page Directory.
Middle 10 bits: Index in the Page Table.
Bottom 12 bits: Offset within the actual 4KB physical page.
Identity Mapping: In vmm_init, we map the physical addresses 0-4MB to the exact same virtual addresses. This is crucial. If the kernel code is executing at 0x100000 (physical), and we turn on paging without mapping virtual 0x100000 to physical 0x100000, the next CPU instruction fetch will create a Page Fault and crash the system.
TLB (Translation Lookaside Buffer): The CPU caches address translations. If we modify the page tables, the CPU doesn't look at RAM immediately. We use the assembly instruction invlpg to tell the CPU "re-read the table for this specific address."
Usage Example
c
void kernel_main() {
// Initialize system
pmm_init(); // Initialize your physical allocator
vmm_init(); // Initialize paging
// Example: Map physical address 0x500000 (a video buffer, perhaps)
// to virtual address 0xC0000000
void* phys_addr = (void*)0x500000;
void* virt_addr = (void*)0xC0000000;
vmm_map_page(phys_addr, virt_addr, I86_PTE_PRESENT | I86_PTE_WRITABLE);
// Now we can write to 0xC0000000 and it goes to RAM at 0x500000
uint32_t* ptr = (uint32_t*)virt_addr;
*ptr = 0xDEADBEEF;
}
The code above simplifies step 4 (Get the Page Table). Once paging is on, you cannot access physical addresses directly. If you need to update a Page Table (which resides in physical memory), you cannot just dereference page_table_t*.
To solve this, OS developers use Recursive Mapping or Fractal Mapping. You map the last entry of the Page Directory to point to the Page Directory itself. This allows you to calculate a virtual address that lets you modify page tables as if they were normal memory.
For a beginner implementation, it is often easier to just identity map all RAM used for page tables, or simply disable paging temporarily (dangerous) to make updates, until you are ready to implement recursive mapping.
// Current active directory
page_directory_t* _current_directory = NULL;
// Helper: Invalidate Translation Lookaside Buffer (TLB)
// Forces the CPU to refresh its cache for this specific page.
static inline void vmm_flush_tlb_entry(uint32_t addr) {
__asm__ volatile("invlpg (%0)" :: "r" (addr) : "memory");
}
// Switch Page Directory (Context Switch)
// Loads Cr3 register with physical address of directory
void vmm_switch_directory(page_directory_t* dir) {
_current_directory = dir;
__asm__ volatile("mov %0, %%cr3" :: "r" (dir) : "memory");
}
// Map a specific page
// phys: Physical Address
// virt: Virtual Address target
// flags: Permissions (I86_PTE_PRESENT | I86_PTE_WRITABLE, etc)
bool vmm_map_page(void* phys, void* virt, uint32_t flags) {
// 1. Calculate indices
uint32_t pd_index = PDE_INDEX(virt);
uint32_t pt_index = PTE_INDEX(virt);
// 2. Get the Page Directory Entry
pd_entry* e = &_current_directory->entries[pd_index];
// 3. Check if the Page Table exists. If not, create it.
if ((*e & I86_PTE_PRESENT) != I86_PTE_PRESENT) {
// Allocate a new physical frame for the page table
void* new_table_phys = pmm_alloc_block();
if (!new_table_phys) return false; // Out of memory
// Important: We must likely map this new physical address to a
// temporary virtual address to zero it out if paging is already on.
// For simplicity here, we assume we can access it directly or paging is off.
page_table_t* new_table_virt = (page_table_t*)new_table_phys;
// Zero out the new table (prevent garbage mappings)
for(int i = 0; i < ENTRIES_PER_TABLE; i++) {
new_table_virt->entries[i] = 0;
}
// Update Page Directory Entry to point to this new table's PHYSICAL address
// We add flags (Present + R/W + User) to the directory entry
*e = (uint32_t)new_table_phys | I86_PTE_PRESENT | I86_PTE_WRITABLE | I86_PTE_USER;
}
// 4. Get the Page Table
// Note: In a fully recursive mapping setup, getting the virtual address
// of the table is tricky. Here we assume *e contains a valid pointer
// or we have identity mapping covering kernel space.
page_table_t* table = (page_table_t*)PAGE_GET_PHYSICAL_ADDR(e);
// 5. Get the specific Page Table Entry
pt_entry* page = &table->entries[pt_index];
// 6. Set the mapping (Physical Address + Flags)
*page = (uint32_t)phys | flags;
// 7. Flush TLB so CPU knows about the change immediately
vmm_flush_tlb_entry((uint32_t)virt);
return true;
}
// Unmap a page
void vmm_unmap_page(void* virt) {
uint32_t pd_index = PDE_INDEX(virt);
uint32_t pt_index = PTE_INDEX(virt);
pd_entry* e = &_current_directory->entries[pd_index];
// If table doesn't exist, nothing to unmap
if ((*e & I86_PTE_PRESENT) != I86_PTE_PRESENT) return;
page_table_t* table = (page_table_t*)PAGE_GET_PHYSICAL_ADDR(e);
pt_entry* page = &table->entries[pt_index];
// If page exists, clear it
if (*page & I86_PTE_PRESENT) {
// Optional: Get physical address and free it via PMM
// void* phys_frame = (void*)PAGE_GET_PHYSICAL_ADDR(page);
// pmm_free_block(phys_frame);
*page = 0; // Clear mapping
vmm_flush_tlb_entry((uint32_t)virt);
}
}
// Initializer
void vmm_init() {
// 1. Allocate a Directory
page_directory_t* dir = (page_directory_t*)pmm_alloc_block();
// 2. Clear it
for(int i = 0; i < ENTRIES_PER_TABLE; i++) {
dir->entries[i] = 0x00000002; // Supervisor, RW, Not Present
}
// 3. Identity Map the Kernel (Essential!)
// Assuming Kernel is resident in first 1MB. We map 0x0 -> 0x0, 0x1000 -> 0x1000, etc.
// Without this, enabling paging crashes immediately because EIP points to physical
// addresses which satisfy the fetch, but after paging, the CPU can't translate them.
_current_directory = dir;
// Identity map the first 4MB (1 Page Table covers 4MB)
// Map Virt 0x00000000 -> Phys 0x00000000
for (int i = 0; i < 1024; i++) {
uint32_t phys_addr = i * PAGE_SIZE;
vmm_map_page((void*)phys_addr, (void*)phys_addr, I86_PTE_PRESENT | I86_PTE_WRITABLE);
}
// 4. Load CR3 and Enable Paging
vmm_switch_directory(dir);
uint32_t cr0;
__asm__ volatile("mov %%cr0, %0" : "=r"(cr0));
cr0 |= 0x80000000; // Set PG (Paging) bit 31
__asm__ volatile("mov %0, %%cr0" :: "r"(cr0));
}