KERNELRAMDIRTY01frame 6frame 7notes.txtpage 0…page 1a1p = mmap(NULL, 8192, RW,2 MAP_SHARED, fd, 0);3c = p[5000];4p[5000] = 'Z';5msync(p, 8192, MS_SYNC);CPU·MMUpage 0page 1bufp?7aZ
Back: the kernel, the page cache (RAM) and the diskFront: your program, the CPU and MMU, the page table, a read() bufferTokens: the fault, the page coming in, the loaded and stored bytes, the write-backAt the back: the kernel, the page cache (two frames of RAM and a dirty lamp) and the disk holding notes.txt as two pages. In front: the program's five lines, the CPU with its MMU, the mapping's page table and a read() buffer. mmap only marks both pages not present. The first load faults; the kernel reads page 1 into frame 7, points the page table at it, and the retried load reads 'a' from the cache itself. The store dirties frame 7 and msync writes it back. read() would copy the page into a buffer instead. Each page box shows only byte 5000 of its page, the one the program touches. Page 0 is drawn as … because the program never uses it. Frame 7 is just the free frame this run happens to get.

Mapping a file

  1. 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.

The first touch

Writing and comparing

What happens

;; step 1/11 · idea
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;
}

Each page box shows only byte 5000 of its page, the one the program touches. Page 0 is drawn as … because the program never uses it. Frame 7 is just the free frame this run happens to get. Real kernels read ahead around a fault: Linux reads a window of pages around the faulting page (unless the program calls madvise(MADV_RANDOM)) and may also map nearby cached pages (fault-around). So neighbouring pages, like page 0 here, are often read too. The figure leaves this out. Real CPUs also cache translations in the TLB, so the retried load may first miss in the TLB and then walk the page table. The figure leaves the TLB out.