Skip to content

Instantly share code, notes, and snippets.

@zid
Last active July 11, 2023 15:50
Show Gist options
  • Save zid/3c68a18db30bc8d56699b1e6f10ed23c to your computer and use it in GitHub Desktop.
Save zid/3c68a18db30bc8d56699b1e6f10ed23c to your computer and use it in GitHub Desktop.
#include <assert.h>
#include <stddef.h>
#include <string.h>
#include "bprintf.h"
#include "mmu.h"
#define IDENT_PDS 64
__attribute__((aligned(4096))) static uintptr_t pml4[512];
__attribute__((aligned(4096))) static uintptr_t pdpt[512];
__attribute__((aligned(4096))) static uintptr_t pd_ident[IDENT_PDS * 512];
void
init_mmu(void)
{
asm("cli");
/* Map first 64GiB of physical memory at -512GiB to -448GiB */
pml4[511] = (uintptr_t)&pdpt | PDE_P | PDE_W | PDE_G;
for (size_t i = 0; i < IDENT_PDS; i++)
pdpt[i] = (uintptr_t)&pd_ident[i*512] | PDE_P | PDE_W | PDE_G;
for (size_t i = 0; i < IDENT_PDS * 512; i++)
pd_ident[i] = (i * 0x2000000UL) | PDE_P | PDE_W | PDE_PS | PDE_G;
/* Map the first 1GiB physical to the last 1GiB virtual */
pdpt[511] = (uintptr_t)&pd_ident[0] | PDE_P | PDE_W;
/* EFI environment identity maps the lower half, preserve that here. */
pml4[0] = (uintptr_t)&pdpt | PDE_P | PDE_W | PDE_G;
asm volatile("movq %0, %%cr3" : : "r"(&pml4) : "memory");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment