ENع
→Memory-mapped files
الدرس 44 · File systems

Memory-mapped files

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

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

read() copies a file's bytes out of the kernel's page cache into your buffer. mmap() skips that copy: it gives the file a range of addresses, and loads and stores on those addresses reach the cached pages themselves. Follow five lines of C as mmap() sets up a mapping that reads nothing, the first load raises a page fault, the kernel pages one 4096-byte page in from disk, a store dirties it, and msync() writes it back. This builds on the lesson The buffer cache and writing back, and on page tables and page faults from the memory module.

ستتعلّم

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

شكل 44 · تفاعلي
01 / 11

A file as memory

mmap() asks the kernel to make a file look like part of the program's memory. The program then reads and writes the file with plain loads and stores, as if it were an array. notes.txt holds 8192 bytes: two pages of 4096.

file      notes.txt   8192 bytes = 2 pages of 4096
page 0    bytes 0 .. 4095
page 1    bytes 4096 .. 8191   (byte 5000 is 'a')

the whole program (C99 + POSIX):

#define _POSIX_C_SOURCE 200809L
#include <fcntl.h>
#include <stdio.h>
#include <sys/mman.h>
#include <unistd.h>

#define RW (PROT_READ | PROT_WRITE)

int main(void) {
    int fd = open("notes.txt", O_RDWR);   /* 8192 bytes */
    char *p, c;
    if (fd < 0) return 1;
    p = mmap(NULL, 8192, RW,
        MAP_SHARED, fd, 0);
    if (p == MAP_FAILED) return 1;
    c = p[5000];
    p[5000] = 'Z';
    msync(p, 8192, MS_SYNC);
    printf("%c\n", c);
    munmap(p, 8192);
    close(fd);
    return 0;
}
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. A file as memory

    mmap() asks the kernel to make a file look like part of the program's memory. The program then reads and writes the file with plain loads and stores, as if it were an array. notes.txt holds 8192 bytes: two pages of 4096.

    file      notes.txt   8192 bytes = 2 pages of 4096
    page 0    bytes 0 .. 4095
    page 1    bytes 4096 .. 8191   (byte 5000 is 'a')
    
    the whole program (C99 + POSIX):
    
    #define _POSIX_C_SOURCE 200809L
    #include <fcntl.h>
    #include <stdio.h>
    #include <sys/mman.h>
    #include <unistd.h>
    
    #define RW (PROT_READ | PROT_WRITE)
    
    int main(void) {
        int fd = open("notes.txt", O_RDWR);   /* 8192 bytes */
        char *p, c;
        if (fd < 0) return 1;
        p = mmap(NULL, 8192, RW,
            MAP_SHARED, fd, 0);
        if (p == MAP_FAILED) return 1;
        c = p[5000];
        p[5000] = 'Z';
        msync(p, 8192, MS_SYNC);
        printf("%c\n", c);
        munmap(p, 8192);
        close(fd);
        return 0;
    }
  2. mmap maps, but reads nothing

    The system call mmap() asks the kernel for a range of addresses, p to p + 8191, backed by the file. The kernel records this but reads nothing yet: both page-table entries say not present. It returns the start address p.

    lines 1-2  p = mmap(NULL, 8192, RW,
               MAP_SHARED, fd, 0);
    RW          PROT_READ | PROT_WRITE   may load and store
    MAP_SHARED  stores reach the file, other processes see them
    fd, 0       the open file, starting at offset 0
                (the offset must be a multiple of the page size)
    
    page table  page 0  not present
                page 1  not present
    disk reads  0
  3. Line 3: no page yet

    c = p[5000] is a plain load, not a system call. Byte 5000 sits on page 1 (5000 ÷ 4096 = 1, remainder 904). The CPU's MMU, the part that translates addresses, looks up page 1 in the page table and finds it not present.

    line 3     c = p[5000];
    address    p + 5000
    page       5000 // 4096 = 1
    offset     5000 %  4096 = 904
    MMU        page table entry 1: present bit = 0
               the load cannot finish
  4. A page fault enters the kernel

    The MMU raises a page fault, a trap into the kernel. The kernel checks the address: it lies inside the mapping of notes.txt, so this is not a bug. The kernel must bring in page 1 of the file.

    page fault  trap: user mode -> kernel mode
    address     p + 5000
    kernel      inside a mapping?   yes: notes.txt, offset 5000
                file page           5000 // 4096 = 1
                outside any mapping would mean SIGSEGV
  5. The kernel reads page 1

    Page 1 is not in the page cache yet. The kernel takes a free frame of RAM, frame 7, and reads those 4096 bytes from disk into it. Only page 1 is needed now; in this simple model page 0 stays on disk.

    page cache  page 1 of notes.txt?   no
    free frame  7
    disk I/O    read 4096 bytes: file bytes 4096 .. 8191
    frame 7     now holds page 1   (clean)
    page 0      not needed now; this model leaves it on disk
    
    (had the page already been cached, say by an
     earlier read(), no disk I/O would be needed)
  6. Page 1 maps to frame 7

    The kernel fills in entry 1 of the page table: page 1 is present, in frame 7. Then it returns from the fault, and the CPU runs the same load instruction again.

    page table  page 0  not present
                page 1  present, frame 7
    return      kernel mode -> user mode
    retry       the same instruction:  c = p[5000]
  7. The load reads the cache

    This time the MMU turns p + 5000 into frame 7, byte 904, and the load reads 'a' straight from the page cache. Nothing was copied for the program: its addresses lead to the kernel's own copy of the file.

    MMU      page 1 -> frame 7
    address  frame 7, byte 904
    c        'a'
    copies   0   (the program reads the cached page)
    faults   1   (only the first touch of page 1)
  8. Line 4: a store

    p[5000] = 'Z' needs no system call and no disk read: page 1 is present. The CPU writes Z into frame 7. The page is now dirty, changed in RAM but not yet on disk. Other processes mapping the file see Z at once.

    line 4   p[5000] = 'Z';
    MMU      page 1 -> frame 7   (present, writable)
    frame 7  byte 904: 'a' -> 'Z'
    dirty    page 1: yes
    disk     still 'a'
    
    MAP_SHARED: every process mapping notes.txt shares
    this page; with MAP_PRIVATE the store would go to
    a private copy instead (copy-on-write).
  9. Line 5: msync writes back

    msync() with MS_SYNC asks the kernel to write the mapping's dirty pages back to the file, and waits until that is done. Page 1 goes to disk and is clean again. Without msync, the kernel still writes it back later, on its own schedule.

    line 5   msync(p, 8192, MS_SYNC);
    kernel   dirty pages in p .. p + 8191:  page 1
    disk     write 4096 bytes from frame 7
    MS_SYNC  wait until the write is done
    file     byte 5000 = 'Z'
    dirty    page 1: no
  10. Compare: read() copies

    The usual read(fd, buf, 4096) works differently. The kernel copies the page out of the page cache into the program's own buffer. The same bytes now sit in RAM twice, and the CPU spent time copying them.

    /* the same byte with read() instead of mmap() */
    char buf[4096];
    lseek(fd, 4096, SEEK_SET);
    read(fd, buf, 4096);      /* page 1 */
    c = buf[904];
    
    page cache  frame 7  (kernel's copy)
    buf         a second copy, 4096 bytes copied
  11. Why map a file?

    Mapping skips the copy, reads pages only when they are needed, and lets many processes share one cached copy. The price: each first touch costs a page fault, and touching a mapped page past the end of the file raises a SIGBUS signal.

    the mechanism as a Python simulation:
    
    PAGE = 4096
    disk = {0: "...", 1: "a"}      # byte 5000 of each page of notes.txt
    cache = {}                     # page cache: file page -> frame
    frames = {}                    # frame of RAM -> its contents
    table = {}                     # the page table of this mapping
    dirty = set()
    free = [7]
    
    def mmap(npages):              # records the mapping, reads nothing
        for page in range(npages):
            table[page] = None     # not present
    
    def access(addr, value=None):  # what the MMU and kernel do
        page = addr // PAGE
        if table[page] is None:    # page fault
            print("page fault on page", page)
            if page not in cache:  # read it from disk
                cache[page] = free.pop()
                frames[cache[page]] = disk[page]
            table[page] = cache[page]
        frame = table[page]
        if value is None:
            return frames[frame]   # load: no copy
        frames[frame] = value      # store: page is dirty
        dirty.add(page)
    
    def msync():
        for page in sorted(dirty):
            disk[page] = frames[table[page]]
        dirty.clear()
    
    mmap(2)
    c = access(5000)               # line 3
    access(5000, "Z")              # line 4
    msync()                        # line 5
    print(c, disk[1], table)
    
    prints:
    page fault on page 1
    a Z {0: None, 1: 7}

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