← All writing

MIT 6.S081 (2)

Traps and Copy-on-Write

Parts: 1 · 2 · 3 · 4

Lab: traps

There are three kinds of event which cause the CPU to set aside ordinary execution of instructions

and force a transfer of control to special code that handles the event.

  • system call
  • exception: an instruction (user or kernel) does something illegal, such as divide by zero or use an invalid virtual address.
  • device interrupt: a device signals that it needs attention.

This book uses trap as a generic term for these situations.

See xv6 book at chaper four for full description.

RISC-V trap machinery

Here’s an outline of the most important registers:

  • stvec: The kernel writes the address of its trap handler here; the RISC-V jumps to the address in stvec to handle a trap.
  • sepc: When a trap occurs, RISC-V saves the program counter here (since the pc is then overwritten with the value in stvec). The sret (return from trap) instruction copies sepc to the pc. The kernel can write sepc to control where sret goes.
  • scause: RISC-V puts a number here that describes the reason for the trap.
  • sscratch: The trap handler code uses sscratch to help it avoid overwriting user registers before saving them.
  • sstatus: The SIE bit in sstatus controls whether device interrupts are enabled. If the kernel clears SIE, the RISC-V will defer device interrupts until the kernel sets SIE. The SPP bit indicates whether a trap came from user mode or supervisor mode, and controls to what mode sret returns.

When it needs to force a trap, the RISC-V hardware does the following for all trap types:

  1. If the trap is a device interrupt, and the sstatus SIE bit is clear, don’t do any of the following.
  2. Disable interrupts by clearing the SIE bit in sstatus.
  3. Copy the pc to sepc.
  4. Save the current mode (user or supervisor) in the SPP bit in sstatus.
  5. Set scause to reflect the trap’s cause.
  6. Set the mode to supervisor.
  7. Copy stvec to the pc.
  8. Start executing at the new pc.

Note that the CPU doesn’t switch to the kernel page table, doesn’t switch to a stack in the kernel, and doesn’t save any registers other than the pc.

Kernel software must perform these tasks.

function pointer

The function name in C is a pointer to the address of such function.

We can define a function pointer like this.

c
#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int main() {
    // Function name 'add' can be used like a pointer to the function
    // Define a variable that can point to a function taking (int,int) and returning int
    int (*fp)(int, int) = add;   // same as &add

    printf("%p\n", add);   // print the address of the function
    printf("%p\n", &add);  // also works (identical)
    printf("%d\n", fp(2, 3)); // call through pointer
}

CPU clock ticks

The hardware: timer interrupts

On RISC-V, there is a CLINT (Core Local Interruptor) device that maintains:

  • mtime: a continuously incrementing 64-bit counter (in cycles).
  • mtimecmp: a register that, when mtime >= mtimecmp, triggers a timer interrupt.

So, to get regular ticks, xv6 sets mtimecmp = mtime + interval.

xv6 boot

In kernel/start.c, xv6 boots and eventually sets up the timer:

  • Each hart (CPU) calls timerinit() (in kernel/start.c), which programs the timer:

    c
    // ask each hart to generate timer interrupts.
    void
    timerinit()
    {
      // enable supervisor-mode timer interrupts.
      w_mie(r_mie() | MIE_STIE);
      
      // enable the sstc extension (i.e. stimecmp).
      // With Sstc, the supervisor can directly write to the stimecmp
      // register instead of going through machine mode and CLINT.
      w_menvcfg(r_menvcfg() | (1L << 63)); 
      
      // allow supervisor to use stimecmp and time.
      w_mcounteren(r_mcounteren() | 2);
      
      // ask for the very first timer interrupt.
      // when time >= timecmp a interrupt occurs.
      w_stimecmp(r_time() + 1000000);
    }
    

  • then trap.c will handle this and update timecmp for next timer interrupt.

    c
    void
    clockintr()
    {
      // Only CPU 0 is the one responsible for maintaining global time
      // Otherwise, every core would increment ticks, and time would advance too fast.
      // So different CPU can be synchronous with this global time.
      if(cpuid() == 0){
        acquire(&tickslock);
        ticks++;
        wakeup(&ticks);
        release(&tickslock);
      }
    
      // ask for the next timer interrupt. this also clears
      // the interrupt request. 1000000 is about a tenth
      // of a second.
      w_stimecmp(r_time() + 1000000);
    }
    

extern

NOTE: a global variable can be seen in other files, but you need to declare it with extern in other files. Without extern, if you just write int globalVar; in another file, the compiler will think you’re defining a new variable, which can cause linking errors or multiple definitions

c
// File1.c
int globalVar = 42; // definition

c
// File2.c
#include <stdio.h>

extern int globalVar;  // declaration 

int main() {
    printf("%d\n", globalVar); // can access the variable from File1.c
    return 0;
}

sh
gcc file1.c file2.c -o hello.c

Lab: Copy-on-Write Fork for xv6 (hard)

This lab is hard since it is easy to get wrong.

Here I meet FIVE bugs when I complete my code first time.

c
void
kfree(void *pa)
{
  struct run *r;

  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP)
    panic("kfree");

    /********** bug 1: here *************/
  // Fill with junk to catch dangling refs.
  // Shit this bug take me about 2 hours.
  // I forget to handle this and cause
  // clear all pages whoever they are.
 /*  memset(pa, 0, PGSIZE); */

  r = (struct run*)pa;
  int index = MEMINDEX(r);

  acquire(&kmem.lock);
  acquire(&refcountlock);

  if(kmem.refcount != 0)
  {
    /********** bug 3: here *************/
    // NOTE: If refcount is unsigned and = 0.
    // Then kmem.refcount[index]--. It will
    // underflow to 65535.
    kmem.refcount[index]--;
    if(kmem.refcount[index] == 0)
    {
         /********** bug 2: here *************/
        // NOTE!!!!!!!!
        // Order is important here.
        // clear must before r->next = kmem.freelist;
        // Or r->next will be 0;
        memset(pa, 0, PGSIZE);
        r->next = kmem.freelist;
        kmem.freelist = r;
    }
    // printf("kfree address %lx, index %d, refcount %d\n", (uint64)r, index, kmem.refcount[index]);
  }
  else
  {
    memset(pa, 0, PGSIZE);
    r->next = kmem.freelist;
    kmem.freelist = r;
  }
  release(&refcountlock);
  release(&kmem.lock);
}

1.Clear all pages whoever they are

Whne I modify kfree. I forget to move memset(pa, 0, PGSIZE); to proper place.

2.Place memset(pa, 0, PGSIZE); to wrong place

c
//  This it wrong
    r->next = kmem.freelist;
    kmem.freelist = r;
    memset(pa, 0, PGSIZE);

memset must before r->next = kmem.freelist, or r->next will be 0.

This is a really subtle BUG.

3.Unsigned short underflow

If kmem.refcount[index]; is not initialized correctly and do kmem.refcount[index]--;.

It will underflow to 65535 if kmem.refcount[index] == 0.

So I must maintain kmem.refcount carefully for every time.

4.Set every page as PTE_SW

c
int
uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)
{
  pte_t *pte;
  uint64 pa, i;
  uint flags;
//   char *mem;

  for(i = 0; i < sz; i += PGSIZE){
    if((pte = walk(old, i, 0)) == 0)
      panic("uvmcopy: pte should exist");
    if((*pte & PTE_V) == 0)
      panic("uvmcopy: page not present");
    pa = PTE2PA(*pte);
    /*************** bug 4: Here ******************/
    // Clear PTE_W for both parent and child
    // NOTE: We need to identify the page as writable
    // by using a bit (PTE_SW).
    if ((*pte) & PTE_W)
    {
        *pte &= (~PTE_W);
        *pte |= PTE_SW;
        if((*pte) & PTE_W)
            panic("uvmcopy: PTE_W not cleared!");
    }

    flags = PTE_FLAGS(*pte);
    // We share the physical memory.
    // if((mem = kalloc()) == 0)
    //   goto err;
    // memmove(mem, (char*)pa, PGSIZE);

    
    if(mappages(new, i, PGSIZE, pa, flags) != 0){
        //   kfree(mem);
        goto err;
    }
    kincresememrefcount(pa);
  }
  return 0;

 err:
  uvmunmap(new, 0, i / PGSIZE, 1);
  return -1;
}

When orignal page is wriable, I can clear PTE_W and set PTE_SW.

The if ((*pte) & PTE_W) check is necessary.

I noticed this condition when I first code. However I delete it when I see other's code which marks all page as PTE_SW. What a pity!!!

5.Ignore load page fault

c
    /*************** bug 5: Here ******************/
  // BUG FOUND: Load page fault is need handle too.
    else if (r_scause() == 15 || r_scause() == 13) // page fault and load page fault
    {
        // printf("page fault begin....\n");
        uint64 va = r_stval(); // the faulting address.
        // printf("page fault va = 0x%lx\n", va);
        if(pagefaultcheck(p->pagetable, va) == 0)
        {
            printf("pagefaultcheck: failed\n");
            setkilled(p);
        }
        else
        {
		...
		}
	}...

I don't consider r_scause() == 13. And because of that, sbrkfail() test will fail.


← Previous · Next →

← Back to ArchiveBack to top ↑

Comments

No approved comments yet.

Your display name and plain-text comment become public only after owner approval. No account or email is required.