MIT6.828 HW4: lazy page allocation

  当进程需要更多的内存的时候,调用malloc申请更多的堆内存,而系统调用sbrk()完成该工作。sbrk系统调用分配物理内存,并映射到进程的虚拟地址。但是有的进程会一次申请大量的内存,但是又可能根本用不到,比如说sparse array。所以说复杂的内核涉及会将实际的allocation的工作推迟到实际用的时候,发生了page fault了,然后再进行实际的分配。
  第1部分:Eliminate allocation from sbrk()
  对系统调用sbrk的实际实现sys_sbrk进行修改,只将进程的内存空间大小增加n,而不进行实际的分配。代码修改如下

//sysproc.c
int
sys_sbrk(void)
{
  int addr, newsz;
  int n;

  if(argint(0, &n) < 0)
    return -1;
  addr = proc->sz;
  newsz = addr + n;
  if (newsz >= KERNBASE)
      return -1;
  proc->sz = newsz;
  //if(growproc(n) < 0)
  //  return -1;
  return addr;
}

  返回的地址是新分配的地址空间的开头,在此处就是原来地址空间的末尾。我们增加了sz,但却并未实际增加进程大小。
  再次启动xv6,运行echo hi,得到如下错误提示:
  这里写图片描述
  因为在shell中运行echo时,需要调用malloc函数。运行malloc的时候,虽然返回是成功了的,但是当程序试图操作cmd指向的内存区域的时候,发现该内存区域不是当前进程所有的,因为在sys_sbrk中根本没分配。

  第2部分:Lazy allocation
  在trap.c中添加lazy allocation。我们的代码不需要完美到注意到每个细节,当前我们只需要能够执行echo等简单代码即可。  
  提示:

  • Hint: look at the cprintf arguments to see how to find the virtual address that caused the page fault.
  • Hint: steal code from allocuvm() in vm.c, which is what sbrk() calls (via growproc()).
  • Hint: use PGROUNDDOWN(va) to round the faulting virtual address down to a page boundary.
  • Hint: break or return in order to avoid the cprintf and the proc->killed = 1.
  • Hint: you’ll need to call mappages(). In order to do this you’ll need to delete the static in the declaration of mappages() in vm.c, and you’ll need to declare mappages() in trap.c. Add this declaration to trap.c before any call to mappages().
  • Hint: you can check whether a fault is a page fault by checking if tf->trapno is equal to T_PGFLT in trap().

    代码如下:

if (tf->trapno == T_PGFLT) {
      char *mem;
      uint a;

      a = PGROUNDDOWN(rcr2());
      mem = kalloc();
      if (mem == 0) {
          cprintf("kalloc out of memory!\n");
          proc->killed = 1;
          break;
      }
      memset(mem, 0, PGSIZE);
      mappages(proc->pgdir, (char*)a, PGSIZE, v2p(mem), PTE_W|PTE_U);
      break;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值