发布于 

MIT 6.828 HW4 lazy page allocation

Notes of MIT 6.828 HW4

Add lazy page allcation feature to delay allocation of each page of memory until the application tries to use that page.

Part One: Eliminate allocation from sbrk()

Just increment the process’s size (myproc()->sz) by n and return the old size, no allocation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int
sys_sbrk(void)
{
int addr;
int n;
int newsz;

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

Part Two: Lazy allocation

Modify trap.c to handle the page fault by mapping a newly-allocated page of physical memory at the faulting address, and then returning back to user space to let the process continue executing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int mappages(pde_t *pgdir, void *va, uint size, uint pa, int perm);

void
trap(struct trapframe *tf)
{
/* ... */
switch(tf->trapno){
/* ... */
//PAGEBREAK: 13
default:
/* ... */
if(tf->trapno == T_PGFLT) {
uint vaddr = PGROUNDDOWN(rcr2());
char *mem = kalloc();

if (mem == 0)
goto lazy_alloc_fail;
memset(mem, 0, PGSIZE);

if(mappages(myproc()->pgdir, (char*)vaddr, PGSIZE, V2P(mem), PTE_W|PTE_U) < 0) {
kfree(mem);
goto lazy_alloc_fail;
}

return;
}
lazy_alloc_fail:
// In user space, assume process misbehaved.
cprintf("pid %d %s: trap %d err %d on cpu %d "
"eip 0x%x addr 0x%x--kill proc\n",
myproc()->pid, myproc()->name, tf->trapno,
tf->err, cpuid(), tf->eip, rcr2());
myproc()->killed = 1;
}
}