deallocxv6

what does deallocation function in xv6's allocation function


in case 1 and 2, what does the deallocation function do in an allocation function?

case 1: if(mem == 0) 

// does this condition mean physical memory has not space? 

case 2:  if(mappages(pgdir, (char*)a, PGSIZE, V2P(mem), PTE_W|PTE_U) < 0)

// does this condtion mean pagetable entry has not allocate in physical memory?

I attached the deallocation function and the allocation function.

reference: https://github.com/fernandabonetti/xv6/blob/master/vm.c

  int
     allocuvm(pde_t *pgdir, uint oldsz, uint newsz)
    {
      char *mem;
      uint a;

      if(newsz >= KERNBASE)
        return 0;
      if(newsz < oldsz)
        return oldsz;


       a = PGROUNDUP(oldsz);
       for(; a < newsz; a += PGSIZE){
        mem = kalloc();
        if(mem == 0){
      cprintf("allocuvm out of memory\n");
          deallocuvm(pgdir, newsz, oldsz);
      return 0;
    }
    memset(mem, 0, PGSIZE);
    if(mappages(pgdir, (char*)a, PGSIZE, V2P(mem), PTE_W|PTE_U) < 0){
      cprintf("allocuvm out of memory (2)\n");
      deallocuvm(pgdir, newsz, oldsz);
      kfree(mem);
      return 0;
    }
  }
  return newsz;
}


int
deallocuvm(pde_t *pgdir, uint oldsz, uint newsz)
{
  pte_t *pte;
  uint a, pa;

  if(newsz >= oldsz)
    return oldsz;

  a = PGROUNDUP(newsz);
  for(; a  < oldsz; a += PGSIZE){
    pte = walkpgdir(pgdir, (char*)a, 0);
    if(!pte)
      a = PGADDR(PDX(a) + 1, 0, 0) - PGSIZE;
    else if((*pte & PTE_P) != 0){
      pa = PTE_ADDR(*pte);
      if(pa == 0)
        panic("kfree");
      char *v = P2V(pa);
      kfree(v);
      *pte = 0;
    }
  }
  return newsz;
}

Solution

  • allocuvm is a short of Allocate User Virtual Memory. This function is responsible to increase the user's virtual memory in a specific page directory. There are indeed 2 cases where this function can fail:

    Case 1: kalloc function failed. kalloc is a short of kernel allocation. This function is responsible to return an address of a new, currently unused, page in RAM. If it returns 0, that means there are no available unused pages currently.

    Case 2: mappages function failed. This function is responsible of making the new allocated page to be accessible by the process who uses the given page directory by mapping that page with the next virtual address available in the page directory. If this function fails that means it failed in doing so, probably due to the page directory being already full.

    In both cases, allocuvm didn't managed to increase the user's memory to the size requested, Therefore, it is undoing all allocations until the point of failure, so the virtual memory will remain unchanged, and returns an error it self.