Reputation: 135
I'm attempting to write my own operating system, and have gotten to the point where I have to consider memory management and paging. This has shown itself to be a bit more challenging than I anticipated. :-D Before I attempt another failed implementation I'd like to have my thoughts about the subject in order.
To my understanding, in order to properly implement paging in C on a 32-bit x86 system I should:
Create a memory manager I...
Find out where the high part of the memory starts by using the "end" tag defined in my linker script. I should get a number which is an address in memory. Everything before this address is the memory needed for the kernel, everything after it is free space.
Use that number to create a pointer variable that I can use to work with that memory address. At the memory address the pointer points to I'll define a doubly linked list. The list will contain numbers (representing memory addresses, and offset every 4K) that can be used to point to every "page" in the system memory, and something telling the system if that page is allocated or free.
When I want the memory manager to allocate a page I'll need to have a function that iterates through the list until it finds a free 4K page, marks it as allocated, and returns the number that can be used as a memory address for that page.
To free a page I have a function that accepts a number representing the memory address of a page, and I go over the list until I find the element with that number, and mark it as free.
To set up paging, I then have to create a page directory (in the first page?), and 1024 page tables containing 1024 pages. I then put the address of the page directory in the Cr3 register, and change a bit in the Cr0 register. At this point I'll also need new functions to allocate and free pages through the page directory.
Is my thinking on all of this correct? If not, what am I failing to understand? What do I need to do to keep the system from trying to access non-existent memory?
Upvotes: 1
Views: 236
Reputation: 46
You will also need to write the page fault exception handler and insert it into the table of interrupts for whatever processor you are using. This handler will perform the search through the page tables when there is a TLB miss. Each process will have its' own set of page tables mapping virtual to physical addresses.
Upvotes: 1