619 lines · plain
1============================2Transparent Hugepage Support3============================4 5Objective6=========7 8Performance critical computing applications dealing with large memory9working sets are already running on top of libhugetlbfs and in turn10hugetlbfs. Transparent HugePage Support (THP) is an alternative mean of11using huge pages for the backing of virtual memory with huge pages12that supports the automatic promotion and demotion of page sizes and13without the shortcomings of hugetlbfs.14 15Currently THP only works for anonymous memory mappings and tmpfs/shmem.16But in the future it can expand to other filesystems.17 18.. note::19 in the examples below we presume that the basic page size is 4K and20 the huge page size is 2M, although the actual numbers may vary21 depending on the CPU architecture.22 23The reason applications are running faster is because of two24factors. The first factor is almost completely irrelevant and it's not25of significant interest because it'll also have the downside of26requiring larger clear-page copy-page in page faults which is a27potentially negative effect. The first factor consists in taking a28single page fault for each 2M virtual region touched by userland (so29reducing the enter/exit kernel frequency by a 512 times factor). This30only matters the first time the memory is accessed for the lifetime of31a memory mapping. The second long lasting and much more important32factor will affect all subsequent accesses to the memory for the whole33runtime of the application. The second factor consist of two34components:35 361) the TLB miss will run faster (especially with virtualization using37 nested pagetables but almost always also on bare metal without38 virtualization)39 402) a single TLB entry will be mapping a much larger amount of virtual41 memory in turn reducing the number of TLB misses. With42 virtualization and nested pagetables the TLB can be mapped of43 larger size only if both KVM and the Linux guest are using44 hugepages but a significant speedup already happens if only one of45 the two is using hugepages just because of the fact the TLB miss is46 going to run faster.47 48Modern kernels support "multi-size THP" (mTHP), which introduces the49ability to allocate memory in blocks that are bigger than a base page50but smaller than traditional PMD-size (as described above), in51increments of a power-of-2 number of pages. mTHP can back anonymous52memory (for example 16K, 32K, 64K, etc). These THPs continue to be53PTE-mapped, but in many cases can still provide similar benefits to54those outlined above: Page faults are significantly reduced (by a55factor of e.g. 4, 8, 16, etc), but latency spikes are much less56prominent because the size of each page isn't as huge as the PMD-sized57variant and there is less memory to clear in each page fault. Some58architectures also employ TLB compression mechanisms to squeeze more59entries in when a set of PTEs are virtually and physically contiguous60and approporiately aligned. In this case, TLB misses will occur less61often.62 63THP can be enabled system wide or restricted to certain tasks or even64memory ranges inside task's address space. Unless THP is completely65disabled, there is ``khugepaged`` daemon that scans memory and66collapses sequences of basic pages into PMD-sized huge pages.67 68The THP behaviour is controlled via :ref:`sysfs <thp_sysfs>`69interface and using madvise(2) and prctl(2) system calls.70 71Transparent Hugepage Support maximizes the usefulness of free memory72if compared to the reservation approach of hugetlbfs by allowing all73unused memory to be used as cache or other movable (or even unmovable74entities). It doesn't require reservation to prevent hugepage75allocation failures to be noticeable from userland. It allows paging76and all other advanced VM features to be available on the77hugepages. It requires no modifications for applications to take78advantage of it.79 80Applications however can be further optimized to take advantage of81this feature, like for example they've been optimized before to avoid82a flood of mmap system calls for every malloc(4k). Optimizing userland83is by far not mandatory and khugepaged already can take care of long84lived page allocations even for hugepage unaware applications that85deals with large amounts of memory.86 87In certain cases when hugepages are enabled system wide, application88may end up allocating more memory resources. An application may mmap a89large region but only touch 1 byte of it, in that case a 2M page might90be allocated instead of a 4k page for no good. This is why it's91possible to disable hugepages system-wide and to only have them inside92MADV_HUGEPAGE madvise regions.93 94Embedded systems should enable hugepages only inside madvise regions95to eliminate any risk of wasting any precious byte of memory and to96only run faster.97 98Applications that gets a lot of benefit from hugepages and that don't99risk to lose memory by using hugepages, should use100madvise(MADV_HUGEPAGE) on their critical mmapped regions.101 102.. _thp_sysfs:103 104sysfs105=====106 107Global THP controls108-------------------109 110Transparent Hugepage Support for anonymous memory can be entirely disabled111(mostly for debugging purposes) or only enabled inside MADV_HUGEPAGE112regions (to avoid the risk of consuming more memory resources) or enabled113system wide. This can be achieved per-supported-THP-size with one of::114 115 echo always >/sys/kernel/mm/transparent_hugepage/hugepages-<size>kB/enabled116 echo madvise >/sys/kernel/mm/transparent_hugepage/hugepages-<size>kB/enabled117 echo never >/sys/kernel/mm/transparent_hugepage/hugepages-<size>kB/enabled118 119where <size> is the hugepage size being addressed, the available sizes120for which vary by system.121 122For example::123 124 echo always >/sys/kernel/mm/transparent_hugepage/hugepages-2048kB/enabled125 126Alternatively it is possible to specify that a given hugepage size127will inherit the top-level "enabled" value::128 129 echo inherit >/sys/kernel/mm/transparent_hugepage/hugepages-<size>kB/enabled130 131For example::132 133 echo inherit >/sys/kernel/mm/transparent_hugepage/hugepages-2048kB/enabled134 135The top-level setting (for use with "inherit") can be set by issuing136one of the following commands::137 138 echo always >/sys/kernel/mm/transparent_hugepage/enabled139 echo madvise >/sys/kernel/mm/transparent_hugepage/enabled140 echo never >/sys/kernel/mm/transparent_hugepage/enabled141 142By default, PMD-sized hugepages have enabled="inherit" and all other143hugepage sizes have enabled="never". If enabling multiple hugepage144sizes, the kernel will select the most appropriate enabled size for a145given allocation.146 147It's also possible to limit defrag efforts in the VM to generate148anonymous hugepages in case they're not immediately free to madvise149regions or to never try to defrag memory and simply fallback to regular150pages unless hugepages are immediately available. Clearly if we spend CPU151time to defrag memory, we would expect to gain even more by the fact we152use hugepages later instead of regular pages. This isn't always153guaranteed, but it may be more likely in case the allocation is for a154MADV_HUGEPAGE region.155 156::157 158 echo always >/sys/kernel/mm/transparent_hugepage/defrag159 echo defer >/sys/kernel/mm/transparent_hugepage/defrag160 echo defer+madvise >/sys/kernel/mm/transparent_hugepage/defrag161 echo madvise >/sys/kernel/mm/transparent_hugepage/defrag162 echo never >/sys/kernel/mm/transparent_hugepage/defrag163 164always165 means that an application requesting THP will stall on166 allocation failure and directly reclaim pages and compact167 memory in an effort to allocate a THP immediately. This may be168 desirable for virtual machines that benefit heavily from THP169 use and are willing to delay the VM start to utilise them.170 171defer172 means that an application will wake kswapd in the background173 to reclaim pages and wake kcompactd to compact memory so that174 THP is available in the near future. It's the responsibility175 of khugepaged to then install the THP pages later.176 177defer+madvise178 will enter direct reclaim and compaction like ``always``, but179 only for regions that have used madvise(MADV_HUGEPAGE); all180 other regions will wake kswapd in the background to reclaim181 pages and wake kcompactd to compact memory so that THP is182 available in the near future.183 184madvise185 will enter direct reclaim like ``always`` but only for regions186 that are have used madvise(MADV_HUGEPAGE). This is the default187 behaviour.188 189never190 should be self-explanatory.191 192By default kernel tries to use huge, PMD-mappable zero page on read193page fault to anonymous mapping. It's possible to disable huge zero194page by writing 0 or enable it back by writing 1::195 196 echo 0 >/sys/kernel/mm/transparent_hugepage/use_zero_page197 echo 1 >/sys/kernel/mm/transparent_hugepage/use_zero_page198 199Some userspace (such as a test program, or an optimized memory200allocation library) may want to know the size (in bytes) of a201PMD-mappable transparent hugepage::202 203 cat /sys/kernel/mm/transparent_hugepage/hpage_pmd_size204 205All THPs at fault and collapse time will be added to _deferred_list,206and will therefore be split under memory presure if they are considered207"underused". A THP is underused if the number of zero-filled pages in208the THP is above max_ptes_none (see below). It is possible to disable209this behaviour by writing 0 to shrink_underused, and enable it by writing2101 to it::211 212 echo 0 > /sys/kernel/mm/transparent_hugepage/shrink_underused213 echo 1 > /sys/kernel/mm/transparent_hugepage/shrink_underused214 215khugepaged will be automatically started when PMD-sized THP is enabled216(either of the per-size anon control or the top-level control are set217to "always" or "madvise"), and it'll be automatically shutdown when218PMD-sized THP is disabled (when both the per-size anon control and the219top-level control are "never")220 221Khugepaged controls222-------------------223 224.. note::225 khugepaged currently only searches for opportunities to collapse to226 PMD-sized THP and no attempt is made to collapse to other THP227 sizes.228 229khugepaged runs usually at low frequency so while one may not want to230invoke defrag algorithms synchronously during the page faults, it231should be worth invoking defrag at least in khugepaged. However it's232also possible to disable defrag in khugepaged by writing 0 or enable233defrag in khugepaged by writing 1::234 235 echo 0 >/sys/kernel/mm/transparent_hugepage/khugepaged/defrag236 echo 1 >/sys/kernel/mm/transparent_hugepage/khugepaged/defrag237 238You can also control how many pages khugepaged should scan at each239pass::240 241 /sys/kernel/mm/transparent_hugepage/khugepaged/pages_to_scan242 243and how many milliseconds to wait in khugepaged between each pass (you244can set this to 0 to run khugepaged at 100% utilization of one core)::245 246 /sys/kernel/mm/transparent_hugepage/khugepaged/scan_sleep_millisecs247 248and how many milliseconds to wait in khugepaged if there's an hugepage249allocation failure to throttle the next allocation attempt::250 251 /sys/kernel/mm/transparent_hugepage/khugepaged/alloc_sleep_millisecs252 253The khugepaged progress can be seen in the number of pages collapsed (note254that this counter may not be an exact count of the number of pages255collapsed, since "collapsed" could mean multiple things: (1) A PTE mapping256being replaced by a PMD mapping, or (2) All 4K physical pages replaced by257one 2M hugepage. Each may happen independently, or together, depending on258the type of memory and the failures that occur. As such, this value should259be interpreted roughly as a sign of progress, and counters in /proc/vmstat260consulted for more accurate accounting)::261 262 /sys/kernel/mm/transparent_hugepage/khugepaged/pages_collapsed263 264for each pass::265 266 /sys/kernel/mm/transparent_hugepage/khugepaged/full_scans267 268``max_ptes_none`` specifies how many extra small pages (that are269not already mapped) can be allocated when collapsing a group270of small pages into one large page::271 272 /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_none273 274A higher value leads to use additional memory for programs.275A lower value leads to gain less thp performance. Value of276max_ptes_none can waste cpu time very little, you can277ignore it.278 279``max_ptes_swap`` specifies how many pages can be brought in from280swap when collapsing a group of pages into a transparent huge page::281 282 /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_swap283 284A higher value can cause excessive swap IO and waste285memory. A lower value can prevent THPs from being286collapsed, resulting fewer pages being collapsed into287THPs, and lower memory access performance.288 289``max_ptes_shared`` specifies how many pages can be shared across multiple290processes. khugepaged might treat pages of THPs as shared if any page of291that THP is shared. Exceeding the number would block the collapse::292 293 /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_shared294 295A higher value may increase memory footprint for some workloads.296 297Boot parameters298===============299 300You can change the sysfs boot time default for the top-level "enabled"301control by passing the parameter ``transparent_hugepage=always`` or302``transparent_hugepage=madvise`` or ``transparent_hugepage=never`` to the303kernel command line.304 305Alternatively, each supported anonymous THP size can be controlled by306passing ``thp_anon=<size>[KMG],<size>[KMG]:<state>;<size>[KMG]-<size>[KMG]:<state>``,307where ``<size>`` is the THP size (must be a power of 2 of PAGE_SIZE and308supported anonymous THP) and ``<state>`` is one of ``always``, ``madvise``,309``never`` or ``inherit``.310 311For example, the following will set 16K, 32K, 64K THP to ``always``,312set 128K, 512K to ``inherit``, set 256K to ``madvise`` and 1M, 2M313to ``never``::314 315 thp_anon=16K-64K:always;128K,512K:inherit;256K:madvise;1M-2M:never316 317``thp_anon=`` may be specified multiple times to configure all THP sizes as318required. If ``thp_anon=`` is specified at least once, any anon THP sizes319not explicitly configured on the command line are implicitly set to320``never``.321 322``transparent_hugepage`` setting only affects the global toggle. If323``thp_anon`` is not specified, PMD_ORDER THP will default to ``inherit``.324However, if a valid ``thp_anon`` setting is provided by the user, the325PMD_ORDER THP policy will be overridden. If the policy for PMD_ORDER326is not defined within a valid ``thp_anon``, its policy will default to327``never``.328 329Hugepages in tmpfs/shmem330========================331 332You can control hugepage allocation policy in tmpfs with mount option333``huge=``. It can have following values:334 335always336 Attempt to allocate huge pages every time we need a new page;337 338never339 Do not allocate huge pages;340 341within_size342 Only allocate huge page if it will be fully within i_size.343 Also respect fadvise()/madvise() hints;344 345advise346 Only allocate huge pages if requested with fadvise()/madvise();347 348The default policy is ``never``.349 350``mount -o remount,huge= /mountpoint`` works fine after mount: remounting351``huge=never`` will not attempt to break up huge pages at all, just stop more352from being allocated.353 354There's also sysfs knob to control hugepage allocation policy for internal355shmem mount: /sys/kernel/mm/transparent_hugepage/shmem_enabled. The mount356is used for SysV SHM, memfds, shared anonymous mmaps (of /dev/zero or357MAP_ANONYMOUS), GPU drivers' DRM objects, Ashmem.358 359In addition to policies listed above, shmem_enabled allows two further360values:361 362deny363 For use in emergencies, to force the huge option off from364 all mounts;365force366 Force the huge option on for all - very useful for testing;367 368Shmem can also use "multi-size THP" (mTHP) by adding a new sysfs knob to369control mTHP allocation:370'/sys/kernel/mm/transparent_hugepage/hugepages-<size>kB/shmem_enabled',371and its value for each mTHP is essentially consistent with the global372setting. An 'inherit' option is added to ensure compatibility with these373global settings. Conversely, the options 'force' and 'deny' are dropped,374which are rather testing artifacts from the old ages.375 376always377 Attempt to allocate <size> huge pages every time we need a new page;378 379inherit380 Inherit the top-level "shmem_enabled" value. By default, PMD-sized hugepages381 have enabled="inherit" and all other hugepage sizes have enabled="never";382 383never384 Do not allocate <size> huge pages;385 386within_size387 Only allocate <size> huge page if it will be fully within i_size.388 Also respect fadvise()/madvise() hints;389 390advise391 Only allocate <size> huge pages if requested with fadvise()/madvise();392 393Need of application restart394===========================395 396The transparent_hugepage/enabled and397transparent_hugepage/hugepages-<size>kB/enabled values and tmpfs mount398option only affect future behavior. So to make them effective you need399to restart any application that could have been using hugepages. This400also applies to the regions registered in khugepaged.401 402Monitoring usage403================404 405The number of PMD-sized anonymous transparent huge pages currently used by the406system is available by reading the AnonHugePages field in ``/proc/meminfo``.407To identify what applications are using PMD-sized anonymous transparent huge408pages, it is necessary to read ``/proc/PID/smaps`` and count the AnonHugePages409fields for each mapping. (Note that AnonHugePages only applies to traditional410PMD-sized THP for historical reasons and should have been called411AnonHugePmdMapped).412 413The number of file transparent huge pages mapped to userspace is available414by reading ShmemPmdMapped and ShmemHugePages fields in ``/proc/meminfo``.415To identify what applications are mapping file transparent huge pages, it416is necessary to read ``/proc/PID/smaps`` and count the FileHugeMapped fields417for each mapping.418 419Note that reading the smaps file is expensive and reading it420frequently will incur overhead.421 422There are a number of counters in ``/proc/vmstat`` that may be used to423monitor how successfully the system is providing huge pages for use.424 425thp_fault_alloc426 is incremented every time a huge page is successfully427 allocated and charged to handle a page fault.428 429thp_collapse_alloc430 is incremented by khugepaged when it has found431 a range of pages to collapse into one huge page and has432 successfully allocated a new huge page to store the data.433 434thp_fault_fallback435 is incremented if a page fault fails to allocate or charge436 a huge page and instead falls back to using small pages.437 438thp_fault_fallback_charge439 is incremented if a page fault fails to charge a huge page and440 instead falls back to using small pages even though the441 allocation was successful.442 443thp_collapse_alloc_failed444 is incremented if khugepaged found a range445 of pages that should be collapsed into one huge page but failed446 the allocation.447 448thp_file_alloc449 is incremented every time a shmem huge page is successfully450 allocated (Note that despite being named after "file", the counter451 measures only shmem).452 453thp_file_fallback454 is incremented if a shmem huge page is attempted to be allocated455 but fails and instead falls back to using small pages. (Note that456 despite being named after "file", the counter measures only shmem).457 458thp_file_fallback_charge459 is incremented if a shmem huge page cannot be charged and instead460 falls back to using small pages even though the allocation was461 successful. (Note that despite being named after "file", the462 counter measures only shmem).463 464thp_file_mapped465 is incremented every time a file or shmem huge page is mapped into466 user address space.467 468thp_split_page469 is incremented every time a huge page is split into base470 pages. This can happen for a variety of reasons but a common471 reason is that a huge page is old and is being reclaimed.472 This action implies splitting all PMD the page mapped with.473 474thp_split_page_failed475 is incremented if kernel fails to split huge476 page. This can happen if the page was pinned by somebody.477 478thp_deferred_split_page479 is incremented when a huge page is put onto split480 queue. This happens when a huge page is partially unmapped and481 splitting it would free up some memory. Pages on split queue are482 going to be split under memory pressure.483 484thp_underused_split_page485 is incremented when a huge page on the split queue was split486 because it was underused. A THP is underused if the number of487 zero pages in the THP is above a certain threshold488 (/sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_none).489 490thp_split_pmd491 is incremented every time a PMD split into table of PTEs.492 This can happen, for instance, when application calls mprotect() or493 munmap() on part of huge page. It doesn't split huge page, only494 page table entry.495 496thp_zero_page_alloc497 is incremented every time a huge zero page used for thp is498 successfully allocated. Note, it doesn't count every map of499 the huge zero page, only its allocation.500 501thp_zero_page_alloc_failed502 is incremented if kernel fails to allocate503 huge zero page and falls back to using small pages.504 505thp_swpout506 is incremented every time a huge page is swapout in one507 piece without splitting.508 509thp_swpout_fallback510 is incremented if a huge page has to be split before swapout.511 Usually because failed to allocate some continuous swap space512 for the huge page.513 514In /sys/kernel/mm/transparent_hugepage/hugepages-<size>kB/stats, There are515also individual counters for each huge page size, which can be utilized to516monitor the system's effectiveness in providing huge pages for usage. Each517counter has its own corresponding file.518 519anon_fault_alloc520 is incremented every time a huge page is successfully521 allocated and charged to handle a page fault.522 523anon_fault_fallback524 is incremented if a page fault fails to allocate or charge525 a huge page and instead falls back to using huge pages with526 lower orders or small pages.527 528anon_fault_fallback_charge529 is incremented if a page fault fails to charge a huge page and530 instead falls back to using huge pages with lower orders or531 small pages even though the allocation was successful.532 533swpout534 is incremented every time a huge page is swapped out in one535 piece without splitting.536 537swpout_fallback538 is incremented if a huge page has to be split before swapout.539 Usually because failed to allocate some continuous swap space540 for the huge page.541 542shmem_alloc543 is incremented every time a shmem huge page is successfully544 allocated.545 546shmem_fallback547 is incremented if a shmem huge page is attempted to be allocated548 but fails and instead falls back to using small pages.549 550shmem_fallback_charge551 is incremented if a shmem huge page cannot be charged and instead552 falls back to using small pages even though the allocation was553 successful.554 555split556 is incremented every time a huge page is successfully split into557 smaller orders. This can happen for a variety of reasons but a558 common reason is that a huge page is old and is being reclaimed.559 560split_failed561 is incremented if kernel fails to split huge562 page. This can happen if the page was pinned by somebody.563 564split_deferred565 is incremented when a huge page is put onto split queue.566 This happens when a huge page is partially unmapped and splitting567 it would free up some memory. Pages on split queue are going to568 be split under memory pressure, if splitting is possible.569 570nr_anon571 the number of anonymous THP we have in the whole system. These THPs572 might be currently entirely mapped or have partially unmapped/unused573 subpages.574 575nr_anon_partially_mapped576 the number of anonymous THP which are likely partially mapped, possibly577 wasting memory, and have been queued for deferred memory reclamation.578 Note that in corner some cases (e.g., failed migration), we might detect579 an anonymous THP as "partially mapped" and count it here, even though it580 is not actually partially mapped anymore.581 582As the system ages, allocating huge pages may be expensive as the583system uses memory compaction to copy data around memory to free a584huge page for use. There are some counters in ``/proc/vmstat`` to help585monitor this overhead.586 587compact_stall588 is incremented every time a process stalls to run589 memory compaction so that a huge page is free for use.590 591compact_success592 is incremented if the system compacted memory and593 freed a huge page for use.594 595compact_fail596 is incremented if the system tries to compact memory597 but failed.598 599It is possible to establish how long the stalls were using the function600tracer to record how long was spent in __alloc_pages() and601using the mm_page_alloc tracepoint to identify which allocations were602for huge pages.603 604Optimizing the applications605===========================606 607To be guaranteed that the kernel will map a THP immediately in any608memory region, the mmap region has to be hugepage naturally609aligned. posix_memalign() can provide that guarantee.610 611Hugetlbfs612=========613 614You can use hugetlbfs on a kernel that has transparent hugepage615support enabled just fine as always. No difference can be noted in616hugetlbfs other than there will be less overall fragmentation. All617usual features belonging to hugetlbfs are preserved and618unaffected. libhugetlbfs will also work fine as usual.619