title: Walking page tables of a process in Linux
body: <p>i'm trying to navigate the page tables for a process in linux. In a kernel module i realized the following function:</p>
  
  <pre><code>static struct page *walk_page_table(unsigned long addr)
  {
      pgd_t *pgd;
      pte_t *ptep, pte;
      pud_t *pud;
      pmd_t *pmd;
  
      struct page *page = NULL;
      struct mm_struct *mm = current-&gt;mm;
  
      pgd = pgd_offset(mm, addr);
      if (pgd_none(*pgd) || pgd_bad(*pgd))
          goto out;
      printk(KERN_NOTICE "Valid pgd");
  
      pud = pud_offset(pgd, addr);
      if (pud_none(*pud) || pud_bad(*pud))
          goto out;
      printk(KERN_NOTICE "Valid pud");
  
      pmd = pmd_offset(pud, addr);
      if (pmd_none(*pmd) || pmd_bad(*pmd))
          goto out;
      printk(KERN_NOTICE "Valid pmd");
  
      ptep = pte_offset_map(pmd, addr);
      if (!ptep)
          goto out;
      pte = *ptep;
  
      page = pte_page(pte);
      if (page)
          printk(KERN_INFO "page frame struct is @ %p", page);
  
   out:
      return page;
  }
  </code></pre>
  
  <p>This function is called from the <code>ioctl</code> and <code>addr</code> is a virtual address in process address space:</p>
  
  <pre><code>static int my_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long addr)
  {
     struct page *page = walk_page_table(addr);
     ...
     return 0;
  }
  </code></pre>
  
  <p>The strange thing is that calling <code>ioctl</code> in a user space process, this segfaults...but it seems that the way i'm looking for the page table entry is correct because with <code>dmesg</code> i obtain for example for each <code>ioctl</code> call:</p>
  
  <pre><code>[ 1721.437104] Valid pgd
  [ 1721.437108] Valid pud
  [ 1721.437108] Valid pmd
  [ 1721.437110] page frame struct is @ c17d9b80
  </code></pre>
  
  <p>So why the process can't complete correcly the `ioctl' call? Maybe i have to lock something before navigating the page tables?</p>
  
  <p>I'm working with kernel 2.6.35-22 and three levels page tables.</p>
  
  <p>Thank you all!</p>