transhuge.txt 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. = Transparent Hugepage Support =
  2. == Objective ==
  3. Performance critical computing applications dealing with large memory
  4. working sets are already running on top of libhugetlbfs and in turn
  5. hugetlbfs. Transparent Hugepage Support is an alternative means of
  6. using huge pages for the backing of virtual memory with huge pages
  7. that supports the automatic promotion and demotion of page sizes and
  8. without the shortcomings of hugetlbfs.
  9. Currently it only works for anonymous memory mappings but in the
  10. future it can expand over the pagecache layer starting with tmpfs.
  11. The reason applications are running faster is because of two
  12. factors. The first factor is almost completely irrelevant and it's not
  13. of significant interest because it'll also have the downside of
  14. requiring larger clear-page copy-page in page faults which is a
  15. potentially negative effect. The first factor consists in taking a
  16. single page fault for each 2M virtual region touched by userland (so
  17. reducing the enter/exit kernel frequency by a 512 times factor). This
  18. only matters the first time the memory is accessed for the lifetime of
  19. a memory mapping. The second long lasting and much more important
  20. factor will affect all subsequent accesses to the memory for the whole
  21. runtime of the application. The second factor consist of two
  22. components: 1) the TLB miss will run faster (especially with
  23. virtualization using nested pagetables but almost always also on bare
  24. metal without virtualization) and 2) a single TLB entry will be
  25. mapping a much larger amount of virtual memory in turn reducing the
  26. number of TLB misses. With virtualization and nested pagetables the
  27. TLB can be mapped of larger size only if both KVM and the Linux guest
  28. are using hugepages but a significant speedup already happens if only
  29. one of the two is using hugepages just because of the fact the TLB
  30. miss is going to run faster.
  31. == Design ==
  32. - "graceful fallback": mm components which don't have transparent
  33. hugepage knowledge fall back to breaking a transparent hugepage and
  34. working on the regular pages and their respective regular pmd/pte
  35. mappings
  36. - if a hugepage allocation fails because of memory fragmentation,
  37. regular pages should be gracefully allocated instead and mixed in
  38. the same vma without any failure or significant delay and without
  39. userland noticing
  40. - if some task quits and more hugepages become available (either
  41. immediately in the buddy or through the VM), guest physical memory
  42. backed by regular pages should be relocated on hugepages
  43. automatically (with khugepaged)
  44. - it doesn't require memory reservation and in turn it uses hugepages
  45. whenever possible (the only possible reservation here is kernelcore=
  46. to avoid unmovable pages to fragment all the memory but such a tweak
  47. is not specific to transparent hugepage support and it's a generic
  48. feature that applies to all dynamic high order allocations in the
  49. kernel)
  50. - this initial support only offers the feature in the anonymous memory
  51. regions but it'd be ideal to move it to tmpfs and the pagecache
  52. later
  53. Transparent Hugepage Support maximizes the usefulness of free memory
  54. if compared to the reservation approach of hugetlbfs by allowing all
  55. unused memory to be used as cache or other movable (or even unmovable
  56. entities). It doesn't require reservation to prevent hugepage
  57. allocation failures to be noticeable from userland. It allows paging
  58. and all other advanced VM features to be available on the
  59. hugepages. It requires no modifications for applications to take
  60. advantage of it.
  61. Applications however can be further optimized to take advantage of
  62. this feature, like for example they've been optimized before to avoid
  63. a flood of mmap system calls for every malloc(4k). Optimizing userland
  64. is by far not mandatory and khugepaged already can take care of long
  65. lived page allocations even for hugepage unaware applications that
  66. deals with large amounts of memory.
  67. In certain cases when hugepages are enabled system wide, application
  68. may end up allocating more memory resources. An application may mmap a
  69. large region but only touch 1 byte of it, in that case a 2M page might
  70. be allocated instead of a 4k page for no good. This is why it's
  71. possible to disable hugepages system-wide and to only have them inside
  72. MADV_HUGEPAGE madvise regions.
  73. Embedded systems should enable hugepages only inside madvise regions
  74. to eliminate any risk of wasting any precious byte of memory and to
  75. only run faster.
  76. Applications that gets a lot of benefit from hugepages and that don't
  77. risk to lose memory by using hugepages, should use
  78. madvise(MADV_HUGEPAGE) on their critical mmapped regions.
  79. == sysfs ==
  80. Transparent Hugepage Support can be entirely disabled (mostly for
  81. debugging purposes) or only enabled inside MADV_HUGEPAGE regions (to
  82. avoid the risk of consuming more memory resources) or enabled system
  83. wide. This can be achieved with one of:
  84. echo always >/sys/kernel/mm/transparent_hugepage/enabled
  85. echo madvise >/sys/kernel/mm/transparent_hugepage/enabled
  86. echo never >/sys/kernel/mm/transparent_hugepage/enabled
  87. It's also possible to limit defrag efforts in the VM to generate
  88. hugepages in case they're not immediately free to madvise regions or
  89. to never try to defrag memory and simply fallback to regular pages
  90. unless hugepages are immediately available. Clearly if we spend CPU
  91. time to defrag memory, we would expect to gain even more by the fact
  92. we use hugepages later instead of regular pages. This isn't always
  93. guaranteed, but it may be more likely in case the allocation is for a
  94. MADV_HUGEPAGE region.
  95. echo always >/sys/kernel/mm/transparent_hugepage/defrag
  96. echo madvise >/sys/kernel/mm/transparent_hugepage/defrag
  97. echo never >/sys/kernel/mm/transparent_hugepage/defrag
  98. By default kernel tries to use huge zero page on read page fault.
  99. It's possible to disable huge zero page by writing 0 or enable it
  100. back by writing 1:
  101. echo 0 >/sys/kernel/mm/transparent_hugepage/use_zero_page
  102. echo 1 >/sys/kernel/mm/transparent_hugepage/use_zero_page
  103. khugepaged will be automatically started when
  104. transparent_hugepage/enabled is set to "always" or "madvise, and it'll
  105. be automatically shutdown if it's set to "never".
  106. khugepaged runs usually at low frequency so while one may not want to
  107. invoke defrag algorithms synchronously during the page faults, it
  108. should be worth invoking defrag at least in khugepaged. However it's
  109. also possible to disable defrag in khugepaged by writing 0 or enable
  110. defrag in khugepaged by writing 1:
  111. echo 0 >/sys/kernel/mm/transparent_hugepage/khugepaged/defrag
  112. echo 1 >/sys/kernel/mm/transparent_hugepage/khugepaged/defrag
  113. You can also control how many pages khugepaged should scan at each
  114. pass:
  115. /sys/kernel/mm/transparent_hugepage/khugepaged/pages_to_scan
  116. and how many milliseconds to wait in khugepaged between each pass (you
  117. can set this to 0 to run khugepaged at 100% utilization of one core):
  118. /sys/kernel/mm/transparent_hugepage/khugepaged/scan_sleep_millisecs
  119. and how many milliseconds to wait in khugepaged if there's an hugepage
  120. allocation failure to throttle the next allocation attempt.
  121. /sys/kernel/mm/transparent_hugepage/khugepaged/alloc_sleep_millisecs
  122. The khugepaged progress can be seen in the number of pages collapsed:
  123. /sys/kernel/mm/transparent_hugepage/khugepaged/pages_collapsed
  124. for each pass:
  125. /sys/kernel/mm/transparent_hugepage/khugepaged/full_scans
  126. max_ptes_none specifies how many extra small pages (that are
  127. not already mapped) can be allocated when collapsing a group
  128. of small pages into one large page.
  129. /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_none
  130. A higher value leads to use additional memory for programs.
  131. A lower value leads to gain less thp performance. Value of
  132. max_ptes_none can waste cpu time very little, you can
  133. ignore it.
  134. max_ptes_swap specifies how many pages can be brought in from
  135. swap when collapsing a group of pages into a transparent huge page.
  136. /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_swap
  137. A higher value can cause excessive swap IO and waste
  138. memory. A lower value can prevent THPs from being
  139. collapsed, resulting fewer pages being collapsed into
  140. THPs, and lower memory access performance.
  141. == Boot parameter ==
  142. You can change the sysfs boot time defaults of Transparent Hugepage
  143. Support by passing the parameter "transparent_hugepage=always" or
  144. "transparent_hugepage=madvise" or "transparent_hugepage=never"
  145. (without "") to the kernel command line.
  146. == Need of application restart ==
  147. The transparent_hugepage/enabled values only affect future
  148. behavior. So to make them effective you need to restart any
  149. application that could have been using hugepages. This also applies to
  150. the regions registered in khugepaged.
  151. == Monitoring usage ==
  152. The number of transparent huge pages currently used by the system is
  153. available by reading the AnonHugePages field in /proc/meminfo. To
  154. identify what applications are using transparent huge pages, it is
  155. necessary to read /proc/PID/smaps and count the AnonHugePages fields
  156. for each mapping. Note that reading the smaps file is expensive and
  157. reading it frequently will incur overhead.
  158. There are a number of counters in /proc/vmstat that may be used to
  159. monitor how successfully the system is providing huge pages for use.
  160. thp_fault_alloc is incremented every time a huge page is successfully
  161. allocated to handle a page fault. This applies to both the
  162. first time a page is faulted and for COW faults.
  163. thp_collapse_alloc is incremented by khugepaged when it has found
  164. a range of pages to collapse into one huge page and has
  165. successfully allocated a new huge page to store the data.
  166. thp_fault_fallback is incremented if a page fault fails to allocate
  167. a huge page and instead falls back to using small pages.
  168. thp_collapse_alloc_failed is incremented if khugepaged found a range
  169. of pages that should be collapsed into one huge page but failed
  170. the allocation.
  171. thp_split is incremented every time a huge page is split into base
  172. pages. This can happen for a variety of reasons but a common
  173. reason is that a huge page is old and is being reclaimed.
  174. thp_zero_page_alloc is incremented every time a huge zero page is
  175. successfully allocated. It includes allocations which where
  176. dropped due race with other allocation. Note, it doesn't count
  177. every map of the huge zero page, only its allocation.
  178. thp_zero_page_alloc_failed is incremented if kernel fails to allocate
  179. huge zero page and falls back to using small pages.
  180. As the system ages, allocating huge pages may be expensive as the
  181. system uses memory compaction to copy data around memory to free a
  182. huge page for use. There are some counters in /proc/vmstat to help
  183. monitor this overhead.
  184. compact_stall is incremented every time a process stalls to run
  185. memory compaction so that a huge page is free for use.
  186. compact_success is incremented if the system compacted memory and
  187. freed a huge page for use.
  188. compact_fail is incremented if the system tries to compact memory
  189. but failed.
  190. compact_pages_moved is incremented each time a page is moved. If
  191. this value is increasing rapidly, it implies that the system
  192. is copying a lot of data to satisfy the huge page allocation.
  193. It is possible that the cost of copying exceeds any savings
  194. from reduced TLB misses.
  195. compact_pagemigrate_failed is incremented when the underlying mechanism
  196. for moving a page failed.
  197. compact_blocks_moved is incremented each time memory compaction examines
  198. a huge page aligned range of pages.
  199. It is possible to establish how long the stalls were using the function
  200. tracer to record how long was spent in __alloc_pages_nodemask and
  201. using the mm_page_alloc tracepoint to identify which allocations were
  202. for huge pages.
  203. == get_user_pages and follow_page ==
  204. get_user_pages and follow_page if run on a hugepage, will return the
  205. head or tail pages as usual (exactly as they would do on
  206. hugetlbfs). Most gup users will only care about the actual physical
  207. address of the page and its temporary pinning to release after the I/O
  208. is complete, so they won't ever notice the fact the page is huge. But
  209. if any driver is going to mangle over the page structure of the tail
  210. page (like for checking page->mapping or other bits that are relevant
  211. for the head page and not the tail page), it should be updated to jump
  212. to check head page instead (while serializing properly against
  213. split_huge_page() to avoid the head and tail pages to disappear from
  214. under it, see the futex code to see an example of that, hugetlbfs also
  215. needed special handling in futex code for similar reasons).
  216. NOTE: these aren't new constraints to the GUP API, and they match the
  217. same constrains that applies to hugetlbfs too, so any driver capable
  218. of handling GUP on hugetlbfs will also work fine on transparent
  219. hugepage backed mappings.
  220. In case you can't handle compound pages if they're returned by
  221. follow_page, the FOLL_SPLIT bit can be specified as parameter to
  222. follow_page, so that it will split the hugepages before returning
  223. them. Migration for example passes FOLL_SPLIT as parameter to
  224. follow_page because it's not hugepage aware and in fact it can't work
  225. at all on hugetlbfs (but it instead works fine on transparent
  226. hugepages thanks to FOLL_SPLIT). migration simply can't deal with
  227. hugepages being returned (as it's not only checking the pfn of the
  228. page and pinning it during the copy but it pretends to migrate the
  229. memory in regular page sizes and with regular pte/pmd mappings).
  230. == Optimizing the applications ==
  231. To be guaranteed that the kernel will map a 2M page immediately in any
  232. memory region, the mmap region has to be hugepage naturally
  233. aligned. posix_memalign() can provide that guarantee.
  234. == Hugetlbfs ==
  235. You can use hugetlbfs on a kernel that has transparent hugepage
  236. support enabled just fine as always. No difference can be noted in
  237. hugetlbfs other than there will be less overall fragmentation. All
  238. usual features belonging to hugetlbfs are preserved and
  239. unaffected. libhugetlbfs will also work fine as usual.
  240. == Graceful fallback ==
  241. Code walking pagetables but unware about huge pmds can simply call
  242. split_huge_page_pmd(vma, addr, pmd) where the pmd is the one returned by
  243. pmd_offset. It's trivial to make the code transparent hugepage aware
  244. by just grepping for "pmd_offset" and adding split_huge_page_pmd where
  245. missing after pmd_offset returns the pmd. Thanks to the graceful
  246. fallback design, with a one liner change, you can avoid to write
  247. hundred if not thousand of lines of complex code to make your code
  248. hugepage aware.
  249. If you're not walking pagetables but you run into a physical hugepage
  250. but you can't handle it natively in your code, you can split it by
  251. calling split_huge_page(page). This is what the Linux VM does before
  252. it tries to swapout the hugepage for example.
  253. Example to make mremap.c transparent hugepage aware with a one liner
  254. change:
  255. diff --git a/mm/mremap.c b/mm/mremap.c
  256. --- a/mm/mremap.c
  257. +++ b/mm/mremap.c
  258. @@ -41,6 +41,7 @@ static pmd_t *get_old_pmd(struct mm_stru
  259. return NULL;
  260. pmd = pmd_offset(pud, addr);
  261. + split_huge_page_pmd(vma, addr, pmd);
  262. if (pmd_none_or_clear_bad(pmd))
  263. return NULL;
  264. == Locking in hugepage aware code ==
  265. We want as much code as possible hugepage aware, as calling
  266. split_huge_page() or split_huge_page_pmd() has a cost.
  267. To make pagetable walks huge pmd aware, all you need to do is to call
  268. pmd_trans_huge() on the pmd returned by pmd_offset. You must hold the
  269. mmap_sem in read (or write) mode to be sure an huge pmd cannot be
  270. created from under you by khugepaged (khugepaged collapse_huge_page
  271. takes the mmap_sem in write mode in addition to the anon_vma lock). If
  272. pmd_trans_huge returns false, you just fallback in the old code
  273. paths. If instead pmd_trans_huge returns true, you have to take the
  274. mm->page_table_lock and re-run pmd_trans_huge. Taking the
  275. page_table_lock will prevent the huge pmd to be converted into a
  276. regular pmd from under you (split_huge_page can run in parallel to the
  277. pagetable walk). If the second pmd_trans_huge returns false, you
  278. should just drop the page_table_lock and fallback to the old code as
  279. before. Otherwise you should run pmd_trans_splitting on the pmd. In
  280. case pmd_trans_splitting returns true, it means split_huge_page is
  281. already in the middle of splitting the page. So if pmd_trans_splitting
  282. returns true it's enough to drop the page_table_lock and call
  283. wait_split_huge_page and then fallback the old code paths. You are
  284. guaranteed by the time wait_split_huge_page returns, the pmd isn't
  285. huge anymore. If pmd_trans_splitting returns false, you can proceed to
  286. process the huge pmd and the hugepage natively. Once finished you can
  287. drop the page_table_lock.
  288. == compound_lock, get_user_pages and put_page ==
  289. split_huge_page internally has to distribute the refcounts in the head
  290. page to the tail pages before clearing all PG_head/tail bits from the
  291. page structures. It can do that easily for refcounts taken by huge pmd
  292. mappings. But the GUI API as created by hugetlbfs (that returns head
  293. and tail pages if running get_user_pages on an address backed by any
  294. hugepage), requires the refcount to be accounted on the tail pages and
  295. not only in the head pages, if we want to be able to run
  296. split_huge_page while there are gup pins established on any tail
  297. page. Failure to be able to run split_huge_page if there's any gup pin
  298. on any tail page, would mean having to split all hugepages upfront in
  299. get_user_pages which is unacceptable as too many gup users are
  300. performance critical and they must work natively on hugepages like
  301. they work natively on hugetlbfs already (hugetlbfs is simpler because
  302. hugetlbfs pages cannot be split so there wouldn't be requirement of
  303. accounting the pins on the tail pages for hugetlbfs). If we wouldn't
  304. account the gup refcounts on the tail pages during gup, we won't know
  305. anymore which tail page is pinned by gup and which is not while we run
  306. split_huge_page. But we still have to add the gup pin to the head page
  307. too, to know when we can free the compound page in case it's never
  308. split during its lifetime. That requires changing not just
  309. get_page, but put_page as well so that when put_page runs on a tail
  310. page (and only on a tail page) it will find its respective head page,
  311. and then it will decrease the head page refcount in addition to the
  312. tail page refcount. To obtain a head page reliably and to decrease its
  313. refcount without race conditions, put_page has to serialize against
  314. __split_huge_page_refcount using a special per-page lock called
  315. compound_lock.