Finding the PDE offset and the PTE offset from a virtual add

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
0xBADC0DE

Finding the PDE offset and the PTE offset from a virtual add

Post by 0xBADC0DE »

How do you find the PDE offset and PTE offset from a virtual address?
paulbarker

Re:Finding the PDE offset and the PTE offset from a virtual

Post by paulbarker »

PDE_OFFSET = (addr / PAGE_SIZE / PAGES_PER_PDE) * sizeof(PDE_ENTRY)
PTE_OFFSET = (addr / PAGE_SIZE % PAGES_PER_PDE) * sizeof(PTE_ENTRY)

PAGE_SIZE = 4096
PAGES_PER_PDE = 1024
I think the size of each entry is 4 bytes but I'm not sure of that.

Disclaimer: This is off the top of my head and not checked against documentation.
Candamir

Re:Finding the PDE offset and the PTE offset from a virtual

Post by Candamir »

Wouldn't it be like this?

Code: Select all

/** Gets the page directory entry for a given virtual address.
 */

unsigned long get_pde(unsigned long *va)
{
   unsigned long first_ten       = ((unsigned long)va) >> 22; // Top ten bits tell index of pde
   return page_directory[first_ten]; // Use global pointer to page directory
}

/** Gets the page table entry for a given virtual address.
 */

unsigned long get_pte(unsigned long *va)
{
   unsigned long pde             = get_pde(va);
   unsigned long *pde_address    = (unsigned long *)(pde & 0xFFFFF000); // Clear all flags in bits 0-11 to obtain addr
   
   unsigned long next_ten        = (((unsigned long)va) >> 12) & 0x3FF; // Next ten bits tell index of pte in table
   return pde_address[next_ten];
}
The code is heavily based on the fact that all PDEs start addresses are 4MB-aligned and thus only rely on the last ten bits of the address, and the PTEs are always 4KB-aligned and so we use the next/previous (depends on how you look at it) 10 bits.
paulbarker

Re:Finding the PDE offset and the PTE offset from a virtual

Post by paulbarker »

I'm pretty sure thats equivalent to my code. The point of mine was to explain how its done without doing it for him :).
Candamir

Re:Finding the PDE offset and the PTE offset from a virtual

Post by Candamir »

Oops ;D Forgot about the MT-philosophy for a moment ;)
Post Reply