# xv6 Lab7 locks - MIT 6.1810 Fall 2025 Operating System

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/xv6-lab7-locks/>). I am continuously working to improve the translation.

## Reading

Just read the book briefly — have GPT translate it and extract the key points, then read the corresponding sections.

Sources of concurrency:

- Multi-core CPUs
- Thread switching
- Interrupts

Reviewing concepts:

- Race conditions
- Critical sections

Reducing lock contention: OSTEP also covers this. Putting one big lock over the entire data structure certainly solves the problem, but it's inefficient.

Source code about locks: `kernel/spinlock.h` `kernel/spinlock.c`

About the spinlock

```c
struct spinlock {
  uint locked; // 0 表示没被持有
  char *name;
  struct cpu *cpu;
};
```

Regarding acquiring locks, RISC-V provides the atomic instruction `amoswap`, which atomically completes read memory - write register to memory - return the old value; this is the implementation of `acquire()`. Releasing the lock follows a similar idea and principle.

The focus of this lab is to optimize `kalloc()` by splitting the lock into finer granularity.

Deadlock must be prevented.

In xv6's implementation, CPU interrupts are disabled whenever any spinlock is held.

`acquire()` internally calls:

```c
push_off();
```

to disable interrupts.

`release()` finally calls:

```c
pop_off();
```

to restore interrupts.

About sleeplock: it was introduced because spinlocks cannot be interrupted.

Using `acquiresleep()` yields the CPU; internally it is protected by a spinlock, and afterwards it can be woken up.

## Memory allocator

Roughly speaking, there is a `kalloctest.c` that performs intense lock contention (repeatedly calling `kalloc() free()`).

The root cause is that `kalloc()` has only one free list, and this free list is protected by a single global lock.

The basic idea for reducing lock contention is to redesign the memory allocator. **Therefore, the task of this lab is to maintain a separate free list for each CPU, and give each list its own lock.**

So this lab must be done on a machine with multiple CPU cores.

One major difficulty is when one CPU's free list is already empty, but another CPU's free list still has free memory. At this point, the CPU lacking memory needs to go to other CPUs' free lists to grab some free pages — this is the so-called **stealing**.

Now let's start implementing:

First, we need to modify `kmem`, which is the original free list struct (a freelist with a lock inside):

Originally:

```c
struct {
  struct spinlock lock;
  struct run *freelist;
} kmem;
```

Modified to a form that supports multiple CPUs:

```c
struct {
  struct spinlock lock[NCPU];
  struct run *freelist[NCPU];
} kmem;
```

Then modify `kinit()` and so on; in short, you need to use the currently running CPU.

Here you first need to know the API for getting the currently running CPU. Hint 3 mentions this, but I still asked an LLM:

> There are only three core APIs: `cpuid()`, `push_off()`, and `pop_off()`.
>
> 1. What does `cpuid()` do
>
> In [kernel/proc.c](/en/home/wendaining/alles/xv6-labs-2025/kernel/proc.c:64):
>
> ```c
> int
> cpuid()
> {
>   int id = r_tp();
>   return id;
> }
> ```
>
> Each CPU has a number, in the range:
>
> ```text
> 0 to NCPU - 1
> ```
>
> `cpuid()` reads this number from RISC-V's `tp` register. So if the current code is running on CPU 3:
>
> ```c
> int id = cpuid();
> ```
>
> the resulting `id` is `3`, and afterwards you can access:
>
> ```c
> kmem.lock[id]
> kmem.freelist[id]
> ```
>
> 2. Why you can't just call `cpuid()` directly
>
> The problem is: a process may be scheduled onto another CPU.
>
> Consider the following situation:
>
> ```c
> int id = cpuid();  // 此时得到 2
> // 这里发生时钟中断和重新调度
> // 进程后来在 CPU 5 上继续运行
> ```
>
> At this point the variable `id` is still `2`, but the code is already running on CPU 5. The "current CPU" no longer matches the saved number.
>
> Therefore, the usage convention for `cpuid()` is: **interrupts must be disabled while reading and using the CPU number.**
>
> The source code comment also states this explicitly:
>
> ```c
> // Must be called with interrupts disabled,
> // to prevent race with process being moved
> // to a different CPU.
> ```
>
> 3. `push_off()` and `pop_off()`
>
> The basic safe form is:
>
> ```c
> push_off();
> int id = cpuid();
> 
> // 在这里使用 id
> 
> pop_off();
> ```
>
> - `push_off()`: disables interrupts on the current CPU.
> - `pop_off()`: restores the interrupt state from before entering this code.
>
> During this period, the code won't be preempted by a timer interrupt, so the current execution flow won't suddenly migrate to another CPU.
>
> It's not recommended to use `intr_off()` and `intr_on()` directly, because they don't handle nesting correctly. For example, the spinlock's `acquire()` itself also calls `push_off()`.
>
> `push_off()`/`pop_off()` track the nesting depth, so the following is legal:
>
> ```c
> push_off();                 // 第 1 层
> int id = cpuid();
> 
> acquire(&kmem.lock[id]);    // acquire 内部进入第 2 层
> // 修改 freelist
> release(&kmem.lock[id]);    // 退出第 2 层
> 
> pop_off();                  // 退出第 1 层
> ```
>
> Until the outermost `pop_off()`, interrupts remain disabled.
>
> 4. Why you can't call `pop_off()` immediately after getting the number
>
> The following approach is not ideal:
>
> ```c
> push_off();
> int id = cpuid();
> pop_off();
> 
> acquire(&kmem.lock[id]);
> ```
>
> Because after `pop_off()`, the code may migrate to another CPU, and then what it operates on is no longer "the current CPU's freelist".
>
> So in `kfree()`, the interrupt-disabled region should cover until the end of the corresponding freelist operation:
>
> ```c
> push_off();
> int id = cpuid();
> 
> acquire(&kmem.lock[id]);
> 
> // 把 r 插入 kmem.freelist[id]
> 
> release(&kmem.lock[id]);
> pop_off();
> ```
>
> This is basically what you need to complete next.
>
> 5. Why `freerange()` gives all pages to one CPU
>
> The boot flow is roughly:
>
> ```text
> boot CPU
>   → kinit()
>     → initialize all kmem locks
>     → freerange()
>       → call kfree() on each physical page
> ```
>
> `freerange()` itself doesn't need to know the CPU number:
>
> ```c
> for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE)
>   kfree(p);
> ```
>
> It's `kfree()` that actually chooses the freelist.
>
> At boot, `kinit()` only runs on the boot CPU, usually CPU 0. Therefore, every `kfree(p)` gets CPU number 0, and the final effect is:
>
> ```text
> kmem.freelist[0]: owns all initial free pages
> kmem.freelist[1]: empty
> kmem.freelist[2]: empty
> ...
> ```
>
> This is what the hint means by:
>
> > Have `freerange()` give all free memory to the CPU currently running `freerange()`.
>
> This doesn't require modifying `freerange()`; rather, it requires `kfree()` to choose the freelist based on the current CPU. Later, when other CPUs allocate memory for the first time, they'll find their freelist empty and then steal pages from CPU 0.
>
> For now, you can just modify `kfree()` and leave `kalloc()` and stealing aside for the moment. The goal of the change is to replace the original:
>
> ```c
> kmem.lock
> kmem.freelist
> ```
>
> with versions indexed by a safely obtained `id`:
>
> ```c
> kmem.lock[id]
> kmem.freelist[id]
> ```

So `kfree()` and `kalloc()` are changed like this:

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

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

  // Fill with junk to catch dangling refs.
  memset(pa, 1, PGSIZE);

  r = (struct run*)pa;
  push_off();
  int id = cpuid();
  acquire(&kmem.lock[id]);
  r->next = kmem.freelist[id];
  kmem.freelist[id] = r;
  release(&kmem.lock[id]);
  pop_off();
}

void *
kalloc(void)
{
  struct run *r;
  push_off();
  int id = cpuid();
  acquire(&kmem.lock[id]);
  r = kmem.freelist;
  if(r)
    kmem.freelist[id] = r->next;
  release(&kmem.lock[id]);
  pop_off();
  if(r)
    memset((char*)r, 5, PGSIZE); // fill with junk
  return (void*)r;
}
```

But this doesn't implement stealing yet.

Modify `kalloc()`:

```c
void *
kalloc(void)
{
  struct run *r;
  push_off();
  int id = cpuid();
  acquire(&kmem.lock[id]);
  r = kmem.freelist[id];
  if(r)
    kmem.freelist[id] = r->next;
  release(&kmem.lock[id]);
  if (r == 0) {
    for (int i = 0; i < NCPU; ++i) {
      // 找到序号最小的有空余页的空闲列表
      if (i == id) {
        continue;
      }
      acquire(&kmem.lock[i]);
      if (kmem.freelist[i]) {
        r = kmem.freelist[i];
        kmem.freelist[i] = r->next;
      }
      release(&kmem.lock[i]);
      if (r) {
        break;
      }
    }
  }
  pop_off();
  if(r)
    memset((char*)r, 5, PGSIZE); // fill with junk
  return (void*)r;
}
```

Then all tests pass.

## Read-write lock

Consider in xv6:

```c
sys_pause()
sys_uptime()
```

Both of these functions read the global variable `ticks`.

But `ticks` is also updated by `clockintr()` at the same time, so both functions acquire `tickslock` before reading `ticks`. But actually only a write lock needs to be held; there's no need at all to set up read-related locks. This lab is about distinguishing readers from writers.

Reviewing the OSTEP content: in the readers-writers problem, the rules are:

- At any given time, there can be at most **one writer**;
- When a writer exists, no reader can exist;
- If there is no writer, **multiple readers** can exist simultaneously.
- To prevent readers from reading forever and starving writers, writer priority is set: once a writer starts trying to acquire the lock, any readers that arrive afterwards must wait until that writer successfully acquires the lock and releases it.

read-write lock API (in `kernel/defs.h`):

```c
void initrwlock(struct rwspinlock*);
void read_acquire(struct rwspinlock*);
void read_release(struct rwspinlock*);
void write_acquire(struct rwspinlock*);
void write_release(struct rwspinlock*);
```

This lab requires completing the stub functions corresponding to the read-write spinlock API in `kernel/spinlock.c`, and modifying the `struct rwspinlock` definition in `kernel/spinlock.h`.

The hints say to read the `sys_rwlktest()` function to understand the test cases; basically it just keeps verifying reads and writes (the four rules above).

From the tests, we can infer that this lock needs to record at least:

- The number of readers
- Whether there is currently an active reader
- The number of currently waiting writers

At the same time, **all state transitions must be atomic**.

```c
// Reader-writer lock.
struct rwspinlock {
  struct spinlock l; // state lock
  int readers;
  int waiting_writers;
  int is_writer_active;
};
```

The hints say:

> If you don't modify anything and run `rwlktest` directly in xv6, the kernel will print:
>
> ```text
> panic: acquire
> ```
>
> The reason is that the original spinlock implementation only allows the lock to be held by one thread at a time.
>
> You need to replace the calls to `acquire()` and `release()` in:
>
> ```text
> write_acquire_inner
> write_release_inner
> read_acquire_inner
> read_release_inner
> ```
>
> with your own lock implementation.

The implementation part:

```c
static void
read_acquire_inner(struct rwspinlock *rwlk)
{
  while (1) {
    acquire(&rwlk->l);
    if (rwlk->is_writer_active == 0 && rwlk->waiting_writers == 0) {
      rwlk->readers++;
      release(&rwlk->l);
      return;
    }
    release(&rwlk->l);
  }
}

static void
read_release_inner(struct rwspinlock *rwlk)
{
  while (1) {
    acquire(&rwlk->l);
    if (rwlk->readers > 0) {
      rwlk->readers--;
      release(&rwlk->l);
      return;
    }
    release(&rwlk->l);
  }
}

static void
write_acquire_inner(struct rwspinlock *rwlk)
{
  // 首先这个肯定不能放到循环里面，其次这个务必要加锁
  acquire(&rwlk->l);
  rwlk->waiting_writers++;
  release(&rwlk->l);
  while (1) {
    acquire(&rwlk->l);
    if (rwlk->readers == 0 && rwlk->is_writer_active == 0) {
      rwlk->waiting_writers--;
      rwlk->is_writer_active = 1;
      release(&rwlk->l);
      return;
    }
    release(&rwlk->l);
  }
}

static void
write_release_inner(struct rwspinlock *rwlk)
{
  while (1) {
    acquire(&rwlk->l);
    if (rwlk->is_writer_active) {
      rwlk->is_writer_active = 0;
      release(&rwlk->l);
      return;
    }
    release(&rwlk->l);
  }
}
```

2 points to note:

1. You must add a loop, because it keeps trying to acquire — remember this is a spinlock
    - At first I read OSTEP's section on implementing read-write locks and didn't see it; only later did I realize they use a semaphore mechanism, and the semaphore mechanism is built on read-write locks underneath. The data structures we implemented are actually somewhat like implementing a semaphore mechanism.
2. In the `write_acquire_inner(*struct* rwspinlock **rwlk*)` function, the addition to the `waiting_writers` variable must definitely be placed outside the loop and at the beginning of the function, because it represents the start of waiting, and the spinning is the waiting process. Also, obviously you need to acquire the lock — I forgot to do that at first, and test8 wouldn't pass.

![All tests passed](https://image.wendaining.top/image-20260818183344272.png)
