Search code examples
memorysystem-callsxv6

Writing a program to count process memory pages in xv6


I'm trying to write a system call that returns the number of memory pages the current process is using but I have no idea where to start and which variables I should look at. I saw two variables sz and pgdir in proc.h. But I don't know what each of them represents exactly.


Solution

  • Looking at proc.c, you have all you want to understand the memory management:

    // Grow current process's memory by n bytes.
    // Return 0 on success, -1 on failure.
    int
    growproc(int n)
    {
      uint sz;
      struct proc *curproc = myproc();
      sz = curproc->sz;
        if((sz = allocuvm(curproc->pgdir, sz, sz + n)) == 0)
          return -1;
      curproc->sz = sz;
      switchuvm(curproc);
      return 0;
    }
    

    growproc is used to increase the process memory by n bytes. This function is used by the sbrk syscall, itself called by malloc.

    From this, we assert that sz from struct proc { is actually the process memory size.

    Reading allocuvm from vm.c, you can see two macros:

    • PGROUNDUP(size) which transform a memory size to a memory size that is rounded to next page size,
    • PGSIZE which is the page size.

    So, the number of pages actually used by a process is (PGROUNDUP(proc)->sz)/PGSIZE.