ENع
→Copy-on-write
الدرس 37 · Memory in practice

Copy-on-write and shared pages

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

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

fork() promises the child its own copy of the parent's memory, yet on Linux it copies none of the program's pages up front. The trick is copy-on-write: the kernel copies the page table, not the pages, and marks the shared pages read-only. Follow one global variable through fork, a refused write, a page fault and a single page copy, and see why reads stay shared for good. The lessons on fork, exec and wait and on the kernel's page tables show the pieces this lesson puts together.

ستتعلّم

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

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

Copying is expensive

fork() must give the child its own copy of the parent's memory. Copying every page at once is slow, and often wasted: many children call exec(), which loads a new program, and throw the copy out. Copy-on-write puts off each copy until someone writes.

the whole program (C99, POSIX):

#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int x = 1;

int main(void) {
    pid_t pid;
    pid = fork();
    if (pid == 0) x = 2;
    else wait(NULL);
    printf("x=%d\n", x);
    return 0;
}

fork()   child gets a copy of the address space
exec()   often called next: replaces it all
COW      copy a page only when it is written
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Copying is expensive

    fork() must give the child its own copy of the parent's memory. Copying every page at once is slow, and often wasted: many children call exec(), which loads a new program, and throw the copy out. Copy-on-write puts off each copy until someone writes.

    the whole program (C99, POSIX):
    
    #define _POSIX_C_SOURCE 200809L
    #include <stdio.h>
    #include <sys/types.h>
    #include <sys/wait.h>
    #include <unistd.h>
    
    int x = 1;
    
    int main(void) {
        pid_t pid;
        pid = fork();
        if (pid == 0) x = 2;
        else wait(NULL);
        printf("x=%d\n", x);
        return 0;
    }
    
    fork()   child gets a copy of the address space
    exec()   often called next: replaces it all
    COW      copy a page only when it is written
  2. Pages, frames and entries

    Each process has a page table. An entry names the frame of physical memory holding a page, and whether writes are allowed. The parent's code page sits in frame 4, read-only (R); its data page, with x = 1, in frame 5, writable (RW).

    parent's page table
      code page  ->  frame 4   R    (the program)
      data page  ->  frame 5   RW   (int x = 1)
    
    a page is 4096 bytes on x86-64
    R  = read only      RW = read and write
    (x86: the W bit of the entry)
  3. fork copies the table

    Line 1 calls fork(). The kernel gives the child a new page table and copies the parent's entries into it, not the pages. Both tables now point at the same two frames. Not one byte of the program's memory was copied.

    line 1   pid = fork();
    kernel   new page table for the child
             entries copied:  code -> 4,  data -> 5
    memory   frames copied:   none
    
    fork(2): "the only penalty that it incurs is the time
    and memory required to duplicate the parent's page
    tables, and to create a unique task structure"
  4. Both made read-only

    Before fork returns, the kernel clears the write bit on the data page in both tables: 5 · RW becomes 5 · R. It also notes that frame 5 now has two users. Either process may read it; neither may write.

    parent   data -> 5   RW  ->  R   (marked copy-on-write)
    child    data -> 5   RW  ->  R   (marked copy-on-write)
    
    users    frame 4: 2     frame 5: 2
    
    the kernel keeps a count per frame, and marks the
    page as copy-on-write (the xv6 lab uses a spare
    RSW bit in the RISC-V page table entry)
  5. Reading costs nothing

    Reads need no help. Both processes read x = 1 straight from frame 5 and run the same code from frame 4. The code page was read-only from the start, so it stays shared for good: two processes, one copy.

    read x    parent -> frame 5 -> 1
              child  -> frame 5 -> 1
    run code  both   -> frame 4
    
    shared read-only for good: program code, and
    libraries mapped into many processes
  6. The child writes x

    The child runs line 2, x = 2. The CPU's memory unit (MMU) looks up the child's entry for the data page: frame 5, read-only. It refuses the store before any byte changes and raises a page fault into the kernel.

    line 2   if (pid == 0) x = 2;     (child: pid == 0)
    MMU      child data page -> frame 5   R
    store    refused: nothing in frame 5 changed
    trap     page fault -> kernel mode
  7. The kernel copies one page

    The kernel sees a copy-on-write page, not a bug. It takes free frame 6, copies all 4096 bytes of frame 5 into it, and points the child's entry at frame 6 with writing allowed: 6 · RW.

    fault    child, data page, write, entry is COW
    frame 5  2 users: still shared, so copy
    copy     frame 5 -> frame 6   (4096 bytes)
    child    data -> 6   RW
    users    frame 5: 1     frame 6: 1
    
    a write to a page that was never writable (code)
    is a real error: the process is killed
    (on Linux, by the signal SIGSEGV)
  8. The store runs again

    The kernel returns from the fault, and the CPU runs the same store again. This time the entry allows it, so frame 6 now holds x = 2. Frame 5 still holds x = 1, and only the parent uses it.

    return   from the page fault, back to user mode
    retry    the same store instruction
    MMU      child data page -> frame 6   RW   ok
    frame 6  x = 2      frame 5  x = 1 (parent only)
  9. Each sees its own x

    The child prints x=2 and exits; the parent, done waiting, prints x=1. Same address, different frames: each process saw only its own writes, exactly as if fork had copied everything.

    child    line 4 -> frame 6 -> prints x=2, exits
    parent   line 3 waits for the child
             line 4 -> frame 5 -> prints x=1
    
    output:
    x=2
    x=1
    
    if the parent writes x later, it faults too; frame 5
    now has one user, so the kernel can just make the
    entry writable again, with no copy
  10. Why copy-on-write wins

    Only pages that are written get copied, one at a time, when it happens. A child that calls exec() at once copies almost nothing. The same trick backs private file mappings, and Linux KSM merges identical pages into one write-protected copy.

    copy-on-write as a Python simulation:
    
    frames = {4: "code", 5: "x=1", 6: None}    # physical memory
    users = {4: 1, 5: 1, 6: 0}                 # tables using each frame
    parent = {"code": [4, "R", False], "data": [5, "RW", False]}
    
    def fork(table):                           # copy entries, not pages
        child = {}
        for page, e in table.items():
            if e[1] == "RW":
                e[1], e[2] = "R", True         # read-only, copy-on-write
            child[page] = list(e)
            users[e[0]] += 1
        return child
    
    def write(table, page, value):
        frame, perm, cow = table[page]
        if perm == "R":                        # page fault
            if not cow:
                raise PermissionError(page)
            if users[frame] > 1:               # still shared: copy it
                new = min(f for f in users if users[f] == 0)
                frames[new] = frames[frame]
                users[frame] -= 1
                users[new] = 1
                frame = new
            table[page] = [frame, "RW", False]
        frames[frame] = value
    
    child = fork(parent)
    write(child, "data", "x=2")                # copies frame 5 to 6
    print(frames, users)
    write(parent, "data", "x=3")               # last user: no copy
    print(frames, users)
    
    prints:
    {4: 'code', 5: 'x=1', 6: 'x=2'} {4: 2, 5: 1, 6: 1}
    {4: 'code', 5: 'x=3', 6: 'x=2'} {4: 2, 5: 1, 6: 1}

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