kernel/spinlock.h
Included by 20 files
kernel/bio.c, kernel/console.c, kernel/exec.c, kernel/file.c, kernel/fs.c, kernel/kalloc.c, kernel/log.c, kernel/pipe.c, kernel/printk.c, kernel/proc.c, kernel/sleeplock.c, kernel/spinlock.c, kernel/syscall.c, kernel/sysfile.c, kernel/sysproc.c, kernel/trap.c, kernel/uart.c, kernel/virtio_disk.c, kernel/vm.c, user/init.cAbout this file
The definition of xv6’s basic lock, the spinlock. Any kernel data that more than one CPU (or an interrupt handler) can touch is guarded by one of these: the process table entries, the free-page list, the console buffer, the tick counter, and so on.
The struct is tiny: one word that says whether the lock is held, plus two fields that
exist only to help find bugs. All the logic lives in kernel/spinlock.c.
Read next: kernel/spinlock.c, then kernel/sleeplock.h for the lock used for
long waits.
A lock is one word plus debugging information
Only locked is needed for mutual exclusion: 0 means free, 1 means some CPU holds the
lock. acquire changes it with an atomic swap, release with an atomic store.
name and cpu make bugs easier to find. name is a fixed string given to
initlock (such as "proc" or "kmem") that you can inspect in a debugger.
cpu records which CPU holds the lock; holding compares it with the current CPU,
which lets acquire detect a CPU trying to take a lock it already holds, and lets
release detect a CPU releasing a lock it does not hold. Both mistakes cause a
panic instead of a silent deadlock or corruption.
The lock word, a 32-bit uint. Because it is 32 bits, the compiler implements
acquire's atomic swap with amoswap.w, the “word” form (amoswap.w (atomic swap)).
The lock’s name, for debugging. It points at a string constant; it is never copied.
The struct cpu (kernel/proc.h) of the CPU holding the lock, or 0 when the lock
is free. Written only by the holder: acquire sets it after taking the lock and
release clears it before giving the lock up.