Notes

Do not read codes but patch binary.

xv6 code reading (5.paging)

How CPU works for memory access

When CPU is ordered to access a value on virtual address, it needs to address a specific page. Accessing same virtual address on two different processes must address mutually distinct physical pages.

Given a memory access instruction is supplied on a CPU, it follows these steps below to read or write data.

f:id:vrodxda:20210314224925p:plain

To accomplish this automatically via CPU, kernel needs to tell CPU the mapping when a process starts. Specifically on each step,

Step1 : Page Directory Preparation, CR3 register setup to Page Directory Step2 : Setup for Page Directory Entry Step3 : Setup for Page Table Step4 : Setup for Page Table Entry

are required.

CR3

On xv6, when a new process is created, control register3 (often abbrebiated as CR3) points to head address of page directory. The procedure is done like below.

// vm.c
void
switchuvm(void)
{
  ....
  ltr(SEG_TSS << 3);
  lcr3(V2P(p->pgdir));  // switch to process's address space
  popcli();
}
// x86.h
static inline void
lcr3(uint val)
{
  asm volatile("movl %0,%%cr3" : : "r" (val));
}

Page Directory

A page directory consists of one or multiple page directory entries. Each page directory entry is 32bit in xv6 and consists of pointer to page table and some additional flags. Absolute address to page table entry is not required as page table entry is always allocated per page unit, which means you can omit last 12bit; 22bit is required. space which is left can be compensated by additional flags where its emptiness, user or kernel, rwx about pages which is managed by the pointed page table.

Page directory can be sparse because it needs to be searched by virtual address. High 10bit of virtual address should represent index of page directory entry. If elf program header specifies highest virtual address (e.g. higest bit is 0b1111111111), the last page directory entry on page directory will be used.

Page Table

You also need to prepare a page table required from a page directory entry. Each page table consists of page table entries and each of them manges one page.