OS homework1

CH2 Page Table

page-table的技術:

  1. mapping the same memory (the kernel) in several address spaces
  2. mapping the same memory more than once in one address space (each user page is also mapped into the kernel’s physical view of memory)
  3. guarding a user stack with an unmapped page

Paging hardware

Process address space

0201 // Memory layout
0202 #define EXTMEM 0x100000 // Start of extended memory
0203 #define PHYSTOP 0xE000000 // Top physical memory
0204 #define DEVSPACE 0xFE000000 // Other devices are at high addresses
0205
0206 // Key addresses for address space layout (see kmap in vm.c for layout)
0207 #define KERNBASE 0x80000000 // First kernel virtual address
0208 #define KERNLINK (KERNBASE+EXTMEM) // Address where kernel is linked
0209
0210 #define V2P(a) (((uint) (a)) − KERNBASE)
0211 #define P2V(a) (((void *) (a)) + KERNBASE) 
0212
0213 #define V2P_WO(x) ((x) − KERNBASE) // same as V2P, but without casts
0214 #define P2V_WO(x) ((x) + KERNBASE) // same as P2V, but without casts

Code: creating an address space

// Set up kernel part of a page table.
pde_t* setupkvm(void)
{
pde_t *pgdir;
struct kmap
*k;
if((pgdir = return 0;
(pde_t*)kalloc()) == 0)
memset(pgdir, 0, PGSIZE);
if (P2V(PHYSTOP) > (void*)DEVSPACE)
panic("PHYSTOP too high");
for(k = kmap; k < &kmap[NELEM(kmap)]; k++)
if(mappages(pgdir, k−>virt, k−>phys_end − (uint)k−>phys_start, k−>perm)
k−>phys_start, < 0) {
freevm(pgdir);
return 0; }
return pgdir; 
}
// Allocate one page table for the machine for the kernel address 
// space for scheduler processes.
void kvmalloc(void)
{
kpgdir = setupkvm(); switchkvm();
}
1756 // Create PTEs for virtual addresses starting at va that refer to 1757 // physical addresses starting at pa. va and size might not
1758 // be page−aligned.
1759 static int
1760 mappages(pde_t *pgdir, void *va, uint size, uint pa, int perm) 1761 {
1762 char *a, *last;
1763 pte_t *pte;
1764
1765 a = (char*)PGROUNDDOWN((uint)va);
1766 last = (char*)PGROUNDDOWN(((uint)va) + size − 1);
1767 for(;;){
1768 if((pte = walkpgdir(pgdir, a, 1)) == 0)
1769 return1;
1770 if(*pte & PTE_P)
1771 panic("remap");
1772 *pte = pa | perm | PTE_P;
1773 if(a == last)
1774 break;
1775 a += PGSIZE;
1776 pa += PGSIZE;
1777 }
1778 return 0;
1779 }

Physical memory allocation

Code: Physical memory allocator

程式流程

User part of an address space

Code: sbrk

程式流程

Code: exec

程式流程