1.. _transhuge:
2
3============================
4Transparent Hugepage Support
5============================
6
7This document describes design principles Transparent Hugepage (THP)
8Support and its interaction with other parts of the memory management.
9
10Design principles
11=================
12
13- "graceful fallback": mm components which don't have transparent hugepage
14  knowledge fall back to breaking huge pmd mapping into table of ptes and,
15  if necessary, split a transparent hugepage. Therefore these components
16  can continue working on the regular pages or regular pte mappings.
17
18- if a hugepage allocation fails because of memory fragmentation,
19  regular pages should be gracefully allocated instead and mixed in
20  the same vma without any failure or significant delay and without
21  userland noticing
22
23- if some task quits and more hugepages become available (either
24  immediately in the buddy or through the VM), guest physical memory
25  backed by regular pages should be relocated on hugepages
26  automatically (with khugepaged)
27
28- it doesn't require memory reservation and in turn it uses hugepages
29  whenever possible (the only possible reservation here is kernelcore=
30  to avoid unmovable pages to fragment all the memory but such a tweak
31  is not specific to transparent hugepage support and it's a generic
32  feature that applies to all dynamic high order allocations in the
33  kernel)
34
35get_user_pages and follow_page
36==============================
37
38get_user_pages and follow_page if run on a hugepage, will return the
39head or tail pages as usual (exactly as they would do on
40hugetlbfs). Most gup users will only care about the actual physical
41address of the page and its temporary pinning to release after the I/O
42is complete, so they won't ever notice the fact the page is huge. But
43if any driver is going to mangle over the page structure of the tail
44page (like for checking page->mapping or other bits that are relevant
45for the head page and not the tail page), it should be updated to jump
46to check head page instead. Taking reference on any head/tail page would
47prevent page from being split by anyone.
48
49.. note::
50   these aren't new constraints to the GUP API, and they match the
51   same constrains that applies to hugetlbfs too, so any driver capable
52   of handling GUP on hugetlbfs will also work fine on transparent
53   hugepage backed mappings.
54
55In case you can't handle compound pages if they're returned by
56follow_page, the FOLL_SPLIT bit can be specified as parameter to
57follow_page, so that it will split the hugepages before returning
58them. Migration for example passes FOLL_SPLIT as parameter to
59follow_page because it's not hugepage aware and in fact it can't work
60at all on hugetlbfs (but it instead works fine on transparent
61hugepages thanks to FOLL_SPLIT). migration simply can't deal with
62hugepages being returned (as it's not only checking the pfn of the
63page and pinning it during the copy but it pretends to migrate the
64memory in regular page sizes and with regular pte/pmd mappings).
65
66Graceful fallback
67=================
68
69Code walking pagetables but unaware about huge pmds can simply call
70split_huge_pmd(vma, pmd, addr) where the pmd is the one returned by
71pmd_offset. It's trivial to make the code transparent hugepage aware
72by just grepping for "pmd_offset" and adding split_huge_pmd where
73missing after pmd_offset returns the pmd. Thanks to the graceful
74fallback design, with a one liner change, you can avoid to write
75hundred if not thousand of lines of complex code to make your code
76hugepage aware.
77
78If you're not walking pagetables but you run into a physical hugepage
79but you can't handle it natively in your code, you can split it by
80calling split_huge_page(page). This is what the Linux VM does before
81it tries to swapout the hugepage for example. split_huge_page() can fail
82if the page is pinned and you must handle this correctly.
83
84Example to make mremap.c transparent hugepage aware with a one liner
85change::
86
87	diff --git a/mm/mremap.c b/mm/mremap.c
88	--- a/mm/mremap.c
89	+++ b/mm/mremap.c
90	@@ -41,6 +41,7 @@ static pmd_t *get_old_pmd(struct mm_stru
91			return NULL;
92
93		pmd = pmd_offset(pud, addr);
94	+	split_huge_pmd(vma, pmd, addr);
95		if (pmd_none_or_clear_bad(pmd))
96			return NULL;
97
98Locking in hugepage aware code
99==============================
100
101We want as much code as possible hugepage aware, as calling
102split_huge_page() or split_huge_pmd() has a cost.
103
104To make pagetable walks huge pmd aware, all you need to do is to call
105pmd_trans_huge() on the pmd returned by pmd_offset. You must hold the
106mmap_sem in read (or write) mode to be sure an huge pmd cannot be
107created from under you by khugepaged (khugepaged collapse_huge_page
108takes the mmap_sem in write mode in addition to the anon_vma lock). If
109pmd_trans_huge returns false, you just fallback in the old code
110paths. If instead pmd_trans_huge returns true, you have to take the
111page table lock (pmd_lock()) and re-run pmd_trans_huge. Taking the
112page table lock will prevent the huge pmd to be converted into a
113regular pmd from under you (split_huge_pmd can run in parallel to the
114pagetable walk). If the second pmd_trans_huge returns false, you
115should just drop the page table lock and fallback to the old code as
116before. Otherwise you can proceed to process the huge pmd and the
117hugepage natively. Once finished you can drop the page table lock.
118
119Refcounts and transparent huge pages
120====================================
121
122Refcounting on THP is mostly consistent with refcounting on other compound
123pages:
124
125  - get_page()/put_page() and GUP operate in head page's ->_refcount.
126
127  - ->_refcount in tail pages is always zero: get_page_unless_zero() never
128    succeed on tail pages.
129
130  - map/unmap of the pages with PTE entry increment/decrement ->_mapcount
131    on relevant sub-page of the compound page.
132
133  - map/unmap of the whole compound page accounted in compound_mapcount
134    (stored in first tail page). For file huge pages, we also increment
135    ->_mapcount of all sub-pages in order to have race-free detection of
136    last unmap of subpages.
137
138PageDoubleMap() indicates that the page is *possibly* mapped with PTEs.
139
140For anonymous pages PageDoubleMap() also indicates ->_mapcount in all
141subpages is offset up by one. This additional reference is required to
142get race-free detection of unmap of subpages when we have them mapped with
143both PMDs and PTEs.
144
145This is optimization required to lower overhead of per-subpage mapcount
146tracking. The alternative is alter ->_mapcount in all subpages on each
147map/unmap of the whole compound page.
148
149For anonymous pages, we set PG_double_map when a PMD of the page got split
150for the first time, but still have PMD mapping. The additional references
151go away with last compound_mapcount.
152
153File pages get PG_double_map set on first map of the page with PTE and
154goes away when the page gets evicted from page cache.
155
156split_huge_page internally has to distribute the refcounts in the head
157page to the tail pages before clearing all PG_head/tail bits from the page
158structures. It can be done easily for refcounts taken by page table
159entries. But we don't have enough information on how to distribute any
160additional pins (i.e. from get_user_pages). split_huge_page() fails any
161requests to split pinned huge page: it expects page count to be equal to
162sum of mapcount of all sub-pages plus one (split_huge_page caller must
163have reference for head page).
164
165split_huge_page uses migration entries to stabilize page->_refcount and
166page->_mapcount of anonymous pages. File pages just got unmapped.
167
168We safe against physical memory scanners too: the only legitimate way
169scanner can get reference to a page is get_page_unless_zero().
170
171All tail pages have zero ->_refcount until atomic_add(). This prevents the
172scanner from getting a reference to the tail page up to that point. After the
173atomic_add() we don't care about the ->_refcount value. We already known how
174many references should be uncharged from the head page.
175
176For head page get_page_unless_zero() will succeed and we don't mind. It's
177clear where reference should go after split: it will stay on head page.
178
179Note that split_huge_pmd() doesn't have any limitation on refcounting:
180pmd can be split at any point and never fails.
181
182Partial unmap and deferred_split_huge_page()
183============================================
184
185Unmapping part of THP (with munmap() or other way) is not going to free
186memory immediately. Instead, we detect that a subpage of THP is not in use
187in page_remove_rmap() and queue the THP for splitting if memory pressure
188comes. Splitting will free up unused subpages.
189
190Splitting the page right away is not an option due to locking context in
191the place where we can detect partial unmap. It's also might be
192counterproductive since in many cases partial unmap happens during exit(2) if
193a THP crosses a VMA boundary.
194
195Function deferred_split_huge_page() is used to queue page for splitting.
196The splitting itself will happen when we get memory pressure via shrinker
197interface.
198