Search code examples
memoryx86operating-systemkernelxv6

does kalloc in xv6 return virtual address or physical address?


I am new to stackoverflow and also to this xv6. I was going through the code of xv6 x86 version. I started from main.c Let me tell what idea I have till now.

  1. kinit1 creates some pages which can be used.
  2. We then call kvmalloc from main.c, which is in vm.c
  3. kvmalloc calls setupkvm
  4. In setupkvm we create pgdir (Page directory which contains pointers to other page tables as of my knowledge till now)
  5. Then we go to mappages to start mapping the pagetables
  6. mappages calls walkpgdir which goes throught the pagedirectory and if it finds a virtual to physical mapping it returns the virutal mapping.
  7. At first we don't have anything in the pgdir, because we have just created pgdir and are about to fill it.
  8. We will go through the else block of the code, there we use kalloc and store the address in pgtab, one thing to consider here is there is no concept of virtual memory till now(I have been following from main there is no vm till now) so I am thinking pgtab will be physical memory.
  9. Now if pgtab is physical memory *pde = V2P(pgtab) | PTE_P | PTE_W | PTE_U; why are we using V2P, virtual to physical of pgtab. This is my doubt.

Just in case you need the code for walkpgdir it is here,

static pte_t *
walkpgdir(pde_t *pgdir, const void *va, int alloc)
{
  pde_t *pde;
  pte_t *pgtab;

  pde = &pgdir[PDX(va)];
  if(*pde & PTE_P){
    pgtab = (pte_t*)P2V(PTE_ADDR(*pde));
  } else {
    if(!alloc || (pgtab = (pte_t*)kalloc()) == 0)
      return 0;
    // Make sure all those PTE_P bits are zero.
    memset(pgtab, 0, PGSIZE);
    // The permissions here are overly generous, but they can
    // be further restricted by the permissions in the page table
    // entries, if necessary.
    *pde = V2P(pgtab) | PTE_P | PTE_W | PTE_U;
  }
  return &pgtab[PTX(va)];
}

Hey, forgive me if I made a mistake in explaining stuff, I just told what I understood, I was just changing through various files and told what I understood. Please correct me if I am wrong.


Solution

  • kalloc and kfree allocate or free a physical page. They both return pointers to the virtual address of the page in the kernel’s memory.

    Your confusion comes from the assumption that pgtab is already a physical memory address. While kalloc() does return a page from physical memory, the address returned is mapped in the kernel's virtual address space. So, pgtab is a virtual address that points to physical memory.

    A virtual address typically is translated to a physical address by the MMU when you access data at the address. What the virtual address translates to depends on the memory map specified by the kernel.

    Read about kalloc and kfree here