ENع
←Huge pages and NUMA
Lesson 38 · Memory in practice

Huge pages and NUMA memory placement

14 min10 steps5 questionsAdvanced
About this lesson

Big programs spend real time just finding their memory. Every access needs a translation, the TLB only remembers a few dozen of them, and each miss walks four levels of page table. Huge pages fix that by mapping 2 MiB at once. On servers with two or more processor sockets there is a second question: which socket's memory holds the page? Follow one 2 MiB buffer as it is filled on 4 KiB pages, then on one huge page, then placed on a NUMA node by first touch, read from the far node, and moved closer. The lessons on the kernel's page tables and on managing the TLB explain the walk and the TLB this lesson builds on, and Copy-on-write and shared pages shows another trick the kernel plays with page mappings.

You'll learn to

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

Fig 38 · Interactive
01 / 10

The TLB remembers translations

Every memory access uses a virtual address that must be translated to a physical one. The CPU keeps recent translations in a small cache, the TLB. A typical TLB holds 32, 64 or 128 entries, and each entry covers one page.

virtual address -> TLB -> physical address

page size   4 KiB (ordinary x86-64 page)
TLB         64 entries (OSTEP: typically 32, 64 or 128)
reach       64 x 4 KiB = 256 KiB

reach (or coverage): how much memory the TLB can
translate without a miss
Loading figure…
or ← →
Read the lesson step by step
  1. The TLB remembers translations

    Every memory access uses a virtual address that must be translated to a physical one. The CPU keeps recent translations in a small cache, the TLB. A typical TLB holds 32, 64 or 128 entries, and each entry covers one page.

    virtual address -> TLB -> physical address
    
    page size   4 KiB (ordinary x86-64 page)
    TLB         64 entries (OSTEP: typically 32, 64 or 128)
    reach       64 x 4 KiB = 256 KiB
    
    reach (or coverage): how much memory the TLB can
    translate without a miss
  2. 2 MiB on 4 KiB pages

    Leave line 1 out for now. Line 2 fills a 2 MiB buffer. On ordinary 4 KiB pages that is 512 pages: 512 page faults and 512 translations. A 64-entry TLB reaches only 256 KiB, so it keeps missing.

    the whole program (C99, POSIX threads):
    
    #define _GNU_SOURCE
    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <sys/mman.h>
    
    #define SZ (2u << 20)   /* 2 MiB: one huge page on x86-64 */
    
    static unsigned char *p;
    static long n;
    
    static long sum(const unsigned char *a, size_t len) {
        long s = 0;
        for (size_t i = 0; i < len; i++) s += a[i];
        return s;
    }
    
    static void *worker(void *arg) {   /* may run on another node */
        (void)arg;
        n = sum(p, SZ);
        return NULL;
    }
    
    int main(void) {
        void *mem;
        pthread_t t;
        if (posix_memalign(&mem, SZ, SZ) != 0) return 1;  /* 2 MiB aligned */
        p = mem;
    #ifdef MADV_HUGEPAGE
        madvise(p, SZ, MADV_HUGEPAGE);
    #endif
        memset(p, 1, SZ);              /* first touch */
        if (pthread_create(&t, NULL, worker, NULL) != 0) return 1;
        pthread_join(t, NULL);
        printf("%ld\n", n);
        free(mem);
        return 0;
    }
    
    line 2   memset(p, 1, SZ);
    buffer   2 MiB / 4 KiB = 512 pages
    faults   512  (one per page, on first touch)
    TLB      64 entries reach 256 KiB: 512 misses per pass
  3. Every miss walks four levels

    On a TLB miss the hardware walks the page table. On x86-64 that is four levels, each indexed by 9 bits of the address, so up to four memory reads before the data itself. 512 misses mean up to 2,048 extra reads.

    48-bit virtual address, 4 KiB page:
      | PGD 9 | PUD 9 | PMD 9 | PTE 9 | offset 12 |
    
    9 bits per level  ->  512 entries per table
    reads per miss  up to 4
    one pass        512 misses x 4 = up to 2048 reads
    (caches of page-table entries can save some of them)
  4. One huge page instead

    Line 1 asks the kernel for huge pages here. Now one entry at the third level, the PMD, points straight at a 2 MiB block of physical memory. The walk stops a level early, and one TLB entry covers the whole buffer.

    line 1   madvise(p, SZ, MADV_HUGEPAGE);
    
    48-bit virtual address, 2 MiB page:
      | PGD 9 | PUD 9 | PMD 9 |      offset 21      |
    
    page     1 x 2 MiB = 512 x 4 KiB
    faults   1        TLB misses per pass   1
    walk     up to 3 reads (no PTE level)
    reach    64 x 2 MiB = 128 MiB
  5. The price of huge pages

    A huge page needs 2 MiB of free physical memory in one aligned piece, which gets hard once memory is fragmented. Touch one byte and you still get 2 MiB, and the kernel must zero all of it. So Linux makes them optional.

    two ways to get huge pages on Linux:
    
    hugetlbfs     a pool reserved ahead (vm.nr_hugepages),
                  used with mmap(MAP_HUGETLB) or hugetlbfs files
    THP           transparent huge pages, no special API:
                  /sys/kernel/mm/transparent_hugepage/enabled
                  always | madvise | never
                  madvise: only regions marked MADV_HUGEPAGE
                  khugepaged later collapses small pages into huge
    
    x86-64 sizes  4 KiB, 2 MiB (PMD), 1 GiB (PUD)
  6. Two sockets, two memories

    Big servers are often NUMA machines: each processor socket has its own memory, and Linux calls each socket with its memory a node. A CPU reaches its own node's memory fastest. The other node's memory is reached over a link between sockets, more slowly.

    NUMA = non-uniform memory access
    
    node 0   CPU 0 + its memory     node 1   CPU 1 + its memory
    local    CPU 0 -> node 0 memory     faster, more bandwidth
    remote   CPU 0 -> link -> node 1    slower
    
    see it on Linux:  numactl --hardware
                      /proc/<pid>/numa_maps
  7. First touch picks the node

    Memory is placed when a page is first touched, not when it is allocated. Line 2 runs on a CPU in node 0, so Linux's default local policy takes the huge page from node 0's memory.

    line 2   memset(p, 1, SZ);
    
    posix_memalign   reserves addresses only
    memset           first write -> page fault
    page fault       kernel picks a physical page now,
                     by the default policy: local allocation
    CPU 0 in node 0  -> the 2 MiB page lives in node 0
  8. Reading from the far node

    Line 3 runs in a worker thread the scheduler put on node 1. Each cache line it reads (the small block a CPU fetches at once) comes over the link from node 0: all 2 MiB is remote and slower.

    line 3   n = sum(p, SZ);      (in the worker thread)
    
    worker on  CPU 1, node 1
    page on    node 0
    reads      2 MiB, all remote: each cache-line fill
               crosses the link from node 0
    
    the TLB entry is fine; the data is just far away
  9. Moving the page closer

    Linux can fix this. Automatic NUMA balancing notices node 1 using the page and migrates it there, or a program asks with move_pages() or mbind(). The huge page is one block, so it moves all at once. Later reads are local.

    automatic   kernel.numa_balancing = 1:
                unmap pages now and then, catch the fault,
                see which node uses them, migrate
    by hand     move_pages(2)   move these pages to node 1
                mbind(2)        a policy for an address range
                numactl --membind=1 ./prog
    
    after       page on node 1, worker on node 1: local
  10. Fewer slow trips

    Huge pages cut TLB misses and page-table walks for big, busy memory. NUMA placement keeps that memory on the node whose CPUs use it. Both serve one goal: fewer slow trips for each useful memory access.

    the two ideas as a Python simulation:
    
    from collections import OrderedDict
    PAGE, HUGE, ENTRIES = 4096, 2 << 20, 64
    
    def misses(page_size, passes=2):     # LRU TLB, one 64-byte line at a time
        tlb, n = OrderedDict(), 0
        for _ in range(passes):
            for addr in range(0, HUGE, 64):
                vpn = addr // page_size
                if vpn in tlb:
                    tlb.move_to_end(vpn)
                    continue
                n += 1
                tlb[vpn] = True
                if len(tlb) > ENTRIES:
                    tlb.popitem(last=False)
        return n
    
    print("4 KiB pages:", misses(PAGE), "TLB misses")
    print("2 MiB page: ", misses(HUGE), "TLB miss")
    
    home = {}                            # page -> node, set on first touch
    for page in range(HUGE // PAGE):
        home.setdefault(page, 0)         # memset runs on node 0
    far = sum(home[pg] != 1 for pg in range(HUGE // PAGE))
    print("pages remote for node 1:", far)
    
    prints:
    4 KiB pages: 1024 TLB misses
    2 MiB page:  1 TLB miss
    pages remote for node 1: 512

Quiz Unlocks after the last step.