1= Transparent Hugepage Support =
   3== Objective ==
   5Performance critical computing applications dealing with large memory
   6working sets are already running on top of libhugetlbfs and in turn
   7hugetlbfs. Transparent Hugepage Support is an alternative means of
   8using huge pages for the backing of virtual memory with huge pages
   9that supports the automatic promotion and demotion of page sizes and
  10without the shortcomings of hugetlbfs.
  12Currently it only works for anonymous memory mappings and tmpfs/shmem.
  13But in the future it can expand to other filesystems.
  15The reason applications are running faster is because of two
  16factors. The first factor is almost completely irrelevant and it's not
  17of significant interest because it'll also have the downside of
  18requiring larger clear-page copy-page in page faults which is a
  19potentially negative effect. The first factor consists in taking a
  20single page fault for each 2M virtual region touched by userland (so
  21reducing the enter/exit kernel frequency by a 512 times factor). This
  22only matters the first time the memory is accessed for the lifetime of
  23a memory mapping. The second long lasting and much more important
  24factor will affect all subsequent accesses to the memory for the whole
  25runtime of the application. The second factor consist of two
  26components: 1) the TLB miss will run faster (especially with
  27virtualization using nested pagetables but almost always also on bare
  28metal without virtualization) and 2) a single TLB entry will be
  29mapping a much larger amount of virtual memory in turn reducing the
  30number of TLB misses. With virtualization and nested pagetables the
  31TLB can be mapped of larger size only if both KVM and the Linux guest
  32are using hugepages but a significant speedup already happens if only
  33one of the two is using hugepages just because of the fact the TLB
  34miss is going to run faster.
  36== Design ==
  38- "graceful fallback": mm components which don't have transparent hugepage
  39  knowledge fall back to breaking huge pmd mapping into table of ptes and,
  40  if necessary, split a transparent hugepage. Therefore these components
  41  can continue working on the regular pages or regular pte mappings.
  43- if a hugepage allocation fails because of memory fragmentation,
  44  regular pages should be gracefully allocated instead and mixed in
  45  the same vma without any failure or significant delay and without
  46  userland noticing
  48- if some task quits and more hugepages become available (either
  49  immediately in the buddy or through the VM), guest physical memory
  50  backed by regular pages should be relocated on hugepages
  51  automatically (with khugepaged)
  53- it doesn't require memory reservation and in turn it uses hugepages
  54  whenever possible (the only possible reservation here is kernelcore=
  55  to avoid unmovable pages to fragment all the memory but such a tweak
  56  is not specific to transparent hugepage support and it's a generic
  57  feature that applies to all dynamic high order allocations in the
  58  kernel)
  60Transparent Hugepage Support maximizes the usefulness of free memory
  61if compared to the reservation approach of hugetlbfs by allowing all
  62unused memory to be used as cache or other movable (or even unmovable
  63entities). It doesn't require reservation to prevent hugepage
  64allocation failures to be noticeable from userland. It allows paging
  65and all other advanced VM features to be available on the
  66hugepages. It requires no modifications for applications to take
  67advantage of it.
  69Applications however can be further optimized to take advantage of
  70this feature, like for example they've been optimized before to avoid
  71a flood of mmap system calls for every malloc(4k). Optimizing userland
  72is by far not mandatory and khugepaged already can take care of long
  73lived page allocations even for hugepage unaware applications that
  74deals with large amounts of memory.
  76In certain cases when hugepages are enabled system wide, application
  77may end up allocating more memory resources. An application may mmap a
  78large region but only touch 1 byte of it, in that case a 2M page might
  79be allocated instead of a 4k page for no good. This is why it's
  80possible to disable hugepages system-wide and to only have them inside
  81MADV_HUGEPAGE madvise regions.
  83Embedded systems should enable hugepages only inside madvise regions
  84to eliminate any risk of wasting any precious byte of memory and to
  85only run faster.
  87Applications that gets a lot of benefit from hugepages and that don't
  88risk to lose memory by using hugepages, should use
  89madvise(MADV_HUGEPAGE) on their critical mmapped regions.
  91== sysfs ==
  93Transparent Hugepage Support for anonymous memory can be entirely disabled
  94(mostly for debugging purposes) or only enabled inside MADV_HUGEPAGE
  95regions (to avoid the risk of consuming more memory resources) or enabled
  96system wide. This can be achieved with one of:
  98echo always >/sys/kernel/mm/transparent_hugepage/enabled
  99echo madvise >/sys/kernel/mm/transparent_hugepage/enabled
 100echo never >/sys/kernel/mm/transparent_hugepage/enabled
 102It's also possible to limit defrag efforts in the VM to generate
 103anonymous hugepages in case they're not immediately free to madvise
 104regions or to never try to defrag memory and simply fallback to regular
 105pages unless hugepages are immediately available. Clearly if we spend CPU
 106time to defrag memory, we would expect to gain even more by the fact we
 107use hugepages later instead of regular pages. This isn't always
 108guaranteed, but it may be more likely in case the allocation is for a
 109MADV_HUGEPAGE region.
 111echo always >/sys/kernel/mm/transparent_hugepage/defrag
 112echo defer >/sys/kernel/mm/transparent_hugepage/defrag
 113echo madvise >/sys/kernel/mm/transparent_hugepage/defrag
 114echo never >/sys/kernel/mm/transparent_hugepage/defrag
 116"always" means that an application requesting THP will stall on allocation
 117failure and directly reclaim pages and compact memory in an effort to
 118allocate a THP immediately. This may be desirable for virtual machines
 119that benefit heavily from THP use and are willing to delay the VM start
 120to utilise them.
 122"defer" means that an application will wake kswapd in the background
 123to reclaim pages and wake kcompact to compact memory so that THP is
 124available in the near future. It's the responsibility of khugepaged
 125to then install the THP pages later.
 127"madvise" will enter direct reclaim like "always" but only for regions
 128that are have used madvise(MADV_HUGEPAGE). This is the default behaviour.
 130"never" should be self-explanatory.
 132By default kernel tries to use huge zero page on read page fault to
 133anonymous mapping. It's possible to disable huge zero page by writing 0
 134or enable it back by writing 1:
 136echo 0 >/sys/kernel/mm/transparent_hugepage/use_zero_page
 137echo 1 >/sys/kernel/mm/transparent_hugepage/use_zero_page
 139Some userspace (such as a test program, or an optimized memory allocation
 140library) may want to know the size (in bytes) of a transparent hugepage:
 142cat /sys/kernel/mm/transparent_hugepage/hpage_pmd_size
 144khugepaged will be automatically started when
 145transparent_hugepage/enabled is set to "always" or "madvise, and it'll
 146be automatically shutdown if it's set to "never".
 148khugepaged runs usually at low frequency so while one may not want to
 149invoke defrag algorithms synchronously during the page faults, it
 150should be worth invoking defrag at least in khugepaged. However it's
 151also possible to disable defrag in khugepaged by writing 0 or enable
 152defrag in khugepaged by writing 1:
 154echo 0 >/sys/kernel/mm/transparent_hugepage/khugepaged/defrag
 155echo 1 >/sys/kernel/mm/transparent_hugepage/khugepaged/defrag
 157You can also control how many pages khugepaged should scan at each
 162and how many milliseconds to wait in khugepaged between each pass (you
 163can set this to 0 to run khugepaged at 100% utilization of one core):
 167and how many milliseconds to wait in khugepaged if there's an hugepage
 168allocation failure to throttle the next allocation attempt.
 172The khugepaged progress can be seen in the number of pages collapsed:
 176for each pass:
 180max_ptes_none specifies how many extra small pages (that are
 181not already mapped) can be allocated when collapsing a group
 182of small pages into one large page.
 186A higher value leads to use additional memory for programs.
 187A lower value leads to gain less thp performance. Value of
 188max_ptes_none can waste cpu time very little, you can
 189ignore it.
 191max_ptes_swap specifies how many pages can be brought in from
 192swap when collapsing a group of pages into a transparent huge page.
 196A higher value can cause excessive swap IO and waste
 197memory. A lower value can prevent THPs from being
 198collapsed, resulting fewer pages being collapsed into
 199THPs, and lower memory access performance.
 201== Boot parameter ==
 203You can change the sysfs boot time defaults of Transparent Hugepage
 204Support by passing the parameter "transparent_hugepage=always" or
 205"transparent_hugepage=madvise" or "transparent_hugepage=never"
 206(without "") to the kernel command line.
 208== Hugepages in tmpfs/shmem ==
 210You can control hugepage allocation policy in tmpfs with mount option
 211"huge=". It can have following values:
 213  - "always":
 214    Attempt to allocate huge pages every time we need a new page;
 216  - "never":
 217    Do not allocate huge pages;
 219  - "within_size":
 220    Only allocate huge page if it will be fully within i_size.
 221    Also respect fadvise()/madvise() hints;
 223  - "advise:
 224    Only allocate huge pages if requested with fadvise()/madvise();
 226The default policy is "never".
 228"mount -o remount,huge= /mountpoint" works fine after mount: remounting
 229huge=never will not attempt to break up huge pages at all, just stop more
 230from being allocated.
 232There's also sysfs knob to control hugepage allocation policy for internal
 233shmem mount: /sys/kernel/mm/transparent_hugepage/shmem_enabled. The mount
 234is used for SysV SHM, memfds, shared anonymous mmaps (of /dev/zero or
 235MAP_ANONYMOUS), GPU drivers' DRM objects, Ashmem.
 237In addition to policies listed above, shmem_enabled allows two further
 240  - "deny":
 241    For use in emergencies, to force the huge option off from
 242    all mounts;
 243  - "force":
 244    Force the huge option on for all - very useful for testing;
 246== Need of application restart ==
 248The transparent_hugepage/enabled values and tmpfs mount option only affect
 249future behavior. So to make them effective you need to restart any
 250application that could have been using hugepages. This also applies to the
 251regions registered in khugepaged.
 253== Monitoring usage ==
 255The number of anonymous transparent huge pages currently used by the
 256system is available by reading the AnonHugePages field in /proc/meminfo.
 257To identify what applications are using anonymous transparent huge pages,
 258it is necessary to read /proc/PID/smaps and count the AnonHugePages fields
 259for each mapping.
 261The number of file transparent huge pages mapped to userspace is available
 262by reading ShmemPmdMapped and ShmemHugePages fields in /proc/meminfo.
 263To identify what applications are mapping file  transparent huge pages, it
 264is necessary to read /proc/PID/smaps and count the FileHugeMapped fields
 265for each mapping.
 267Note that reading the smaps file is expensive and reading it
 268frequently will incur overhead.
 270There are a number of counters in /proc/vmstat that may be used to
 271monitor how successfully the system is providing huge pages for use.
 273thp_fault_alloc is incremented every time a huge page is successfully
 274        allocated to handle a page fault. This applies to both the
 275        first time a page is faulted and for COW faults.
 277thp_collapse_alloc is incremented by khugepaged when it has found
 278        a range of pages to collapse into one huge page and has
 279        successfully allocated a new huge page to store the data.
 281thp_fault_fallback is incremented if a page fault fails to allocate
 282        a huge page and instead falls back to using small pages.
 284thp_collapse_alloc_failed is incremented if khugepaged found a range
 285        of pages that should be collapsed into one huge page but failed
 286        the allocation.
 288thp_file_alloc is incremented every time a file huge page is successfully
 289i       allocated.
 291thp_file_mapped is incremented every time a file huge page is mapped into
 292        user address space.
 294thp_split_page is incremented every time a huge page is split into base
 295        pages. This can happen for a variety of reasons but a common
 296        reason is that a huge page is old and is being reclaimed.
 297        This action implies splitting all PMD the page mapped with.
 299thp_split_page_failed is is incremented if kernel fails to split huge
 300        page. This can happen if the page was pinned by somebody.
 302thp_deferred_split_page is incremented when a huge page is put onto split
 303        queue. This happens when a huge page is partially unmapped and
 304        splitting it would free up some memory. Pages on split queue are
 305        going to be split under memory pressure.
 307thp_split_pmd is incremented every time a PMD split into table of PTEs.
 308        This can happen, for instance, when application calls mprotect() or
 309        munmap() on part of huge page. It doesn't split huge page, only
 310        page table entry.
 312thp_zero_page_alloc is incremented every time a huge zero page is
 313        successfully allocated. It includes allocations which where
 314        dropped due race with other allocation. Note, it doesn't count
 315        every map of the huge zero page, only its allocation.
 317thp_zero_page_alloc_failed is incremented if kernel fails to allocate
 318        huge zero page and falls back to using small pages.
 320As the system ages, allocating huge pages may be expensive as the
 321system uses memory compaction to copy data around memory to free a
 322huge page for use. There are some counters in /proc/vmstat to help
 323monitor this overhead.
 325compact_stall is incremented every time a process stalls to run
 326        memory compaction so that a huge page is free for use.
 328compact_success is incremented if the system compacted memory and
 329        freed a huge page for use.
 331compact_fail is incremented if the system tries to compact memory
 332        but failed.
 334compact_pages_moved is incremented each time a page is moved. If
 335        this value is increasing rapidly, it implies that the system
 336        is copying a lot of data to satisfy the huge page allocation.
 337        It is possible that the cost of copying exceeds any savings
 338        from reduced TLB misses.
 340compact_pagemigrate_failed is incremented when the underlying mechanism
 341        for moving a page failed.
 343compact_blocks_moved is incremented each time memory compaction examines
 344        a huge page aligned range of pages.
 346It is possible to establish how long the stalls were using the function
 347tracer to record how long was spent in __alloc_pages_nodemask and
 348using the mm_page_alloc tracepoint to identify which allocations were
 349for huge pages.
 351== get_user_pages and follow_page ==
 353get_user_pages and follow_page if run on a hugepage, will return the
 354head or tail pages as usual (exactly as they would do on
 355hugetlbfs). Most gup users will only care about the actual physical
 356address of the page and its temporary pinning to release after the I/O
 357is complete, so they won't ever notice the fact the page is huge. But
 358if any driver is going to mangle over the page structure of the tail
 359page (like for checking page->mapping or other bits that are relevant
 360for the head page and not the tail page), it should be updated to jump
 361to check head page instead. Taking reference on any head/tail page would
 362prevent page from being split by anyone.
 364NOTE: these aren't new constraints to the GUP API, and they match the
 365same constrains that applies to hugetlbfs too, so any driver capable
 366of handling GUP on hugetlbfs will also work fine on transparent
 367hugepage backed mappings.
 369In case you can't handle compound pages if they're returned by
 370follow_page, the FOLL_SPLIT bit can be specified as parameter to
 371follow_page, so that it will split the hugepages before returning
 372them. Migration for example passes FOLL_SPLIT as parameter to
 373follow_page because it's not hugepage aware and in fact it can't work
 374at all on hugetlbfs (but it instead works fine on transparent
 375hugepages thanks to FOLL_SPLIT). migration simply can't deal with
 376hugepages being returned (as it's not only checking the pfn of the
 377page and pinning it during the copy but it pretends to migrate the
 378memory in regular page sizes and with regular pte/pmd mappings).
 380== Optimizing the applications ==
 382To be guaranteed that the kernel will map a 2M page immediately in any
 383memory region, the mmap region has to be hugepage naturally
 384aligned. posix_memalign() can provide that guarantee.
 386== Hugetlbfs ==
 388You can use hugetlbfs on a kernel that has transparent hugepage
 389support enabled just fine as always. No difference can be noted in
 390hugetlbfs other than there will be less overall fragmentation. All
 391usual features belonging to hugetlbfs are preserved and
 392unaffected. libhugetlbfs will also work fine as usual.
 394== Graceful fallback ==
 396Code walking pagetables but unaware about huge pmds can simply call
 397split_huge_pmd(vma, pmd, addr) where the pmd is the one returned by
 398pmd_offset. It's trivial to make the code transparent hugepage aware
 399by just grepping for "pmd_offset" and adding split_huge_pmd where
 400missing after pmd_offset returns the pmd. Thanks to the graceful
 401fallback design, with a one liner change, you can avoid to write
 402hundred if not thousand of lines of complex code to make your code
 403hugepage aware.
 405If you're not walking pagetables but you run into a physical hugepage
 406but you can't handle it natively in your code, you can split it by
 407calling split_huge_page(page). This is what the Linux VM does before
 408it tries to swapout the hugepage for example. split_huge_page() can fail
 409if the page is pinned and you must handle this correctly.
 411Example to make mremap.c transparent hugepage aware with a one liner
 414diff --git a/mm/mremap.c b/mm/mremap.c
 415--- a/mm/mremap.c
 416+++ b/mm/mremap.c
 417@@ -41,6 +41,7 @@ static pmd_t *get_old_pmd(struct mm_stru
 418                return NULL;
 420        pmd = pmd_offset(pud, addr);
 421+       split_huge_pmd(vma, pmd, addr);
 422        if (pmd_none_or_clear_bad(pmd))
 423                return NULL;
 425== Locking in hugepage aware code ==
 427We want as much code as possible hugepage aware, as calling
 428split_huge_page() or split_huge_pmd() has a cost.
 430To make pagetable walks huge pmd aware, all you need to do is to call
 431pmd_trans_huge() on the pmd returned by pmd_offset. You must hold the
 432mmap_sem in read (or write) mode to be sure an huge pmd cannot be
 433created from under you by khugepaged (khugepaged collapse_huge_page
 434takes the mmap_sem in write mode in addition to the anon_vma lock). If
 435pmd_trans_huge returns false, you just fallback in the old code
 436paths. If instead pmd_trans_huge returns true, you have to take the
 437page table lock (pmd_lock()) and re-run pmd_trans_huge. Taking the
 438page table lock will prevent the huge pmd to be converted into a
 439regular pmd from under you (split_huge_pmd can run in parallel to the
 440pagetable walk). If the second pmd_trans_huge returns false, you
 441should just drop the page table lock and fallback to the old code as
 442before. Otherwise you can proceed to process the huge pmd and the
 443hugepage natively. Once finished you can drop the page table lock.
 445== Refcounts and transparent huge pages ==
 447Refcounting on THP is mostly consistent with refcounting on other compound
 450  - get_page()/put_page() and GUP operate in head page's ->_refcount.
 452  - ->_refcount in tail pages is always zero: get_page_unless_zero() never
 453    succeed on tail pages.
 455  - map/unmap of the pages with PTE entry increment/decrement ->_mapcount
 456    on relevant sub-page of the compound page.
 458  - map/unmap of the whole compound page accounted in compound_mapcount
 459    (stored in first tail page). For file huge pages, we also increment
 460    ->_mapcount of all sub-pages in order to have race-free detection of
 461    last unmap of subpages.
 463PageDoubleMap() indicates that the page is *possibly* mapped with PTEs.
 465For anonymous pages PageDoubleMap() also indicates ->_mapcount in all
 466subpages is offset up by one. This additional reference is required to
 467get race-free detection of unmap of subpages when we have them mapped with
 468both PMDs and PTEs.
 470This is optimization required to lower overhead of per-subpage mapcount
 471tracking. The alternative is alter ->_mapcount in all subpages on each
 472map/unmap of the whole compound page.
 474For anonymous pages, we set PG_double_map when a PMD of the page got split
 475for the first time, but still have PMD mapping. The additional references
 476go away with last compound_mapcount.
 478File pages get PG_double_map set on first map of the page with PTE and
 479goes away when the page gets evicted from page cache.
 481split_huge_page internally has to distribute the refcounts in the head
 482page to the tail pages before clearing all PG_head/tail bits from the page
 483structures. It can be done easily for refcounts taken by page table
 484entries. But we don't have enough information on how to distribute any
 485additional pins (i.e. from get_user_pages). split_huge_page() fails any
 486requests to split pinned huge page: it expects page count to be equal to
 487sum of mapcount of all sub-pages plus one (split_huge_page caller must
 488have reference for head page).
 490split_huge_page uses migration entries to stabilize page->_refcount and
 491page->_mapcount of anonymous pages. File pages just got unmapped.
 493We safe against physical memory scanners too: the only legitimate way
 494scanner can get reference to a page is get_page_unless_zero().
 496All tail pages have zero ->_refcount until atomic_add(). This prevents the
 497scanner from getting a reference to the tail page up to that point. After the
 498atomic_add() we don't care about the ->_refcount value.  We already known how
 499many references should be uncharged from the head page.
 501For head page get_page_unless_zero() will succeed and we don't mind. It's
 502clear where reference should go after split: it will stay on head page.
 504Note that split_huge_pmd() doesn't have any limitation on refcounting:
 505pmd can be split at any point and never fails.
 507== Partial unmap and deferred_split_huge_page() ==
 509Unmapping part of THP (with munmap() or other way) is not going to free
 510memory immediately. Instead, we detect that a subpage of THP is not in use
 511in page_remove_rmap() and queue the THP for splitting if memory pressure
 512comes. Splitting will free up unused subpages.
 514Splitting the page right away is not an option due to locking context in
 515the place where we can detect partial unmap. It's also might be
 516counterproductive since in many cases partial unmap unmap happens during
 517exit(2) if an THP crosses VMA boundary.
 519Function deferred_split_huge_page() is used to queue page for splitting.
 520The splitting itself will happen when we get memory pressure via shrinker
 522 kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.