Reputation: 53
I was reading about page faulting and from what I read, the MMU consults the page table to translate virtual addresses into physical addresses. It is the responsibility of the OS (via the page fault handler) to fill up these page table entries.
What confuses me is how does the page fault handler obtain the physical addresses in the first place? In the diagrams and notes I saw, the CPU seems to use virtual addresses and the MMU transparently translates them to physical addresses. Does the CPU specially work with physical address rather than virtual addresses for page fault handling?
If there is an access to some 4K page that is not present in memory and the page fault handler successfully locates the corresponding 4K page on disk, how does it acquire a 4K page of physical memory and figure out the physical address of the 4K page of physical memory?
Upvotes: 1
Views: 617
Reputation: 98
The operating system works with virtual address at the fundamental level, but it does have to manage physical addresses as well. In an OSes memory management subsystem, there is a part called the physical memory manager. Basically, at startup, it read a table given to it by the firmware which tells it which memory regions are free. It sets up free list to contain all free pages in this map. When a page fault occurs, it pulls a page off of this list, maps it into the PTE, grabs another page for to create a page table if no page table exists for this address (note that it will keep doing that step depending on how many levels haven't been mapped yet), flushes the TLB for this address, and then it carries on.
Note that most physical memory allocators are much more compex then this, but, fundamentally, that is the algorithm.
Upvotes: 2
Reputation: 5502
Part of the OS`s responsibility is to keep track of a list of physical pages. You can look on OSDev to see how this is done - usually by querying BIOS/UEFI-exposed functions, which give you (usually non-contiguous) lists of free memory.
UEFI in particular exposes GetMemoryMap at boot time to get an array of memory descriptors.
Given a maintained list of available physical pages - when the OS handles a page fault, it has access to the faulting virtual address, and it can decide what to do. If it needs to allocate a new page, then it will consults its list of free pages, and choose an available physical page to map into the virtual address space. On x86 this mapping is done by modifying the page table and loading it into the cr3
register.
Once the page is mapped, it can be written to using virtual addresses.
Upvotes: 3