ENع
←The kernel's page tables
Lesson 31 · Memory management

The kernel's page tables: entry bits, building and switching tables

14 min10 steps5 questionsIntermediate
About this lesson

The MMU translates every address through a page table, but who writes those tables? The kernel. It keeps one table per process in its own memory, fills in each entry (a frame number plus flag bits such as present, writable and user), lets the hardware set the accessed and dirty bits, rewrites entries when a program calls mmap, mprotect or munmap, and points the CPU at another table on every context switch. Follow four lines of C as the kernel builds one entry on a page fault, changes it and tears it down, then switches to another process. The Hardware lesson Virtual memory explains the translation itself and is a good warm-up.

You'll learn to

Tick what you feel confident about. These self-checks do not affect your lesson score.

Fig 31 · Interactive
01 / 10

A table for every process

The kernel keeps one page table for each process, in the kernel's own memory. Entry n says which physical frame holds that process's page n. The CPU's MMU reads the table on every access; only the kernel writes it.

page table   one per process, in kernel memory
             entry n  ->  the frame holding page n

A's table    page 0 -> frame 3   page 1 -> frame 1
             page 2 -> (none)
B's table    page 0 -> frame 0   page 1 -> frame 2
             page 2 -> (none)
free frames  4, 5

MMU (hardware)   reads entries on every access
kernel           writes them
Loading figure…
or ← →
Read the lesson step by step
  1. A table for every process

    The kernel keeps one page table for each process, in the kernel's own memory. Entry n says which physical frame holds that process's page n. The CPU's MMU reads the table on every access; only the kernel writes it.

    page table   one per process, in kernel memory
                 entry n  ->  the frame holding page n
    
    A's table    page 0 -> frame 3   page 1 -> frame 1
                 page 2 -> (none)
    B's table    page 0 -> frame 0   page 1 -> frame 2
                 page 2 -> (none)
    free frames  4, 5
    
    MMU (hardware)   reads entries on every access
    kernel           writes them
  2. Inside one entry

    Zoom into A's page 2. An x86 entry holds a frame number and flag bits: P (present), R/W (writes allowed), U/S (user mode allowed), A (accessed) and D (dirty: written). This one is all zeros: page 2 is not mapped.

    one page-table entry (x86):
      frame   which physical frame holds the page
      P       present: 1 = the frame number is good
      R/W     1 = writes allowed, 0 = read only
      U/S     1 = user mode may use it, 0 = kernel only
      A       accessed: set by the MMU on any use
      D       dirty: set by the MMU on a write
    
    A's page 2 now:  frame -  P 0  R/W 0  U/S 0  A 0  D 0
  3. Line 1: asking for a page

    mmap asks the kernel for one page of fresh memory. The kernel only writes a note in its own records: A may use page 2. It takes no frame yet and leaves the entry at P = 0.

    the whole program (C99, POSIX):
    
    #define _DEFAULT_SOURCE
    #include <stdio.h>
    #include <sys/mman.h>
    #include <unistd.h>
    
    #define RW   (PROT_READ | PROT_WRITE)
    #define ANON (MAP_PRIVATE | MAP_ANONYMOUS)
    
    int main(void) {
        size_t pg = (size_t)sysconf(_SC_PAGESIZE);
        char *p;
        p = mmap(0, pg, RW, ANON, -1, 0);
        if (p == MAP_FAILED) return 1;
        p[0] = 'x';
        mprotect(p, pg, PROT_READ);
        printf("%c\n", p[0]);
        munmap(p, pg);
        return 0;
    }
    
    line 1   p = mmap(0, pg, RW, ANON, -1, 0);
    kernel   notes: page 2 of A is valid, zero-filled
    entry    unchanged: P = 0 (no frame yet)
  4. Line 2: the first write faults

    Line 2 stores x in page 2. The MMU reads the entry, finds P = 0 and traps to the kernel: a page fault. The kernel checks its notes. Page 2 is valid, just not filled in yet.

    line 2   p[0] = 'x';
    MMU      entry for page 2: P = 0  ->  page fault
    trap     user mode -> kernel mode, fault handler
    kernel   is page 2 in one of A's regions?  yes (mmap)
             so: fill it in (otherwise: SIGSEGV)
  5. The kernel builds the entry

    The kernel takes free frame 4 and fills it with zeros. Then it writes the entry: frame 4, P = 1, R/W = 1, U/S = 1. It returns from the trap, and the CPU retries the store.

    free list   [4, 5]  ->  take frame 4  ->  [5]
    frame 4     fill with zeros (MAP_ANONYMOUS reads as 0)
    entry       frame 4  P 1  R/W 1  U/S 1  A 0  D 0
    return      back to user mode, retry line 2
  6. The hardware sets A and D

    This time the MMU finds frame 4, and x lands there. The MMU itself sets A, because the page was used, and D, because it was written. Later the kernel reads these bits to choose which pages to keep.

    retry    page 2 -> frame 4: allowed, x stored
    MMU      sets A = 1 (used) and D = 1 (written)
    entry    frame 4  P 1  R/W 1  U/S 1  A 1  D 1
    
    the hardware sets A and D; only the kernel clears them
  7. Line 3: read only now

    mprotect asks the kernel to make the page read only. The kernel clears R/W and makes the CPU drop any cached copy of the entry. Reads still work; a write would fault, and the kernel would stop the program with SIGSEGV, the segmentation-fault signal.

    line 3   mprotect(p, pg, PROT_READ);
    kernel   entry R/W 1 -> 0
             flush the old copy from the TLB
    entry    frame 4  P 1  R/W 0  U/S 1  A 1  D 1
    printf   reads p[0]: prints x
    p[0]='y' would fault -> SIGSEGV
  8. Line 4: giving it back

    munmap gives the page back. The kernel clears the entry, so P = 0 again, flushes the cached copy and puts frame 4 back on its free list. Touching page 2 now would end the program with SIGSEGV.

    line 4   munmap(p, pg);
    entry    cleared: frame -  P 0  R/W 0  U/S 0  A 0  D 0
    TLB      flushed for that page
    frame 4  back on the free list  ->  [5, 4]
    p[0] now would raise SIGSEGV
  9. Switching tables

    When A's turn ends, the kernel switches to process B. Besides the registers, it writes the address of B's table into the CPU's table register (CR3 on x86-64). Only kernel mode may. Now page 1 means frame 2, not frame 1.

    context switch A -> B (in kernel mode):
      save A's registers, load B's
      CR3 = address of B's table   (RISC-V: satp)
    
    page 1   A: frame 1     B: frame 2
    user mode cannot write CR3: it is privileged
    A's table stays in kernel memory for A's next turn
  10. One table, one private world

    A process can only reach the frames its own table lists, and only the kernel can edit a table or point the CPU at one. Building entries, setting bits and switching tables is how the kernel gives every process its own memory.

    the whole story as a Python simulation:
    
    free = [4, 5]                         # free physical frames
    A = {0: [3, {"P", "US"}], 1: [1, {"P", "RW", "US"}]}
    B = {0: [0, {"P", "US"}], 1: [2, {"P", "RW", "US"}]}
    cr3 = A                               # the table the MMU uses
    
    def mmu(page, write=False):           # hardware: check, then set A / D
        e = cr3.get(page)
        if e is None or "P" not in e[1] or (write and "RW" not in e[1]):
            return "fault"
        e[1] |= {"A", "D"} if write else {"A"}
        return e[0]
    
    print(mmu(2, write=True))             # page 2: no entry yet
    A[2] = [free.pop(0), {"P", "RW", "US"}]   # kernel fills it in
    print(mmu(2, write=True), sorted(A[2][1]))
    A[2][1].discard("RW")                 # mprotect(PROT_READ)
    print(mmu(2), mmu(2, write=True))
    free.append(A.pop(2)[0])              # munmap
    cr3 = B                               # context switch to B
    print(mmu(1), free)
    
    prints:
    fault
    4 ['A', 'D', 'P', 'RW', 'US']
    4 fault
    2 [5, 4]

Quiz Unlocks after the last step.