Page 1 of 1

How does map_page function in the wiki work?

Posted: Fri Mar 25, 2022 6:44 am
by yasar11732
Hi,

I am trying to understand this function in wiki;

Code: Select all

void map_page(void *physaddr, void *virtualaddr, unsigned int flags) {
    // Make sure that both addresses are page-aligned.
 
    unsigned long pdindex = (unsigned long)virtualaddr >> 22;
    unsigned long ptindex = (unsigned long)virtualaddr >> 12 & 0x03FF;
 
    unsigned long *pd = (unsigned long *)0xFFFFF000;
    // Here you need to check whether the PD entry is present.
    // When it is not present, you need to create a new empty PT and
    // adjust the PDE accordingly.
 
    unsigned long *pt = ((unsigned long *)0xFFC00000) + (0x400 * pdindex);
    // Here you need to check whether the PT entry is present.
    // When it is, then there is already a mapping present. What do you do now?
 
    pt[ptindex] = ((unsigned long)physaddr) | (flags & 0xFFF) | 0x01; // Present
 
    // Now you need to flush the entry in the TLB
    // or you might not notice the change.
}
As far as I can tell, Page Directory is mapped to 0xFFFFF000 which is 4 KiB below virtual adress space limit. Page tables are mapped starting from 0xFFC00000 which is 4MB below virtual address space limit. If I am not miscalculating anything here, last page table and page directory is mapped to same place.

If I didn't do any mistake, and it is by design, in order to map page tables, I need to use last page table, which is also the page directory. So it means I need to use whole page directory for mapping page tables (because it is also a page table now :/) so, how can I map anything else now?

My brain stackoverflows while trying to figure this out.

Best Regards,

Re: How does map_page function in the wiki work?

Posted: Fri Mar 25, 2022 12:03 pm
by yasar11732
I must be getting old, this took me a while to get it, but I think I get it.

Here is how I think it works.

In 32 bit non-pae paging, there is 2 level of indirection converting linear adress to physical adress. First, page directory is used to get physical adress of page table, then page table is used find physical adress corresponding to linear adress.

But, if you point page directory to itself, you end up eating one level of indirection, so you end up in physical address of page table instead.

Did I get it right?

Re: How does map_page function in the wiki work?

Posted: Fri Mar 25, 2022 2:47 pm
by nullplan
yasar11732 wrote:But, if you point page directory to itself, you end up eating one level of indirection, so you end up in physical address of page table instead.
That is exactly correct. The trick works for any paging setup on x86, but for 32-bit PAE paging it is questionable whether you want to use it (as it eats one quarter of all available virtual memory), and in 64-bit mode, better alternatives are available.