Certainly! Writing memory management functions is a crucial part of developing an operating system. Since you're working in 32-bit protected mode on the x86 architecture, and assuming paging is not yet enabled, we'll need to manage physical memory directly.
Here's an outline of what we'll cover:
- Understanding Memory in Protected Mode
- Initializing a Simple Memory Manager
- Implementing Allocation (
alloc), Free (free), and Count (count) Functions
- Code Examples with Explanations
1. Understanding Memory in Protected Mode
In protected mode, the CPU can access all the physical memory directly, and addresses are translated using segment descriptors in the Global Descriptor Table (GDT). However, without paging, we don't have virtual memory, so we need to manage physical memory carefully.
Before we can allocate or free memory, we need to know:
- Total available memory: Typically retrieved from the BIOS before entering protected mode (e.g., using the
INT 0x15, E820h function).
- Memory map: Information about which regions of memory are usable.
Since you're already in protected mode and might not have this information, we'll make some assumptions for demonstration purposes.
2. Initializing a Simple Memory Manager
We'll create a simple memory manager that:
- Uses a fixed-size memory pool (heap).
- Manages memory using a free list.
- Allocates and frees memory blocks as needed.
- Keeps track of total free memory.
Memory Pool
For simplicity, we'll define a memory pool starting at a specific address. In a real OS, you'd get the starting address and size from the bootloader or from the BIOS before entering protected mode.
Let's assume:
- Heap starts at:
0x01000000 (16 MB mark)
- Heap size:
0x01000000 bytes (16 MB)
This keeps us above the area where the OS code and data might reside.
3. Implementing Allocation (alloc), Free (free), and Count (count) Functions
We'll create the following functions:
void memory_init(); Initialize the memory manager.
void* alloc(size_t size); Allocate a memory block.
void free(void* ptr); Free a previously allocated block.
size_t memory_free(); Get total free memory.
Data Structures
We'll use a simple linked list to manage free memory blocks.
typedef struct memory_block {
size_t size;
struct memory_block* next;
} memory_block_t;
Each memory_block_t represents a block of free memory.
4. Code Examples with Explanations
Below is the complete code with explanations.
#include <stdint.h>
#include <stddef.h>
#define HEAP_START 0x01000000 // 16 MB
#define HEAP_SIZE 0x01000000 // 16 MB
typedef struct memory_block {
size_t size;
struct memory_block* next;
} memory_block_t;
static memory_block_t* free_list = NULL;
void memory_init() {
// Initialize the free list with a single large block
free_list = (memory_block_t*)HEAP_START;
free_list->size = HEAP_SIZE - sizeof(memory_block_t);
free_list->next = NULL;
}
void* alloc(size_t size) {
memory_block_t* current = free_list;
memory_block_t* previous = NULL;
// Align size to 8 bytes for better alignment
size = (size + 7) & ~7;
while (current) {
if (current->size >= size) {
// Found a suitable block
if (current->size <= size + sizeof(memory_block_t)) {
// Not enough space to split the block
if (previous) {
previous->next = current->next;
} else {
free_list = current->next;
}
return (void*)((uintptr_t)current + sizeof(memory_block_t));
} else {
// Split the block
memory_block_t* new_block = (memory_block_t*)((uintptr_t)current + sizeof(memory_block_t) + size);
new_block->size = current->size - size - sizeof(memory_block_t);
new_block->next = current->next;
if (previous) {
previous->next = new_block;
} else {
free_list = new_block;
}
current->size = size;
return (void*)((uintptr_t)current + sizeof(memory_block_t));
}
}
previous = current;
current = current->next;
}
// No suitable block found
return NULL;
}
void free(void* ptr) {
if (!ptr) {
return;
}
memory_block_t* block = (memory_block_t*)((uintptr_t)ptr - sizeof(memory_block_t));
memory_block_t* current = free_list;
memory_block_t* previous = NULL;
// Insert the block back into the free list (sorted by address)
while (current && current < block) {
previous = current;
current = current->next;
}
block->next = current;
if (previous) {
previous->next = block;
} else {
free_list = block;
}
// Try to merge with next block
if (block->next && (uintptr_t)block + block->size + sizeof(memory_block_t) == (uintptr_t)block->next) {
block->size += block->next->size + sizeof(memory_block_t);
block->next = block->next->next;
}
// Try to merge with previous block
if (previous && (uintptr_t)previous + previous->size + sizeof(memory_block_t) == (uintptr_t)block) {
previous->size += block->size + sizeof(memory_block_t);
previous->next = block->next;
}
}
size_t memory_free() {
size_t total_free = 0;
memory_block_t* current = free_list;
while (current) {
total_free += current->size;
current = current->next;
}
return total_free;
}
Explanations
memory_init()
- Initializes the memory manager.
- Sets up the
free_list with a single large block that spans the entire heap.
- Subtracts the size of
memory_block_t from the total heap size to account for the block's metadata.
alloc(size_t size)
- Allocates a block of memory of at least
size bytes.
- Aligns the requested size to an 8-byte boundary for better alignment.
- Searches the free list for a suitable block.
- If a block is found:
- If the block is about the same size as requested (considering metadata size), it allocates the entire block.
- If the block is larger, it splits the block, allocating the requested size and leaving the remainder in the free list.
- Updates the
free_list accordingly.
- Returns a pointer to the allocated memory (after the metadata).
free(void* ptr)
- Frees a previously allocated block.
- Calculates the address of the block's metadata.
- Inserts the block back into the free list, maintaining the list sorted by memory address.
- Attempts to merge with adjacent free blocks to avoid fragmentation.
memory_free()
- Calculates the total free memory by iterating through the free list and summing the sizes of each free block.
Usage Example
void kernel_main() {
memory_init();
void* ptr1 = alloc(1024); // Allocate 1 KB
void* ptr2 = alloc(2048); // Allocate 2 KB
size_t free_mem = memory_free(); // Get total free memory
free(ptr1); // Free the first block
free(ptr2); // Free the second block
free_mem = memory_free(); // Should be the same as initial free memory
}
Notes and Considerations
- Alignment: Aligning memory to 8 bytes (or 16 bytes) is essential for performance on x86 architectures.
- Fragmentation: This simple allocator uses a first-fit algorithm and may suffer from fragmentation over time.
- Safety Checks: In a real OS, you should add safety checks to ensure that pointers passed to
free() are valid.
- Synchronization: If your OS is multitasking, you'll need to handle synchronization (e.g., using spinlocks) to protect the memory manager's data structures.
- Memory Map: For a robust memory manager, you should obtain the system's memory map before entering protected mode and avoid using reserved or hardware-specific memory regions.
Extending the Memory Manager
Once you have paging enabled and a virtual memory system in place, you can extend this memory manager to:
- Allocate and map pages on demand.
- Implement features like memory protection, copy-on-write, and demand paging.
- Manage memory in both kernel and user space.
Conclusion
Implementing a memory manager in your OS is a significant step. The provided code offers a simple starting point for memory allocation, freeing, and counting available memory in 32-bit protected mode on x86 architecture.
Remember that operating system development is complex, and careful planning is essential. Make sure to read more about memory management techniques and consider more advanced algorithms (like buddy allocators or slab allocators) as your OS grows in complexity.
Feel free to ask if you have further questions or need more detailed explanations on any part!