Skip to content

Instantly share code, notes, and snippets.

@kaworu
Last active December 26, 2015 21:09
Show Gist options
  • Save kaworu/7214540 to your computer and use it in GitHub Desktop.
Save kaworu/7214540 to your computer and use it in GitHub Desktop.
JamesM's kernel development tutorials (The Heap)
void
init_paging(void)
{
int i;
uint32_t mem_end_page;
/* in heap.c */
extern struct vm_heap *kernel_heap;
/*
* The size of physical memory.
* For the moment we assume it is 16MB big.
*/
mem_end_page = 0x1000000;
nframes = mem_end_page / 0x1000;
frames = kmalloc0(INDEX_FROM_BIT(nframes));
/* Let's make a page directory. */
kernel_directory = kmalloc0_a(sizeof(struct vm_page_directory));
/*
* Map some pages in the kernel heap area.
* Here we call get_page but not alloc_frame. This causes page_table_t's
* to be created where necessary. We can't allocate frames yet because
* they they need to be identity mapped first below, and yet we can't
* increase placement_address between identity mapping and enabling the
* heap.
*/
i = 0;
for (i = VM_KERN_HEAP_START; i < VM_KERN_HEAP_START + VM_KERN_HEAP_INITIAL_SIZE; i += 0x1000)
get_page(i, 1, kernel_directory);
/*
* We need to identity map (phys addr = virt addr) from 0x0 to the end
* of used memory, so we can access this transparently, as if paging
* wasn't enabled. NOTE that we use a while loop here deliberately.
* inside the loop body we actually change placement_address by calling
* kmalloc(). A while loop causes this to be computed on-the-fly rather
* than once at the start.
*/
i = 0;
while (i < placement_address + sizeof(struct vm_heap)) {
/* Kernel code is readable but not writeable from userspace. */
alloc_frame(get_page(i, 1, kernel_directory), 0, 0);
i += 0x1000;
}
// Now allocate those pages we mapped earlier.
for (i = VM_KERN_HEAP_START; i < VM_KERN_HEAP_START + VM_KERN_HEAP_INITIAL_SIZE; i += 0x1000)
alloc_frame(get_page(i, 0, kernel_directory), 0, 0);
/* Before we enable paging, we must register our page fault handler. */
register_interrupt_handler(14, page_fault_handler);
/* Now, enable paging! */
switch_page_directory(kernel_directory);
// Initialise the kernel heap.
kernel_heap = new_heap(VM_KERN_HEAP_START, VM_KERN_HEAP_START + VM_KERN_HEAP_INITIAL_SIZE, 0xCFFFF000, 0, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment