ENع
→Buffer cache
الدرس 43 · File systems

The buffer cache and writing back

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةAdvanced
عن هذا الدرس

Disks are slow and RAM is fast, so the kernel keeps copies of disk blocks in memory: the buffer cache, which Linux calls the page cache. Follow four lines of C as a read misses and fetches a block from disk, the same read hits in RAM, a write changes only the cached copy and leaves it dirty, and fsync() finally puts it on the disk. Along the way you will see why a crash can lose data that write() said was written, how the kernel's flusher threads write back on their own, and how the cache makes room. FAT and ext4: two on-disk layouts shows where blocks live on the disk; the Linux lessons on the file system and on disks, partitions and mounts show the user's view. Crash consistency and journaling builds on this, with the same write-ahead idea as the Databases lesson on write-ahead logging and recovery.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 43 · تفاعلي
01 / 10

The disk is slow

A file lives on the disk, and disks are slow: OSTEP works out about 13.2 ms for one random 4 KB read on a 7,200 RPM hard disk. Memory (RAM) answers far faster, so the kernel avoids the disk whenever it can.

one random 4 KB read (OSTEP ch. 37)
  disk                 seek + rotation + transfer
  Cheetah 15K.5        about 6 ms
  Barracuda 7,200 RPM  about 13.2 ms

RAM loses everything when the power goes;
the disk keeps it. Speed vs safety starts here.
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. The disk is slow

    A file lives on the disk, and disks are slow: OSTEP works out about 13.2 ms for one random 4 KB read on a 7,200 RPM hard disk. Memory (RAM) answers far faster, so the kernel avoids the disk whenever it can.

    one random 4 KB read (OSTEP ch. 37)
      disk                 seek + rotation + transfer
      Cheetah 15K.5        about 6 ms
      Barracuda 7,200 RPM  about 13.2 ms
    
    RAM loses everything when the power goes;
    the disk keeps it. Speed vs safety starts here.
  2. A cache of disk blocks

    The kernel keeps copies of recently used disk blocks in spare RAM: the buffer cache. Linux calls it the page cache. Every read() and write() on a file goes through it. Here it already holds blocks 3 and 9.

    page cache   block -> copy in RAM
      slot 1     block 3   x
      slot 2     block 9   y
      slot 3     (free)
    
    block 3 was used longest ago.
    Linux: one unified page cache for files and memory.
  3. Line 1: a miss

    Line 1 reads one byte of notes.txt. Its block, block 7, is not in the cache: a miss. The kernel reads the whole 4 KB block from disk into the cache while the program waits, then copies the byte, A, into buf.

    line 1   n = pread(fd, buf, 1, 0);
    cache    block 7?  no  -> miss
    disk     read block 7 (all 4 KB) into a free slot
    copy     1 byte to buf: A
    returns  n = 1   (bytes read)
    disk reads so far: 1
  4. Line 2: a hit

    Line 2 asks for the same byte again. Block 7 is in the cache now: a hit. The kernel copies A straight from RAM into buf. The disk does nothing at all, so the call returns much sooner.

    line 2   n = pread(fd, buf, 1, 0);
    cache    block 7?  yes -> hit
    copy     1 byte to buf: A
    returns  n = 1
    disk reads so far: still 1
  5. Line 3: write to RAM only

    Line 3 writes B over that byte. The kernel changes only the copy in the cache and marks the page dirty: newer than the disk. pwrite() returns 1 straight away. The disk still says A.

    line 3   n = pwrite(fd, "B", 1, 0);
    cache    block 7: A -> B, marked dirty
    returns  n = 1   (bytes written)
    disk     block 7: still A
    
    write(2): "A successful return from write() does not
    make any guarantee that data has been committed to disk."
  6. What if the power fails?

    Suppose the power failed right now. RAM forgets everything without power, so the dirty page would vanish. After a restart the disk would still say A: the write is lost, even though pwrite() said it worked.

    what if: power fails now
    cache    gone (RAM needs power)
    disk     block 7: A
    lost     the B that pwrite() accepted
    
    (only imagined: the program carries on)
  7. Writing back, later

    Left alone, the change is still saved later. By default, Linux's flusher threads wake every 5 seconds and write out pages that have been dirty for over 30 seconds. This is write-back: fast now, on disk later.

    Linux defaults (mm/page-writeback.c)
      dirty_writeback_centisecs  500    wake every 5 s
      dirty_expire_centisecs     3000   dirty > 30 s: write
      dirty_background_ratio     10     % of memory dirty:
                                        start writing now
    OSTEP: most file systems buffer writes 5 to 30 s.
  8. Line 4: fsync, now

    Line 4 does not wait. fsync() tells the kernel to write this file's dirty pages to disk now. The kernel sends block 7, waits until the device reports it done, clears the dirty mark, then returns 0.

    line 4   r = fsync(fd);
    write    block 7 -> disk, wait for the device
    disk     block 7: B
    cache    clean again (dirty mark cleared)
    returns  r = 0   (success)
    
    the whole program (C99, POSIX):
    
    #define _POSIX_C_SOURCE 200809L
    #include <fcntl.h>
    #include <stdio.h>
    #include <unistd.h>
    
    int main(void) {
        char buf[1];
        ssize_t n;
        int r;
        int fd = open("notes.txt", O_RDWR);   /* holds one byte: A */
        if (fd < 0) return 1;
        n = pread(fd, buf, 1, 0);
        n = pread(fd, buf, 1, 0);
        n = pwrite(fd, "B", 1, 0);
        r = fsync(fd);
        printf("%c %d %d\n", buf[0], (int)n, r);
        n = pread(fd, buf, 1, 0);
        printf("%c\n", buf[0]);
        return close(fd);
    }
    
    prints:
    A 1 0
    B
  9. Making room

    RAM is limited, so when the kernel needs room it drops a page that was used long ago. Block 3, least recently used and clean, is simply dropped: the disk has the same bytes. A dirty page would be written back first.

    least recently used first:
      block 3   (cached before the program ran)
      block 9
      block 7   (used by lines 1 to 4)
    
    evict block 3: clean -> just drop it
    a dirty victim -> write it to disk, then drop it
  10. Speed or safety

    That is the trade-off. Write-back makes writes fast but can lose the last seconds of work in a crash. Programs that must not lose data, such as databases, call fsync() at the moments that matter.

    write-back   fast writes, a crash can lose the last seconds
    fsync()      safe, but waits for the disk
    
    the cache as a Python simulation:
    
    disk = {3: "x", 7: "A", 9: "y"}   # block -> bytes
    cache = {}                        # block -> [bytes, dirty]
    lru = []                          # least recently used first
    reads = 0
    
    def get(b):
        global reads
        if b in cache:
            lru.remove(b)             # hit
        else:
            reads += 1                # miss: one slow disk read
            cache[b] = [disk[b], False]
        lru.append(b)
        return cache[b]
    
    def write(b, v):
        page = get(b)
        page[0], page[1] = v, True    # RAM only: dirty
    
    def fsync():
        for b, page in cache.items():
            if page[1]:
                disk[b], page[1] = page[0], False
    
    def evict():
        b = lru.pop(0)
        if cache[b][1]:
            disk[b] = cache[b][0]     # dirty: write back first
        del cache[b]
        return b
    
    get(3); get(9); reads = 0       # warm cache
    print(get(7)[0], get(7)[0], "disk reads:", reads)
    write(7, "B")
    print("cache", cache[7][0], "disk", disk[7])
    fsync()
    print("after fsync disk", disk[7])
    print("evicted block", evict())
    
    prints:
    A A disk reads: 1
    cache B disk A
    after fsync disk B
    evicted block 3

اختبار يتاح بعد الخطوة الأخيرة.