Memory-mapped files
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
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.
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;
}اقرأ الدرس خطوة بخطوة
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; }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 0Line 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 finishA 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 SIGSEGVThe 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)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]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)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).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: noCompare: 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 copiedWhy 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}
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01A program maps an 8192-byte file with mmap() and has not touched it yet. How much of the file has the kernel read from disk?
mmap() only records the mapping and fills the page table with not-present entries. Pages are read on demand, when a load or store first touches them and causes a page fault.
02With 4096-byte pages, which page of the mapping holds byte 5000, and at what offset?
5000 // 4096 = 1 and 5000 % 4096 = 904. The MMU uses the page number to find the page-table entry and keeps the offset inside the frame.
03The first load from page 1 finds its page-table entry not present. What happens next?
The address is inside a valid mapping, so the fault is expected. The kernel finds or reads the page, fills in the page-table entry, returns from the fault and the CPU runs the same load again, which now succeeds.
04After p[5000] = 'Z' on a MAP_SHARED mapping, where is the Z?
The store writes into the shared page-cache frame, so other processes mapping the file see it at once. The page is dirty until it is written back: msync() with MS_SYNC forces that and waits; otherwise the kernel does it on its own schedule.
05What does read(fd, buf, 4096) do that a mapped load does not?
read() leaves a second copy of the bytes in the program's buffer, and the CPU spends time making it. A mapped load reads the cached page directly, at the price of a page fault on each first touch.
المسرد
- mmap()
- A system call that maps a file (or plain memory) into a range of a process's addresses, so it can be used with ordinary loads and stores.
- Page
- A fixed-size block of memory, 4096 bytes on x86-64. Mappings, page tables and the page cache all work in whole pages.
- Page table
- The table the MMU uses to turn a program's addresses into physical frames. Each entry says whether a page is present and, if so, which frame holds it.
- MMU
- The memory management unit, the part of the CPU that translates every address through the page table and raises a page fault when it cannot.
- Page fault
- The trap into the kernel that happens when an access finds its page not present (or not allowed). For a mapped file, the kernel brings the page in and retries the access.
- Page cache
- The kernel's copies of file pages in RAM. Both read() and write() and mapped files use the same cached pages on Linux.
- Dirty page
- A cached page that has been changed in RAM but not yet written back to disk.
- msync()
- A system call that writes the dirty pages of a mapping back to the file. With MS_SYNC it waits until the write is done.
الملاحظات والمصادر
- The card shows the five lines of main() that use the mapping. The whole program opens notes.txt, defines RW as PROT_READ | PROT_WRITE, checks for MAP_FAILED, prints the old byte and unmaps the file. It is real C99 with POSIX calls.
- 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.
- 4096-byte pages are the standard on x86-64. Other machines may use other sizes, and a program can ask with sysconf(_SC_PAGESIZE). The mapping still works page by page.
- The lesson shows the dirty flag as a lamp on the page. The page cache tracks which pages are dirty (changed) and which are clean, and writes the dirty ones back; many CPUs also set a dirty bit in the page-table entry on a store.
- On Linux there is one page cache for both paths: pages brought in by read() and write() and pages of mapped files are the same cached pages. That is why a file mapped by one process and read by another stays consistent.
- 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.
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 21: Beyond Physical Memory: Mechanisms
- R. and A. Arpaci-Dusseau, Operating Systems: Three Easy Pieces, ch. 23: Complete Virtual Memory Systems (page cache, memory mapping)
- Linux man-pages: mmap(2)
- Linux man-pages: msync(2)
- MIT 6.1810 (2024), Lab: mmap
- Berkeley CS162, Lecture 16: demand paging (mmap to access a file as RAM)
- Linux kernel documentation: Concepts overview (memory management)
- Linux man-pages: madvise(2) (MADV_RANDOM and read ahead)
اختبار يتاح بعد الخطوة الأخيرة.