kernel/buf.h
About this file
Defines struct buf, one slot of the buffer cache: an in-memory copy of one
1024-byte disk block plus the bookkeeping the cache, the disk driver and the
log need.
kernel/bio.c owns the NBUF buffers and hands them out; kernel/virtio_disk.c
fills or drains data and uses disk; kernel/fs.c and kernel/log.c read and
modify data between bread and brelse.
The file includes nothing itself, so any file that includes it must first include
kernel/fs.h (for BSIZE) and kernel/sleeplock.h.
One cached disk block
The fields fall into three groups, each protected differently:
- identity and list position (
dev,blockno,refcnt,prev,next): protected by the cache’s spinlock,bcache.lock.bgetreads and changes them to find or recycle a buffer. - contents (
valid,data): protected by the buffer’s own sleep lock,lock. Only the process that holds it may read or change the block’s bytes. - device ownership (
disk): protected by the disk driver’svdisk_lockwhile a request is in flight.
The struct is about 1.1 KB, almost all of it data.
1 once data holds the block’s contents, 0 when the buffer has just been assigned to
a new block and not yet read. bread reads from the disk only when it is 0.
1 while the disk device is transferring this buffer. virtio_disk_rw sets it and
sleeps until virtio_disk_intr clears it.
Which disk the block belongs to. xv6 has one disk, so it is always ROOTDEV (1).
Which block of that disk this buffer holds. Together with dev it is the key bget
searches for.
The sleep lock that gives one process at a time the right to use this buffer. It is a sleep lock, not a spinlock, because the holder may wait a long time, for example for the disk, and other processes wanting the block should sleep, not spin.
How many references to this buffer exist: processes between bget and brelse,
plus one if the log has pinned it (bpin). The buffer can be recycled for another
block only when this is 0.
Links in the cache’s circular doubly-linked list, which brelse keeps ordered from
most to least recently used.
The block’s 1024 bytes. The disk device reads or writes this array directly (DMA (direct memory access)), using its address as a physical address.