Page 1 of 1

Memory allocation for page directories and tables in the vmm

Posted: Wed Mar 23, 2022 11:09 am
by prithivimarudhoo
I am having trouble figuring out a way to allocate memory for the page tables and directories in my virtual memory manager.
I'm working my way up from the BareBones tutorial and currently have a reasonably functional Physical Memory Manager.
My bootloader enables paging and set's up the kernel to be higher half (at 0xC0000000). Obviously, when I allocate a block using the physical memory manager and
try to use it, a page fault is thrown, as it should be.

My question is how do I allocate and use memory for the virtual memory manager structures? I can't do the same thing I did for the PhysicalMemoryManager and
attach these VMM structures to the end of the kernel since they will have to be freed and allocated. If I allocate space for the Page Tables and the Page Directories using the
Physical Memory Allocator, I won't be able to use them since any attempt to use them will throw a page fault.

Any help is appreciated. Thank you.

Re: Memory allocation for page directories and tables in the

Posted: Wed Mar 23, 2022 8:56 pm
by Octocontrabass
Your bootloader needs to map the page tables somewhere so your VMM can modify them. That way, when you allocate memory from the PMM, your VMM can assign a virtual address.

Re: Memory allocation for page directories and tables in the

Posted: Wed Mar 23, 2022 9:26 pm
by alexfru
You should probably look up and learn recursive mapping.
It'll let you easily modify page tables to map/unmap things on demand. Your original data structures describing the available RAM (what your bootloader finds from the BIOS or UEFI) should be mapped too, obviously.

You can implement your basic heap that would allocate/deallocate the virtual address space and map/unmap the underlying frames using Flat List. The control information may be directly adjacent to the blocks of allocated/free memory, e.g. (this is the virtual address space view):

[size,other metadata] [allocated/free block 1] [size,other metadata] [allocated/free block 2] ...

You start with one huge free block. Then you subdivide it to allocate and you map pages as needed. When freeing, you coalesce adjacent free blocks and unmap unused pages.

Re: Memory allocation for page directories and tables in the

Posted: Thu Mar 24, 2022 12:43 am
by iansjack
Have a look at this blog post: https://os.phil-opp.com/paging-implementation/ It describes your problem and various solutions. Although the blog is about writing an OS in Rust, the discussion and theory there is equally applicable to C/C++.

If you are writing a 64-bit OS, the approach of creating a mapping of all physical memory to a virtual address range is easiest and most versatile. (Some people see this as a security risk, but I’m not convinced that it’s worse than any other approach.)