1. Understand the Goal: The user wants an implementation of a Virtual Memory Manager (VMM) in C, designed for a small operating system kernel.
Identify Key Components of a VMM:
Physical Memory Management: Needs a way to track which physical frames are free and which are allocated. (Page Frame Allocator).
Virtual Memory Structures: Page Tables (hierarchical, usually 2-level for 32-bit or 4-level for 64-bit). I should stick to a simplified 32-bit model (x86 style) for clarity and manageability in a single response.
Page Directory & Page Table Entries (PDE/PTE): Bit flags (Present, Read/Write, User/Supervisor, etc.) and physical address alignment.
Mapping Logic: The core function: map_page(virtual_address, physical_address, flags).
Translation Lookaside Buffer (TLB) Management: Need to invalidate TLB entries when page tables change (invlpg).
Context Switching: Loading a new Page Directory Base Address (cr3).
Heap/Stack Management (Optional but good context): How the VMM serves dynamic memory requests (though kmalloc is often a separate layer on top, I'll focus on the page mapping part).
Determine the Scope & Constraints:
Language: C (with inline Assembly for hardware interaction).
Architecture: x86 (32-bit) is the standard "learning" architecture for OS dev because 64-bit adds complexity like PAE, higher half kernels, and complex linking that might obscure the core VMM logic in a short code snippet.
Dependencies: It assumes a kalloc (kernel allocator) exists for allocating page tables, and some basic type definitions (uint32_t).
alloc_frame(vaddr, flags): Get a physical frame and map it.
map_page(vaddr, paddr, flags): The mechanics of setting PTEs.
switch_page_directory(pd): Update CR3.
page_fault_handler(): Essential to see it working (even if rudimentary).
Refining the Code Structure (Mental Draft):
Header: Struct definitions, macros.
Physical Frame Allocator (PFA): I can't write a full OS, but I need a stub or a simple bitmap stack allocator to make the VMM functional. Let's use a simple "bump allocator" for physical memory to keep it simple, or just assume the user provides physical frames. Decision: I will implement a simple bitset-based physical frame allocator to make the code self-contained and usable.
VMM Core: The logic to handle the recursive mapping or standard 2-level lookup.
Check if Page Table exists. If not, allocate it and clear it. Update PDE.
Get Page Table Index.
Set the PTE with physical address and flags.
Invalidate TLB.
Assembly: Need invlpg and mov cr3.
Addressing "Self-Contained" requirement:
Since this is for a kernel, standard library (stdlib.h) is not available. I need to define memset, memcpy, or assume they exist. I'll provide a basic memset implementation.
Structuring the Output:
Introduction: Explain the x86 32-bit paging mechanism.
Virtual Memory Manager (VMM): The core logic (mapping, directory switching).
Assembly Helpers: For CR3 and TLB.
Usage Example: How to call these in kernel_main.
Self-Correction/Review during drafting:
Issue: 32-bit address space limits.
Resolution: Keep it 32-bit for simplicity.
Issue: Where do page tables come from?
Resolution: The VMM needs to allocate memory for the page table structures themselves. This memory must be identity-mapped (kernel space) so the kernel can access the tables to modify them. I will enforce that page tables are allocated from the kernel heap/physical area that is always mapped.
Final Polish: Add comments explaining why bit shifting is happening (10 bits for dir, 10 bits for table, 12 bits offset). Ensure types are standard (uint32_t).
(Self-Correction during code generation): I should make sure the paging structures align correctly (packed structs). I need to handle the case where the physical frame is not provided (demand paging) vs provided. For this example, explicit mapping vaddr -> paddr is the most educational approach.
Constructing the Final Response: (This matches the detailed output provided previously).
Define standard types.
Define bitmasks.
Implement PMM (Bitset).
Implement VMM (Mapping logic).
Inline ASM.
Final Code Check:
page_directory: array of 1024 entries.
page_table: array of 1024 entries.
Mapping logic: Correctly indexes current_directory->tables[dir_index]? Wait, standard C arrays are tricky here. A page directory entry holds the physical address of the page table. But the kernel needs to write to the virtual address of that page table to update it.
Crucial Design Choice: To keep this simple, I will implement a structure that holds both the physical pointer (for the CPU) and a virtual pointer (for the kernel to edit the table).
Alternative: Recursive mapping. Too complex for a snippet.
Decision: Use a wrapper struct for the directory that tracks both physical and virtual addresses of the tables.
Let's write the code based on this plan.
PMM:alloc_frame() returns a physical address.
VMM:map_page(virtual, physical, flags).
Get PDE.
If PDE not present: alloc_frame() for the table itself. Zero it. Set PDE.
Get PTE from the table.
Set PTE.
This looks solid. I will produce the C code with inline assembly. Note: I will assume a 32-bit x86 architecture.
Implementing a Virtual Memory Manager (VMM) is a complex task involving interaction with hardware (MMU), physical memory allocation, and logical address manipulation.
Below is a complete, simplified implementation for an x86 (32-bit) architecture. This code is designed to be part of a kernel. It handles Page Directory management, Page Table creation, and the mapping of virtual addresses to physical frames.
Prerequisites & Assumptions
Architecture: x86 32-bit (4KB pages).
Physical Allocator: The code assumes a function kalloc_frame() exists that returns a physical memory address (4KB aligned) for a new page.
Memory Clearing: Assumes memset is available.
Kernel Space: The kernel is assumed to be mapped in the higher half (though the logic works for low memory too).
1. Data Structures and Definitions
First, we define the bitmasks for page flags and the structures representing Page Tables and Page Directories.
c
#include <stdint.h>
#include <stddef.h>
// Helper macros for bitmasking
#define PAGE_PRESENT 0x1
#define PAGE_WRITABLE 0x2
#define PAGE_USER 0x4
#define PAGE_ACCESSED 0x20
#define PAGE_DIRTY 0x40
#define PAGE_4MB 0x80 // For directory entries
#define PAGE_FRAME 0xFFFFF000
// Standard 4KB page size
#define PAGE_SIZE 4096
// A single Page Table Entry (4 bytes)
typedef struct {
uint32_t present : 1;
uint32_t rw : 1; // Read/Write
uint32_t user : 1; // User/Supervisor
uint32_t accessed : 1;
uint32_t dirty : 1;
uint32_t unused : 7; // Reserved bits
uint32_t frame : 20; // Physical Frame Address (shifted right 12 bits)
} page_table_entry_t;
// A single Page Directory Entry (4 bytes)
typedef struct {
uint32_t present : 1;
uint32_t rw : 1;
uint32_t user : 1;
uint32_t accessed : 1;
uint32_t unused : 4;
uint32_t size : 1; // 0 = 4KB, 1 = 4MB
uint32_t ignored : 1;
uint32_t available : 3;
uint32_t table_addr : 20; // Physical address of the page table
} page_directory_entry_t;
// A Page Table (1024 entries)
typedef struct {
page_table_entry_t pages[1024];
} page_table_t;
// A Page Directory (1024 entries)
typedef struct {
page_directory_entry_t tables[1024];
// Array of pointers to page tables for easier kernel access later
// (Only needed if we map the directory into itself, see note below)
uint32_t physical_addr;
} page_directory_t;
// Current directory
page_directory_t *current_directory = NULL;
2. Physical Memory Interface (Stub)
In a real kernel, you would have a bitmap or stack allocator managing physical RAM. Here is the interface we will use:
c
// Defined in your physical memory manager (pmm.c)
extern void* kalloc_frame(); // Returns a physical address (void*)
extern void kfree_frame(void* addr);
// Helper to zero out a page
void clear_page(void* phys_addr) {
// In a real kernel, you must map this physical address to a virtual
// one temporarily to zero it. Here we assume identity mapping or
// a function that handles the mapping internally.
// For this example, we simulate it:
// memset(phys_to_virt(phys_addr), 0, PAGE_SIZE);
}
3. The Virtual Memory Manager Implementation
This section handles the core logic: calculating indices and updating hardware structures.
c
4. Initialization
This function sets up the initial environment. In a real kernel (like Linux or simple hobby OS), you typically map the kernel code (higher half) and possibly identity map the bottom 4MB or 16MB for legacy hardware/bios calls if needed.
c
void init_vmm() {
// 1. Allocate the Page Directory
// We need physical memory for the directory structure itself
void* dir_phys = kalloc_frame();
current_directory = (page_directory_t*)dir_phys; // Again, assuming identity map for setup
// Zero out the directory (mark all entries not present)
memset(current_directory, 0, sizeof(page_directory_t));
current_directory->physical_addr = (uint32_t)dir_phys;
// 2. Identity Map the first 1MB (or 4MB)
// Useful for accessing video memory or BIOS structures easily during early boot
// We map virtual 0x00000000 -> physical 0x00000000
uint32_t i = 0;
while (i < 0x400000) { // First 4MB
map_page(i, i, PAGE_PRESENT | PAGE_WRITABLE);
i += PAGE_SIZE;
}
// 3. Enable Paging in hardware
// Read CR0, set the Paging bit (bit 31), write back
uint32_t cr0;
asm volatile("mov %%cr0, %0" : "=r"(cr0));
cr0 |= 0x80000000; // Set paging bit
asm volatile("mov %0, %%cr0" : : "r"(cr0));
// 4. Load the directory
switch_page_directory(current_directory);
}
5. The "Recursive Mapping" Trick (Advanced Note)
In the code above, the function get_pte_from_pde casts a physical address to a pointer. This works in early boot or if you have identity mapping. However, once the kernel runs in high memory (e.g., 0xC0100000), you cannot access physical address 0x00001000 directly.
The Solution:
A common trick is to map the last entry of the Page Directory to the directory itself.
If you access 0xFFFFF000, the CPU looks at the last entry (index 1023) of the directory.
Since that entry points to the directory itself, the MMU returns the contents of the Directory.
If you access 0xFFC00000, the MMU treats the Page Directory as a giant Page Table, allowing you to modify any Page Table entry using virtual math rather than physical allocation pointers.
Summary of Operation
init_vmm: Allocates a directory, maps essential memory (like the kernel and video memory), and sets the CR0 register to enable paging.
map_page: Takes a Virtual Address and a Physical Address. It finds the correct Page Table Entry in the hierarchy. If the Page Table doesn't exist, it allocates physical RAM for it. It then updates the PTE to point to the physical frame.
switch_page_directory: Updates the CR3 register. This is vital during context switching (switching between processes), as every process has its own Page Directory.
// Helper to extract indices from a virtual address
// Format: [10 bits Directory][10 bits Table][12 bits Offset]
#define DIR_INDEX(addr) (((uint32_t)(addr) >> 22) & 0x3FF)
#define TABLE_INDEX(addr) (((uint32_t)(addr) >> 12) & 0x3FF)
// Low-level assembly to flush the TLB (Translation Lookaside Buffer)
// Needed after updating a page mapping so the CPU sees the change
static inline void invlpg(void* addr) {
asm volatile ("invlpg (%0)" : : "r" (addr));
}
// Load CR3 with the physical address of the directory
void switch_page_directory(page_directory_t *dir) {
current_directory = dir;
asm volatile ("mov %0, %%cr3" : : "r" (dir->physical_addr));
}
// Get a pointer to the Page Table Entry for a specific virtual address
// If create == 1, it allocates a new table if one doesn't exist.
page_table_entry_t* get_page(uint32_t virtual_addr, int create, page_directory_t *dir) {
// 1. Calculate indices
uint32_t dir_idx = DIR_INDEX(virtual_addr);
uint32_t table_idx = TABLE_INDEX(virtual_addr);
// 2. Check if the Page Directory Entry (PDE) exists
if (dir->tables[dir_idx].present) {
// PDE exists. Retrieve the physical address of the table.
// NOTE: To access the table structure to modify it, we need its VIRTUAL address.
// This requires a recursive mapping trick (mapping the PD into itself) or
// a temporary mapping area.
// For this implementation, we assume a standard 'identity mapping'
// of kernel structures or a helper to convert physical to virtual.
// Let's assume we have a function 'get_virtual_table_ptr' for clarity.
// Pseudo-code for accessing the table:
// page_table_t *table = (page_table_t*)(dir->tables[dir_idx].table_addr << 12);
// return &table->pages[table_idx];
// Implementation using a helper (defined below):
return get_pte_from_pde(&dir->tables[dir_idx], table_idx);
} else if (create) {
// 3. PDE doesn't exist, but we are asked to create it.
// Allocate a physical frame for the new Page Table
void* phys = kalloc_frame();
if (!phys) return NULL; // Out of memory
// Clear the new table
clear_page(phys);
// Configure the Directory Entry
dir->tables[dir_idx].present = 1;
dir->tables[dir_idx].rw = 1;
dir->tables[dir_idx].user = 1; // Allow user-mode access by default
dir->tables[dir_idx].table_addr = ((uint32_t)phys) >> 12;
// Return the entry (call recursively now that it exists)
return get_pte_from_pde(&dir->tables[dir_idx], table_idx);
}
return NULL;
}
// Helper to access a Page Table Entry given a PDE
// NOTE: This implies you have a way to access physical memory.
// In a high-half kernel, you usually map the last 4MB of virtual space
// to the current Page Directory to access tables easily.
page_table_entry_t* get_pte_from_pde(page_directory_entry_t *pde, uint32_t idx) {
// Calculate physical address of the table
uint32_t table_phys = pde->table_addr << 12;
// CONVERSION LOGIC:
// In a real OS, you cannot simply cast a physical address to a pointer
// if your kernel is in High Memory (e.g., 0xC0000000+).
// Assuming simple identity mapping for this snippet:
page_table_t *table = (page_table_t*) table_phys;
return &table->pages[idx];
}
// Map a Virtual Address to a Physical Address
void map_page(uint32_t virtual_addr, uint32_t phys_addr, uint32_t flags) {
// 1. Ensure page alignment
if (virtual_addr % PAGE_SIZE != 0 || phys_addr % PAGE_SIZE != 0) {
// Handle error: addresses must be aligned
return;
}
// 2. Get the Page Table Entry (PTE)
// '1' means create the table if it doesn't exist
page_table_entry_t *page = get_page(virtual_addr, 1, current_directory);
if (!page) {
// Handle error: Out of memory creating table
return;
}
// 3. Configure the PTE
page->present = 1;
page->rw = (flags & PAGE_WRITABLE) ? 1 : 0;
page->user = (flags & PAGE_USER) ? 1 : 0;
page->frame = phys_addr >> 12;
// 4. Flush the TLB entry for this virtual address
invlpg((void*)virtual_addr);
}
// Unmap a Virtual Address
void unmap_page(uint32_t virtual_addr) {
page_table_entry_t *page = get_page(virtual_addr, 0, current_directory);
if (page) {
page->present = 0;
page->frame = 0;
// Flush TLB
invlpg((void*)virtual_addr);
}
}