khugepaged: add mTHP collapse support
Subsystems (5)
v19 cover khugepaged: add mTHP collapse support
The following series provides khugepaged with the capability to collapse anonymous memory regions to mTHPs.
To achieve this we generalize the khugepaged functions to no longer depend on PMD_ORDER. Then during the PMD scan, we use a bitmap to track individual pages that are occupied (!none/zero). After the PMD scan is done, we use the bitmap to find the optimal mTHP sizes for the PMD range. The restriction on max_ptes_none is removed during the scan, to make sure we account for the whole PMD range in the bitmap. When no mTHP size is enabled, the legacy behavior of khugepaged is maintained.
We currently only support max_ptes_none values of 0 or HPAGE_PMD_NR - 1 (ie 511). If any other value is specified, the kernel will emit a warning and mTHP collapse will default to max_ptes_none=0. If a mTHP collapse is attempted, but contains swapped out, or shared pages, we don't perform the collapse.
It is now also possible to collapse to mTHPs without requiring the PMD THP size to be enabled. These limitations are to prevent collapse "creep" behavior. This prevents constantly promoting mTHPs to the next available size, which would occur because a collapse introduces more non-zero pages that would satisfy the promotion condition on subsequent scans.
Patch 1-2: Generalize hugepage_vma_revalidate and alloc_charge_folio
for arbitrary orders.
Patch 3: Rework max_ptes_* handling into helper functions Patch 4: Generalize __collapse_huge_page_* for mTHP support Patch 5: Require collapse_huge_page to enter/exit with the lock dropped Patch 6: Generalize collapse_huge_page for mTHP collapse Patch 7: Skip collapsing mTHP to smaller orders Patch 8-9: Add per-order mTHP statistics and tracepoints Patch 10: Introduce collapse_possible_orders helper functions Patch 11-13: Introduce bitmap and mTHP collapse support, fully enabled Patch 14: Documentation
Testing:
- Built for x86_64, aarch64, ppc64le, and s390x
- ran all arches on test suites provided by the kernel-tests project
- internal testing suites: functional testing and performance testing
- selftests mm
- I created a test script that I used to push khugepaged to its limits while monitoring a number of stats and tracepoints. The code is available here[1] (Run in legacy mode for these changes and set mthp sizes to inherit)
The summary from my testings was that there was no significant regression noticed through this test. In some cases my changes had better collapse latencies, and was able to scan more pages in the same amount of time/work, but for the most part the results were consistent.
- redis testing. I did some testing with these changes along with my defer changes (see followup [2] post for more details). We've decided to get the mTHP changes merged first before attempting the defer series.
- some basic testing on 64k page size.
- lots of general use.
[1] - https://gitlab.com/npache/khugepaged_mthp_test
[2] - https://lore.kernel.org/lkml/[email protected]/
V19 Changes:
- Rebased onto mm-unstable (base: 9282f9bdbdf2, where v18 was based)
- Added RBs/Acks
- [patch 04] Make max_ptes_none const; guard pr_warn_once with check so we only warn for non-zero intermediate values and use a single "return 0" path (David)
- [patch 06] Add comment explaining the mmu_notifier_range covers only the modified PTE range (David); change BUG_ON to VM_WARN_ON_ONCE (David); fix update_mmu_cache_range() arch safety issue: reinstall PMD via pmd_populate() before calling map_anon_folio_pte_nopf() and hold the PTE lock nested inside pmd_ptl during the operation (David, Lance); drop the now-unnecessary smp_wmb() as __folio_mark_uptodate() provides the required ordering (David, Lance)
- [patch 07] Clarify commit message: "mTHP to a folio of equal or smaller size, possibly resulting in a partially mapped source folio" (David)
- [patch 08] Add Lorenzo's RB and David's Ack; move TODO comment about shared pages to patch 4 (David)
- [patch 10] Rename collapse_allowable_orders() to collapse_possible_orders() and add collapse_possible() boolean wrapper for callers that only need a yes/no answer (David)
- [patch 11] Major rework: replace the DFS stack-based algorithm with a simpler linear forward-walking approach using offset + order (David); remove mthp_range struct, mthp_bitmap_stack[], stack push/pop functions, and MTHP_STACK_SIZE; add max_order_from_offset() helper using __ffs(offset) for natural alignment; rename mthp_bitmap to mthp_present_ptes (David); remove temporary mthp_bitmap_mask and use bitmap_weight_from() directly (David); fix result propagation so mthp_collapse() returns enum scan_result and properly propagates SCAN_ALLOC_HUGE_PAGE_FAIL and SCAN_PTE_MAPPED_HUGEPAGE to callers (Lance); fold in v18 fixup for potential use-after-free of vma in mthp_collapse() by passing NULL to collapse_max_ptes_none()
- [patch 12] Rework to match new linear algorithm; expand the set of failures that allow retrying at a lower order
- [patch 14] Re-add note about file/shmem still only collapsing to PMD-sized THPs (David)
Baolin Wang (1):
mm/khugepaged: run khugepaged for all orders
Dev Jain (1):
mm/khugepaged: generalize alloc_charge_folio()
Nico Pache (12):
mm/khugepaged: generalize hugepage_vma_revalidate for mTHP support mm/khugepaged: rework max_ptes_* handling with helper functions mm/khugepaged: generalize __collapse_huge_page_* for mTHP support mm/khugepaged: require collapse_huge_page to enter/exit with the lock
dropped
mm/khugepaged: generalize collapse_huge_page for mTHP collapse mm/khugepaged: skip collapsing mTHP to smaller orders mm/khugepaged: add per-order mTHP collapse failure statistics mm/khugepaged: improve tracepoints for mTHP orders mm/khugepaged: introduce collapse_possible_orders helper functions mm/khugepaged: Introduce mTHP collapse support mm/khugepaged: avoid unnecessary mTHP collapse attempts
Documentation: mm: update the admin guide for mTHP collapse
Documentation/admin-guide/mm/transhuge.rst | 71 ++- include/linux/huge_mm.h | 5 + include/trace/events/huge_memory.h | 34 +- mm/huge_memory.c | 11 + mm/khugepaged.c | 616 ++++++++++++++++----- 5 files changed, 569 insertions(+), 168 deletions(-)
base-commit: 9282f9bdbdf22a1914f0b085f2fe5e8141cbc3de
Signature · 1 line
2.54.0
PATCH v19 1/14 mm/khugepaged: generalize hugepage_vma_revalidate for mTHP support
For khugepaged to support different mTHP orders, we must generalize this to check if the PMD is not shared by another VMA and that the order is enabled.
We cannot collapse VMA regions that do not span the full PMD. This is due to the potential of the PMD being shared by another VMA which leaves us vulnerable to race conditions if neighboring VMAs are resized. Always check the PMD order here to ensure its not shared by another VMA. We'd need to lock all VMAs in the PMD range to support this which may lead to increased lock contention and code complexity.
No functional change in this patch. Also correct a comment about the functionality of the revalidation and fix a double space issues.
--- mm/khugepaged.c | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-)
mm/khugepaged.c +18 -8
@@ -905,12 +905,13 @@ static int collapse_find_target_node(struct collapse_control *cc)/* * If mmap_lock temporarily dropped, revalidate vma -* before taking mmap_lock. +* after taking the mmap_lock again. * Returns enum scan_result value. */ static enum scan_result hugepage_vma_revalidate (struct mm_struct *mm,unsigned long address, -bool expect_anon,struct vm_area_struct **vmap,struct collapse_control *cc) +bool expect_anon,struct vm_area_struct **vmap, +struct collapse_control *cc,unsigned int order) {struct vm_area_struct *vma; enum tva_type type = cc->is_khugepaged ? TVA_KHUGEPAGED :
@@ -923,15 +924,22 @@ static enum scan_result hugepage_vma_revalidate(struct mm_struct *mm, unsigned lif (!vma)return SCAN_VMA_NULL ; +/* +* We cannot collapse VMA regions that do not span the full PMD. This is +* due to the potential of the PMD being shared by another VMA leaving +* us vulnerable to a race condition. Always check the PMD order here to +* ensure its not shared by another VMA. We'd need to lock all VMAs in +* the PMD range to support this. +*/ if (!thp_vma_suitable_order (vma, address,PMD_ORDER ))return SCAN_ADDRESS_RANGE ; -if (!thp_vma_allowable_order (vma, vma->vm_flags, type,PMD_ORDER )) +if (!thp_vma_allowable_orders (vma, vma->vm_flags, type,BIT (order)))return SCAN_VMA_CHECK ;/* * Anon VMA expected, the address may be unmapped then * remapped to file after khugepaged reaquired the mmap_lock. * -* thp_vma_allowable_order may return true for qualified file +* thp_vma_allowable_orders may return true for qualified file * vmas. */ if (expect_anon && (!(*vmap)->anon_vma || !vma_is_anonymous (*vmap)))
@@ -1124,7 +1132,8 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a goto out_nolock;mmap_read_lock (mm); - result =hugepage_vma_revalidate (mm, address, true, &vma, cc); + result =hugepage_vma_revalidate (mm, address, true, &vma, cc, +HPAGE_PMD_ORDER );if (result !=SCAN_SUCCEED ) {mmap_read_unlock (mm); goto out_nolock;
@@ -1158,7 +1167,8 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* mmap_lock. */ mmap_write_lock (mm); - result =hugepage_vma_revalidate (mm, address, true, &vma, cc); + result =hugepage_vma_revalidate (mm, address, true, &vma, cc, +HPAGE_PMD_ORDER );if (result !=SCAN_SUCCEED ) goto out_up_write;/* check if the pmd is still valid */
@@ -2861,8 +2871,8 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start, mmap_unlocked = false; *lock_dropped = true; result =hugepage_vma_revalidate (mm, addr, false, &vma, - cc); -if (result !=SCAN_SUCCEED ) { + cc,HPAGE_PMD_ORDER ); +if (result !=SCAN_SUCCEED ) { last_fail = result; goto out_nolock; }
Signature · 1 line
2.54.0
PATCH v19 2/14 mm/khugepaged: generalize alloc_charge_folio()
In reply to Nico PacheFrom: Dev Jain <[email protected]>
Pass order to alloc_charge_folio() and update mTHP statistics.
--- Documentation/admin-guide/mm/transhuge.rst | 8 ++++++++ include/linux/huge_mm.h | 2 ++ mm/huge_memory.c | 4 ++++ mm/khugepaged.c | 20 +++++++++++++------- 4 files changed, 27 insertions(+), 7 deletions(-)
Documentation/admin-guide/mm/transhuge.rst +8 -0
@@ -639,6 +639,14 @@ anon_fault_fallback_charge instead falls back to using huge pages with lower orders or small pages even though the allocation was successful. +collapse_alloc + is incremented every time a huge page is successfully allocated for a + khugepaged collapse. + +collapse_alloc_failed + is incremented every time a huge page allocation fails during a + khugepaged collapse. + zswpout is incremented every time a huge page is swapped out to zswap in one piece without splitting.
include/linux/huge_mm.h +2 -0
@@ -128,6 +128,8 @@ enum mthp_stat_item {MTHP_STAT_ANON_FAULT_ALLOC ,MTHP_STAT_ANON_FAULT_FALLBACK ,MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE , +MTHP_STAT_COLLAPSE_ALLOC , +MTHP_STAT_COLLAPSE_ALLOC_FAILED ,MTHP_STAT_ZSWPOUT ,MTHP_STAT_SWPIN , MTHP_STAT_SWPIN_FALLBACK,
mm/huge_memory.c +4 -0
@@ -699,6 +699,8 @@ static struct kobj_attribute _name##_attr = __ATTR_RO(_name)DEFINE_MTHP_STAT_ATTR (anon_fault_alloc,MTHP_STAT_ANON_FAULT_ALLOC );DEFINE_MTHP_STAT_ATTR (anon_fault_fallback,MTHP_STAT_ANON_FAULT_FALLBACK );DEFINE_MTHP_STAT_ATTR (anon_fault_fallback_charge,MTHP_STAT_ANON_FAULT_FALLBACK_CHARGE ); +DEFINE_MTHP_STAT_ATTR (collapse_alloc,MTHP_STAT_COLLAPSE_ALLOC ); +DEFINE_MTHP_STAT_ATTR (collapse_alloc_failed,MTHP_STAT_COLLAPSE_ALLOC_FAILED );DEFINE_MTHP_STAT_ATTR (zswpout,MTHP_STAT_ZSWPOUT );DEFINE_MTHP_STAT_ATTR (swpin,MTHP_STAT_SWPIN );DEFINE_MTHP_STAT_ATTR (swpin_fallback,MTHP_STAT_SWPIN_FALLBACK );
@@ -764,6 +766,8 @@ static struct attribute *any_stats_attrs[] = {#endif &split_attr.attr, &split_failed_attr.attr, + &collapse_alloc_attr.attr, + &collapse_alloc_failed_attr.attr, NULL, };
mm/khugepaged.c +13 -7
@@ -1077,28 +1077,34 @@ static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm, }static enum scan_result alloc_charge_folio (struct folio **foliop,struct mm_struct *mm, -struct collapse_control *cc) +struct collapse_control *cc,unsigned int order) {gfp_t gfp = (cc->is_khugepaged ?alloc_hugepage_khugepaged_gfpmask () :GFP_TRANSHUGE );int node =collapse_find_target_node (cc);struct folio *folio; - folio =__folio_alloc (gfp,HPAGE_PMD_ORDER , node, &cc->alloc_nmask); + folio =__folio_alloc (gfp, order, node, &cc->alloc_nmask);if (!folio) { *foliop =NULL ; -count_vm_event (THP_COLLAPSE_ALLOC_FAILED ); +if (is_pmd_order (order)) +count_vm_event (THP_COLLAPSE_ALLOC_FAILED ); +count_mthp_stat (order,MTHP_STAT_COLLAPSE_ALLOC_FAILED );return SCAN_ALLOC_HUGE_PAGE_FAIL ; } -count_vm_event (THP_COLLAPSE_ALLOC ); +if (is_pmd_order (order)) +count_vm_event (THP_COLLAPSE_ALLOC ); +count_mthp_stat (order,MTHP_STAT_COLLAPSE_ALLOC ); +if (unlikely (mem_cgroup_charge (folio, mm, gfp))) {folio_put (folio); *foliop =NULL ;return SCAN_CGROUP_CHARGE_FAIL ; } -count_memcg_folio_events (folio,THP_COLLAPSE_ALLOC ,1 ); +if (is_pmd_order (order)) +count_memcg_folio_events (folio,THP_COLLAPSE_ALLOC ,1 ); *foliop = folio;return SCAN_SUCCEED ;
@@ -1127,7 +1133,7 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a*/ mmap_read_unlock (mm); - result =alloc_charge_folio (&folio, mm, cc); + result =alloc_charge_folio (&folio, mm, cc,HPAGE_PMD_ORDER );if (result !=SCAN_SUCCEED ) goto out_nolock;
@@ -1908,7 +1914,7 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,VM_BUG_ON (!IS_ENABLED (CONFIG_READ_ONLY_THP_FOR_FS ) && !is_shmem);VM_BUG_ON (start & (HPAGE_PMD_NR -1 )); - result =alloc_charge_folio (&new_folio, mm, cc); + result =alloc_charge_folio (&new_folio, mm, cc,HPAGE_PMD_ORDER );if (result !=SCAN_SUCCEED ) goto out;
Signature · 1 line
2.54.0
PATCH v19 3/14 mm/khugepaged: rework max_ptes_* handling with helper functions
In reply to Nico PacheThe following cleanup reworks all the max_ptes_* handling into helper functions. This increases the code readability and will later be used to implement the mTHP handling of these variables.
With these changes we abstract all the madvise_collapse() special casing (do not respect the sysctls) away from the functions that utilize them. And will be used later in this series to cleanly restrict the mTHP collapse behavior.
No functional change is intended; however, we are now only reading the sysfs variables once per scan, whereas before these variables were being read on each loop iteration.
--- mm/khugepaged.c | 120 +++++++++++++++++++++++++++++++++--------------- 1 file changed, 84 insertions(+), 36 deletions(-)
mm/khugepaged.c +84 -36
@@ -348,6 +348,64 @@ static bool pte_none_or_zero(pte_t pte)return pte_present (pte) &&is_zero_pfn (pte_pfn (pte)); } +/** +* collapse_max_ptes_none - Calculate maximum allowed empty PTEs or PTEs mapping +* the shared zeropage for the given collapse operation. +* @cc: The collapse control struct +* @vma: The vma to check for userfaultfd +* +* Return: Maximum number of empty/shared zeropage PTEs for the collapse operation +*/ +static unsigned int collapse_max_ptes_none (struct collapse_control *cc, +struct vm_area_struct *vma) +{ +if (vma &&userfaultfd_armed (vma)) +return 0 ; +/* for MADV_COLLAPSE, allow any empty/shared zeropage PTEs */ +if (!cc->is_khugepaged) +return HPAGE_PMD_NR ; +/* For all other cases respect the user defined maximum */ +return khugepaged_max_ptes_none; +} + +/** +* collapse_max_ptes_shared - Calculate maximum allowed PTEs that map shared +* anonymous pages for the given collapse operation. +* @cc: The collapse control struct +* +* Return: Maximum number of PTEs that map shared anonymous pages for the +* collapse operation +*/ +static unsigned int collapse_max_ptes_shared (struct collapse_control *cc) +{ +/* +* For MADV_COLLAPSE, do not restrict the number of PTEs that map shared +* anonymous pages. +*/ +if (!cc->is_khugepaged) +return HPAGE_PMD_NR ; +return khugepaged_max_ptes_shared; +} + +/** +* collapse_max_ptes_swap - Calculate the maximum allowed non-present PTEs or the +* maximum allowed non-present pagecache entries for the given collapse operation. +* @cc: The collapse control struct +* +* Return: Maximum number of non-present PTEs or the maximum allowed non-present +* pagecache entries for the collapse operation. +*/ +static unsigned int collapse_max_ptes_swap (struct collapse_control *cc) +{ +/* +* For MADV_COLLAPSE, do not restrict the number PTEs entries or +* pagecache entries that are non-present. +*/ +if (!cc->is_khugepaged) +return HPAGE_PMD_NR ; +return khugepaged_max_ptes_swap; +} +int hugepage_madvise (struct vm_area_struct *vma,vm_flags_t *vm_flags,int advice) {
@@ -543,6 +601,8 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma, unsigned long start_addr, pte_t *pte, struct collapse_control *cc, struct list_head *compound_pagelist) { + const unsigned int max_ptes_none = collapse_max_ptes_none(cc, vma); +const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc);struct page *page =NULL ;struct folio *folio =NULL ;unsigned long addr = start_addr;
@@ -554,16 +614,12 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma, _pte++, addr += PAGE_SIZE) {pte_t pteval =ptep_get (_pte);if (pte_none_or_zero (pteval)) { - ++none_or_zero; -if (!userfaultfd_armed (vma) && - (!cc->is_khugepaged || - none_or_zero <= khugepaged_max_ptes_none)) { -continue ; - }else { +if (++none_or_zero > max_ptes_none) { result =SCAN_EXCEED_NONE_PTE ;count_vm_event (THP_SCAN_EXCEED_NONE_PTE ); goto out; } +continue ; }if (!pte_present (pteval)) { result =SCAN_PTE_NON_PRESENT ;
@@ -594,9 +650,7 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,/* See collapse_scan_pmd(). */ if (folio_maybe_mapped_shared (folio)) { - ++shared; -if (cc->is_khugepaged && - shared > khugepaged_max_ptes_shared) { +if (++shared > max_ptes_shared) { result =SCAN_EXCEED_SHARED_PTE ;count_vm_event (THP_SCAN_EXCEED_SHARED_PTE ); goto out;
@@ -1271,6 +1325,9 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long start_addr, bool *lock_dropped, struct collapse_control *cc) { + const unsigned int max_ptes_none = collapse_max_ptes_none(cc, vma); +const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc); +const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc);pmd_t *pmd;pte_t *pte, *_pte;int none_or_zero =0 , shared =0 , referenced =0 ;
@@ -1304,36 +1361,29 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,pte_t pteval =ptep_get (_pte);if (pte_none_or_zero (pteval)) { - ++none_or_zero; -if (!userfaultfd_armed (vma) && - (!cc->is_khugepaged || - none_or_zero <= khugepaged_max_ptes_none)) { -continue ; - }else { +if (++none_or_zero > max_ptes_none) { result =SCAN_EXCEED_NONE_PTE ;count_vm_event (THP_SCAN_EXCEED_NONE_PTE ); goto out_unmap; } +continue ; }if (!pte_present (pteval)) { - ++unmapped; -if (!cc->is_khugepaged || - unmapped <= khugepaged_max_ptes_swap) { -/* -* Always be strict with uffd-wp -* enabled swap entries. Please see -* comment below for pte_uffd_wp(). -*/ -if (pte_swp_uffd_wp_any (pteval)) { - result =SCAN_PTE_UFFD_WP ; - goto out_unmap; - } -continue ; - }else { +if (++unmapped > max_ptes_swap) { result =SCAN_EXCEED_SWAP_PTE ;count_vm_event (THP_SCAN_EXCEED_SWAP_PTE ); goto out_unmap; } +/* +* Always be strict with uffd-wp +* enabled swap entries. Please see +* comment below for pte_uffd_wp(). +*/ +if (pte_swp_uffd_wp_any (pteval)) { + result =SCAN_PTE_UFFD_WP ; + goto out_unmap; + } +continue ; }if (pte_uffd_wp (pteval)) {/*
@@ -1376,9 +1426,7 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,* is shared. */ if (folio_maybe_mapped_shared (folio)) { - ++shared; -if (cc->is_khugepaged && - shared > khugepaged_max_ptes_shared) { +if (++shared > max_ptes_shared) { result =SCAN_EXCEED_SHARED_PTE ;count_vm_event (THP_SCAN_EXCEED_SHARED_PTE ); goto out_unmap;
@@ -2333,6 +2381,8 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm, unsigned long addr, struct file *file, pgoff_t start, struct collapse_control *cc) { + const unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL); +const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc);struct folio *folio =NULL ;struct address_space *mapping = file->f_mapping;XA_STATE (xas, &mapping->i_pages, start);
@@ -2351,8 +2401,7 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,if (xa_is_value (folio)) { swap +=1 <<xas_get_order (&xas); -if (cc->is_khugepaged && - swap > khugepaged_max_ptes_swap) { +if (swap > max_ptes_swap) { result =SCAN_EXCEED_SWAP_PTE ;count_vm_event (THP_SCAN_EXCEED_SWAP_PTE );break ;
@@ -2423,8 +2472,7 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm, cc->progress +=HPAGE_PMD_NR ;if (result ==SCAN_SUCCEED ) { -if (cc->is_khugepaged && - present <HPAGE_PMD_NR - khugepaged_max_ptes_none) { +if (present <HPAGE_PMD_NR - max_ptes_none) { result =SCAN_EXCEED_NONE_PTE ;count_vm_event (THP_SCAN_EXCEED_NONE_PTE ); }else {
Signature · 1 line
2.54.0
PATCH v19 4/14 mm/khugepaged: generalize __collapse_huge_page_* for mTHP support
In reply to Nico Pachegeneralize the order of the __collapse_huge_page_* and collapse_max_* functions to support future mTHP collapse.
The current mechanism for determining collapse with the khugepaged_max_ptes_none value is not designed with mTHP in mind. This raises a key design issue: if we support user defined max_pte_none values (even those scaled by order), a collapse of a lower order can introduces an feedback loop, or "creep", when max_ptes_none is set to a value greater than HPAGE_PMD_NR / 2. [1]
With this configuration, a successful collapse to order N will populate enough pages to satisfy the collapse condition on order N+1 on the next scan. This leads to unnecessary work and memory churn.
To fix this issue introduce a helper function that will limit mTHP collapse support to two max_ptes_none values, 0 and HPAGE_PMD_NR - 1. This effectively supports two modes: [2]
- max_ptes_none=0: never collapses if it encounters an empty PTE or a PTE that maps the shared zeropage. Consequently, no memory bloat.
- max_ptes_none=511 (on 4k pagesz): Always collapse to the highest available mTHP order.
This removes the possibility of "creep", and a warning will be emitted if any non-supported max_ptes_none value is configured with mTHP enabled. Any intermediate value will default mTHP collapse to max_ptes_none=0.
mTHP collapse will not honor the khugepaged_max_ptes_shared or khugepaged_max_ptes_swap parameters, and will fail if it encounters a shared or swapped entry.
No functional changes in this patch; however it defines future behavior for mTHP collapse.
[1] - https://lore.kernel.org/all/[email protected]
[2] - https://lore.kernel.org/all/[email protected]
--- mm/khugepaged.c | 126 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 93 insertions(+), 33 deletions(-)
mm/khugepaged.c +93 -33
@@ -353,30 +353,51 @@ static bool pte_none_or_zero(pte_t pte)* the shared zeropage for the given collapse operation. * @cc: The collapse control struct * @vma: The vma to check for userfaultfd +* @order: The folio order being collapsed to * * Return: Maximum number of empty/shared zeropage PTEs for the collapse operation */ static unsigned int collapse_max_ptes_none (struct collapse_control *cc, -struct vm_area_struct *vma) +struct vm_area_struct *vma,unsigned int order) { +const unsigned int max_ptes_none = khugepaged_max_ptes_none; +if (vma &&userfaultfd_armed (vma))return 0 ;/* for MADV_COLLAPSE, allow any empty/shared zeropage PTEs */ if (!cc->is_khugepaged)return HPAGE_PMD_NR ; -/* For all other cases respect the user defined maximum */ -return khugepaged_max_ptes_none; +/* for PMD collapse, respect the user defined maximum */ +if (is_pmd_order (order)) +return max_ptes_none; +/* +* for mTHP collapse with the sysctl value set to KHUGEPAGED_MAX_PTES_LIMIT, +* scale the maximum number of PTEs to the order of the collapse. +*/ +if (max_ptes_none ==KHUGEPAGED_MAX_PTES_LIMIT ) +return (1 << order) -1 ; +/* +* For mTHP collapse of values other than 0 or KHUGEPAGED_MAX_PTES_LIMIT, +* emit a warning and return 0. +*/ +if (max_ptes_none) +pr_warn_once ("mTHP collapse does not support max_ptes_none" +" values other than 0 or %u, defaulting to 0.\n" , +KHUGEPAGED_MAX_PTES_LIMIT ); +return 0 ; }/** * collapse_max_ptes_shared - Calculate maximum allowed PTEs that map shared * anonymous pages for the given collapse operation. * @cc: The collapse control struct +* @order: The folio order being collapsed to * * Return: Maximum number of PTEs that map shared anonymous pages for the * collapse operation */ -static unsigned int collapse_max_ptes_shared (struct collapse_control *cc) +static unsigned int collapse_max_ptes_shared (struct collapse_control *cc, +unsigned int order) {/* * For MADV_COLLAPSE, do not restrict the number of PTEs that map shared
@@ -384,6 +405,13 @@ static unsigned int collapse_max_ptes_shared(struct collapse_control *cc)*/ if (!cc->is_khugepaged)return HPAGE_PMD_NR ; +/* +* for mTHP collapse do not allow collapsing anonymous memory pages that +* are shared between processes. +*/ +if (!is_pmd_order (order)) +return 0 ; +/* for PMD collapse, respect the user defined maximum */ return khugepaged_max_ptes_shared; }
@@ -391,11 +419,13 @@ static unsigned int collapse_max_ptes_shared(struct collapse_control *cc)* collapse_max_ptes_swap - Calculate the maximum allowed non-present PTEs or the * maximum allowed non-present pagecache entries for the given collapse operation. * @cc: The collapse control struct +* @order: The folio order being collapsed to * * Return: Maximum number of non-present PTEs or the maximum allowed non-present * pagecache entries for the collapse operation. */ -static unsigned int collapse_max_ptes_swap (struct collapse_control *cc) +static unsigned int collapse_max_ptes_swap (struct collapse_control *cc, +unsigned int order) {/* * For MADV_COLLAPSE, do not restrict the number PTEs entries or
@@ -403,6 +433,10 @@ static unsigned int collapse_max_ptes_swap(struct collapse_control *cc)*/ if (!cc->is_khugepaged)return HPAGE_PMD_NR ; +/* for mTHP collapse do not allow any non-present PTEs or pagecache entries */ +if (!is_pmd_order (order)) +return 0 ; +/* for PMD collapse, respect the user defined maximum */ return khugepaged_max_ptes_swap; }
@@ -599,10 +633,11 @@ static void release_pte_pages(pte_t *pte, pte_t *_pte,static enum scan_result __collapse_huge_page_isolate (struct vm_area_struct *vma,unsigned long start_addr,pte_t *pte,struct collapse_control *cc, -struct list_head *compound_pagelist) +unsigned int order,struct list_head *compound_pagelist) { -const unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma); -const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc); +const unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma, order); +const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc, order); +const unsigned long nr_pages =1UL << order;struct page *page =NULL ;struct folio *folio =NULL ;unsigned long addr = start_addr;
@@ -610,7 +645,7 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,int none_or_zero =0 , shared =0 , referenced =0 ;enum scan_result result =SCAN_FAIL ; -for (_pte = pte; _pte < pte +HPAGE_PMD_NR ; +for (_pte = pte; _pte < pte + nr_pages; _pte++, addr +=PAGE_SIZE ) {pte_t pteval =ptep_get (_pte);if (pte_none_or_zero (pteval)) {
@@ -650,6 +685,12 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,/* See collapse_scan_pmd(). */ if (folio_maybe_mapped_shared (folio)) { +/* +* TODO: Support shared pages without leading to further +* mTHP collapses. Currently bringing in new pages via +* shared may cause a future higher order collapse on a +* rescan of the same range. +*/ if (++shared > max_ptes_shared) { result =SCAN_EXCEED_SHARED_PTE ;count_vm_event (THP_SCAN_EXCEED_SHARED_PTE );
@@ -743,18 +784,18 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma, }static void __collapse_huge_page_copy_succeeded (pte_t *pte, -struct vm_area_struct *vma, -unsigned long address, -spinlock_t *ptl, -struct list_head *compound_pagelist) +struct vm_area_struct *vma,unsigned long address, +spinlock_t *ptl,unsigned int order, +struct list_head *compound_pagelist) { -unsigned long end = address +HPAGE_PMD_SIZE ; +const unsigned long nr_pages =1UL << order; +unsigned long end = address + (PAGE_SIZE * nr_pages);struct folio *src, *tmp;pte_t pteval;pte_t *_pte;unsigned int nr_ptes; -for (_pte = pte; _pte < pte +HPAGE_PMD_NR ; _pte += nr_ptes, +for (_pte = pte; _pte < pte + nr_pages; _pte += nr_ptes, address += nr_ptes *PAGE_SIZE ) { nr_ptes =1 ; pteval =ptep_get (_pte);
@@ -807,11 +848,10 @@ static void __collapse_huge_page_copy_succeeded(pte_t *pte, }static void __collapse_huge_page_copy_failed (pte_t *pte, -pmd_t *pmd, -pmd_t orig_pmd, -struct vm_area_struct *vma, -struct list_head *compound_pagelist) +pmd_t *pmd,pmd_t orig_pmd,struct vm_area_struct *vma, +unsigned int order,struct list_head *compound_pagelist) { +const unsigned long nr_pages =1UL << order;spinlock_t *pmd_ptl;/*
@@ -827,7 +867,7 @@ static void __collapse_huge_page_copy_failed(pte_t *pte,* Release both raw and compound pages isolated * in __collapse_huge_page_isolate. */ -release_pte_pages (pte, pte +HPAGE_PMD_NR , compound_pagelist); +release_pte_pages (pte, pte + nr_pages, compound_pagelist); }/*
@@ -847,16 +887,17 @@ static void __collapse_huge_page_copy_failed(pte_t *pte,*/ static enum scan_result __collapse_huge_page_copy (pte_t *pte,struct folio *folio,pmd_t *pmd,pmd_t orig_pmd,struct vm_area_struct *vma, -unsigned long address,spinlock_t *ptl, +unsigned long address,spinlock_t *ptl,unsigned int order,struct list_head *compound_pagelist) { +const unsigned long nr_pages =1UL << order;unsigned int i;enum scan_result result =SCAN_SUCCEED ;/* * Copying pages' contents is subject to memory poison at any iteration. */ -for (i =0 ; i <HPAGE_PMD_NR ; i++) { +for (i =0 ; i < nr_pages; i++) {pte_t pteval =ptep_get (pte + i);struct page *page =folio_page (folio, i);unsigned long src_addr = address + i *PAGE_SIZE ;
@@ -875,10 +916,10 @@ static enum scan_result __collapse_huge_page_copy(pte_t *pte, struct folio *foliif (likely (result ==SCAN_SUCCEED ))__collapse_huge_page_copy_succeeded (pte, vma, address, ptl, - compound_pagelist); + order, compound_pagelist);else __collapse_huge_page_copy_failed (pte, pmd, orig_pmd, vma, - compound_pagelist); + order, compound_pagelist);return result; }
@@ -1051,16 +1092,20 @@ static enum scan_result check_pmd_still_valid(struct mm_struct *mm,* Bring missing pages in from swap, to complete THP collapse. * Only done if khugepaged_scan_pmd believes it is worthwhile. * +* For mTHP orders the function bails on the first swap entry, because +* faulting pages back in during collapse could re-populate PTEs that +* push a later scan over the threshold for a higher-order collapse. +* * Called and returns without pte mapped or spinlocks held. * Returns result: if not SCAN_SUCCEED, mmap_lock has been released. */ static enum scan_result __collapse_huge_page_swapin (struct mm_struct *mm, -struct vm_area_struct *vma,unsigned long start_addr,pmd_t *pmd, -int referenced) +struct vm_area_struct *vma,unsigned long start_addr, +pmd_t *pmd,int referenced,unsigned int order) {int swapped_in =0 ;vm_fault_t ret =0 ; -unsigned long addr, end = start_addr + (HPAGE_PMD_NR *PAGE_SIZE ); +unsigned long addr, end = start_addr + (PAGE_SIZE << order);enum scan_result result;pte_t *pte =NULL ;spinlock_t *ptl;
@@ -1092,6 +1137,19 @@ static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm, pte_present(vmf.orig_pte))continue ; +/* +* TODO: Support swapin without leading to further mTHP +* collapses. Currently bringing in new pages via swapin may +* cause a future higher order collapse on a rescan of the same +* range. +*/ +if (!is_pmd_order (order)) { +pte_unmap (pte); +mmap_read_unlock (mm); + result =SCAN_EXCEED_SWAP_PTE ; + goto out; + } + vmf.pte = pte; vmf.ptl = ptl; ret =do_swap_page (&vmf);
@@ -1212,7 +1270,7 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* that case. Continuing to collapse causes inconsistency. */ result =__collapse_huge_page_swapin (mm, vma, address, pmd, - referenced); + referenced,HPAGE_PMD_ORDER );if (result !=SCAN_SUCCEED ) goto out_nolock; }
@@ -1260,6 +1318,7 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a pte =pte_offset_map_lock (mm, &_pmd, address, &pte_ptl);if (pte) { result =__collapse_huge_page_isolate (vma, address, pte, cc, +HPAGE_PMD_ORDER , &compound_pagelist);spin_unlock (pte_ptl); }else {
@@ -1290,6 +1349,7 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a result =__collapse_huge_page_copy (pte, folio, pmd, _pmd, vma, address, pte_ptl, +HPAGE_PMD_ORDER , &compound_pagelist);pte_unmap (pte);if (unlikely (result !=SCAN_SUCCEED ))
@@ -1325,9 +1385,9 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, struct vm_area_struct *vma, unsigned long start_addr, bool *lock_dropped, struct collapse_control *cc) { - const unsigned int max_ptes_none = collapse_max_ptes_none(cc, vma); -const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc); -const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc); + const unsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER); +const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc,HPAGE_PMD_ORDER ); +const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc,HPAGE_PMD_ORDER );pmd_t *pmd;pte_t *pte, *_pte;int none_or_zero =0 , shared =0 , referenced =0 ;
@@ -2381,8 +2441,8 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm, unsigned long addr, struct file *file, pgoff_t start, struct collapse_control *cc) { - const unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL); -const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc); + const unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, HPAGE_PMD_ORDER); +const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc,HPAGE_PMD_ORDER );struct folio *folio =NULL ;struct address_space *mapping = file->f_mapping;XA_STATE (xas, &mapping->i_pages, start);
Signature · 1 line
2.54.0
Re: [PATCH mm-unstable v19 04/14] mm/khugepaged: generalize __collapse_huge_page_* for mTHP support
Quoted 43 lines · Nico Pache
generalize the order of the __collapse_huge_page_* and collapse_max_* functions to support future mTHP collapse.
The current mechanism for determining collapse with the
khugepaged_max_ptes_nonevalue is not designed with mTHP in mind. This raises a key design issue: if we support user definedmax_pte_nonevalues (even those scaled by order), a collapse of a lower order can introduces an feedback loop, or "creep", whenmax_ptes_noneis set to a value greater thanHPAGE_PMD_NR/ 2. [1]With this configuration, a successful collapse to order N will populate enough pages to satisfy the collapse condition on order N+1 on the next scan. This leads to unnecessary work and memory churn.
To fix this issue introduce a helper function that will limit mTHP collapse support to two
max_ptes_nonevalues, 0 andHPAGE_PMD_NR- 1. This effectively supports two modes: [2]- max_ptes_none=0: never collapses if it encounters an empty PTE or a PTE that maps the shared zeropage. Consequently, no memory bloat.
- max_ptes_none=511 (on 4k pagesz): Always collapse to the highest available mTHP order.This removes the possibility of "creep", and a warning will be emitted if any non-supported
max_ptes_nonevalue is configured with mTHP enabled. Any intermediate value will default mTHP collapse to max_ptes_none=0.mTHP collapse will not honor the
khugepaged_max_ptes_sharedorkhugepaged_max_ptes_swapparameters, and will fail if it encounters a shared or swapped entry.No functional changes in this patch; however it defines future behavior for mTHP collapse.
[1] - https://lore.kernel.org/all/[email protected]
[2] - https://lore.kernel.org/all/[email protected]Reviewed-by Lorenzo Stoakes <[email protected]>Reviewed-by Lance Yang <[email protected]>Co-developed-by Dev Jain <[email protected]>Signed-off-by Dev Jain <[email protected]>Signed-off-by Nico Pache <[email protected]>
Quoted 4 lines
--- mm/khugepaged.c | 126 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 93 insertions(+), 33 deletions(-)
LGTM.
Best Regards,
Yan, Zi
PATCH v19 5/14 mm/khugepaged: require collapse_huge_page to enter/exit with the lock dropped
In reply to Nico PacheCurrently the collapse_huge_page function requires the mmap_read_lock to enter with it held, and exit with it dropped. This function moves the unlock into its parent caller, and changes this semantic to requiring it to enter/exit with it always unlocked.
In future patches, we need this expectation, as for in mTHP collapse, we may have already dropped the lock, and do not want to conditionally check for this by passing through the lock_dropped variable.
No functional change is expected as one of the first things the collapse_huge_page function does is drop this lock before allocating the hugepage.
--- mm/khugepaged.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)
mm/khugepaged.c +8 -8
@@ -1222,6 +1222,12 @@ static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_strureturn SCAN_SUCCEED ; } +/* +* collapse_huge_page expects the mmap_lock to be unlocked before entering and +* will always return with the lock unlocked, to avoid holding the mmap_lock +* while allocating a THP, as that could trigger direct reclaim/compaction. +* Note that the VMA must be rechecked after grabbing the mmap_lock again. +*/ static enum scan_result collapse_huge_page (struct mm_struct *mm,unsigned long address,int referenced,int unmapped,struct collapse_control *cc) {
@@ -1237,14 +1243,6 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long aVM_BUG_ON (address & ~HPAGE_PMD_MASK ); -/* -* Before allocating the hugepage, release the mmap_lock read lock. -* The allocation can take potentially a long time if it involves -* sync compaction, and we do not need to hold the mmap_lock during -* that. We will recheck the vma after taking it again in write mode. -*/ -mmap_read_unlock (mm); - result =alloc_charge_folio (&folio, mm, cc,HPAGE_PMD_ORDER );if (result !=SCAN_SUCCEED ) goto out_nolock;
@@ -1549,6 +1547,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, out_unmap:pte_unmap_unlock (pte, ptl);if (result ==SCAN_SUCCEED ) { +/* collapse_huge_page expects the lock to be dropped before calling */ +mmap_read_unlock (mm); result =collapse_huge_page (mm, start_addr, referenced, unmapped, cc);/* collapse_huge_page will return with the mmap_lock released */
Signature · 1 line
2.54.0
Re: [PATCH mm-unstable v19 05/14] mm/khugepaged: require collapse_huge_page to enter/exit with the lock dropped
Quoted 13 lines · Nico Pache
Currently the
collapse_huge_pagefunction requires themmap_read_lockto enter with it held, and exit with it dropped. This function moves the unlock into its parent caller, and changes this semantic to requiring it to enter/exit with it always unlocked.In future patches, we need this expectation, as for in mTHP collapse, we may have already dropped the lock, and do not want to conditionally check for this by passing through the
lock_droppedvariable.No functional change is expected as one of the first things the
collapse_huge_pagefunction does is drop this lock before allocating the hugepage.
Quoted 7 lines
Reviewed-by Lorenzo Stoakes <[email protected]>Signed-off-by Nico Pache <[email protected]>--- mm/khugepaged.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-)
LGTM.
Best Regards,
Yan, Zi
Re: [PATCH mm-unstable v19 05/14] mm/khugepaged: require collapse_huge_page to enter/exit with the lock dropped
In reply to Nico PacheQuoted 9 lines · Nico Pache
Currently the
collapse_huge_pagefunction requires themmap_read_lockto enter with it held, and exit with it dropped. This function moves the unlock into its parent caller, and changes this semantic to requiring it to enter/exit with it always unlocked.In future patches, we need this expectation, as for in mTHP collapse, we may have already dropped the lock, and do not want to conditionally check for this by passing through the
lock_droppedvariable.
Quoted 8 lines
No functional change is expected as one of the first things the
collapse_huge_pagefunction does is drop this lock before allocating the hugepage.Reviewed-by Lorenzo Stoakes <[email protected]>Signed-off-by Nico Pache <[email protected]>---
PATCH v19 6/14 mm/khugepaged: generalize collapse_huge_page for mTHP collapse
In reply to Nico PachePass an order to collapse_huge_page to support collapsing anon memory to arbitrary orders within a PMD. order indicates what mTHP size we are attempting to collapse to.
For non-PMD collapse we must leave the anon VMA write locked until after we collapse the mTHP-- in the PMD case all the pages are isolated, but in the mTHP case this is not true, and we must keep the lock to prevent access/changes to the page tables. This can happen if the rmap walkers hit a pmd_none while the PMD entry is currently unavailable due to being temporarily removed during the collapse phase.
To properly establish the page table hierarchy without violating any expectations from certain architectures (e.g. MIPS), we must make sure to have the PMD reinstalled before the PTEs, and hold both PTE/PMD locks before calling update_mmu_cache_range() (if they are distinct locks).
--- mm/khugepaged.c | 105 ++++++++++++++++++++++++++++++------------------ 1 file changed, 67 insertions(+), 38 deletions(-)
mm/khugepaged.c +67 -38
@@ -1228,34 +1228,36 @@ static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_stru* while allocating a THP, as that could trigger direct reclaim/compaction. * Note that the VMA must be rechecked after grabbing the mmap_lock again. */ -static enum scan_result collapse_huge_page (struct mm_struct *mm,unsigned long address, -int referenced,int unmapped,struct collapse_control *cc) +static enum scan_result collapse_huge_page (struct mm_struct *mm,unsigned long start_addr, +int referenced,int unmapped,struct collapse_control *cc, +unsigned int order) { +const unsigned long pmd_addr = start_addr &HPAGE_PMD_MASK ; +const unsigned long end_addr = start_addr + (PAGE_SIZE << order);LIST_HEAD (compound_pagelist);pmd_t *pmd, _pmd; -pte_t *pte; +pte_t *pte =NULL ;pgtable_t pgtable;struct folio *folio;spinlock_t *pmd_ptl, *pte_ptl;enum scan_result result =SCAN_FAIL ;struct vm_area_struct *vma;struct mmu_notifier_range range; +bool anon_vma_locked = false; -VM_BUG_ON (address & ~HPAGE_PMD_MASK ); - - result =alloc_charge_folio (&folio, mm, cc,HPAGE_PMD_ORDER ); + result =alloc_charge_folio (&folio, mm, cc, order);if (result !=SCAN_SUCCEED ) goto out_nolock;mmap_read_lock (mm); - result =hugepage_vma_revalidate (mm, address, true, &vma, cc, -HPAGE_PMD_ORDER ); + result =hugepage_vma_revalidate (mm, pmd_addr,/*expect_anon=*/ true, + &vma, cc, order);if (result !=SCAN_SUCCEED ) {mmap_read_unlock (mm); goto out_nolock; } - result =find_pmd_or_thp_or_none (mm, address, &pmd); + result =find_pmd_or_thp_or_none (mm, pmd_addr, &pmd);if (result !=SCAN_SUCCEED ) {mmap_read_unlock (mm); goto out_nolock;
@@ -1267,8 +1269,8 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* released when it fails. So we jump out_nolock directly in * that case. Continuing to collapse causes inconsistency. */ - result =__collapse_huge_page_swapin (mm, vma, address, pmd, - referenced,HPAGE_PMD_ORDER ); + result =__collapse_huge_page_swapin (mm, vma, start_addr, pmd, + referenced, order);if (result !=SCAN_SUCCEED ) goto out_nolock; }
@@ -1283,20 +1285,28 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* mmap_lock. */ mmap_write_lock (mm); - result =hugepage_vma_revalidate (mm, address, true, &vma, cc, -HPAGE_PMD_ORDER ); + result =hugepage_vma_revalidate (mm, pmd_addr,/*expect_anon=*/ true, + &vma, cc, order);if (result !=SCAN_SUCCEED ) goto out_up_write;/* check if the pmd is still valid */ vma_start_write (vma); - result =check_pmd_still_valid (mm, address, pmd); + result =check_pmd_still_valid (mm, pmd_addr, pmd);if (result !=SCAN_SUCCEED ) goto out_up_write;anon_vma_lock_write (vma->anon_vma); + anon_vma_locked = true; -mmu_notifier_range_init (&range,MMU_NOTIFY_CLEAR ,0 , mm, address, - address +HPAGE_PMD_SIZE ); +/* +* Only notify about the PTE range we will actually modify. While we +* temporary unmap the whole PTE table for mTHP collapse, we'll remap +* it later, leaving other PTEs effectively unmodified. The locks we +* hold prevent anybody from stumbling over such temporarily unmapped +* PTE tables. +*/ +mmu_notifier_range_init (&range,MMU_NOTIFY_CLEAR ,0 , mm, start_addr, + end_addr);mmu_notifier_invalidate_range_start (&range); pmd_ptl =pmd_lock (mm, pmd);/* probably unnecessary */
@@ -1308,26 +1318,23 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* Parallel GUP-fast is fine since GUP-fast will back off when * it detects PMD is changed. */ - _pmd =pmdp_collapse_flush (vma, address, pmd); + _pmd =pmdp_collapse_flush (vma, pmd_addr, pmd);spin_unlock (pmd_ptl);mmu_notifier_invalidate_range_end (&range);tlb_remove_table_sync_one (); - pte =pte_offset_map_lock (mm, &_pmd, address, &pte_ptl); + pte =pte_offset_map_lock (mm, &_pmd, start_addr, &pte_ptl);if (pte) { - result =__collapse_huge_page_isolate (vma, address, pte, cc, -HPAGE_PMD_ORDER , - &compound_pagelist); + result =__collapse_huge_page_isolate (vma, start_addr, pte, cc, + order, &compound_pagelist);spin_unlock (pte_ptl); }else { result =SCAN_NO_PTE_TABLE ; }if (unlikely (result !=SCAN_SUCCEED )) { -if (pte) -pte_unmap (pte);spin_lock (pmd_ptl); -BUG_ON (!pmd_none (*pmd)); +VM_WARN_ON_ONCE (!pmd_none (*pmd));/* * We can only use set_pmd_at when establishing * hugepmds and never for establishing regular pmds that
@@ -1335,21 +1342,24 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a*/ pmd_populate (mm, pmd,pmd_pgtable (_pmd));spin_unlock (pmd_ptl); -anon_vma_unlock_write (vma->anon_vma); goto out_up_write; }/* -* All pages are isolated and locked so anon_vma rmap -* can't run anymore. +* For PMD collapse all pages are isolated and locked so anon_vma +* rmap can't run anymore. For mTHP collapse the PMD entry has been +* removed and not all pages are isolated and locked, so we must hold +* the lock to prevent neighboring folios from attempting to access +* this PMD until its reinstalled. */ -anon_vma_unlock_write (vma->anon_vma); +if (is_pmd_order (order)) { +anon_vma_unlock_write (vma->anon_vma); + anon_vma_locked = false; + } result =__collapse_huge_page_copy (pte, folio, pmd, _pmd, - vma, address, pte_ptl, -HPAGE_PMD_ORDER , - &compound_pagelist); -pte_unmap (pte); + vma, start_addr, pte_ptl, + order, &compound_pagelist);if (unlikely (result !=SCAN_SUCCEED )) goto out_up_write;
@@ -1359,18 +1369,37 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* write. */ __folio_mark_uptodate (folio); - pgtable =pmd_pgtable (_pmd); -spin_lock (pmd_ptl); -BUG_ON (!pmd_none (*pmd)); -pgtable_trans_huge_deposit (mm, pmd, pgtable); -map_anon_folio_pmd_nopf (folio, pmd, vma, address); +VM_WARN_ON_ONCE (!pmd_none (*pmd)); +if (is_pmd_order (order)) { + pgtable =pmd_pgtable (_pmd); +pgtable_trans_huge_deposit (mm, pmd, pgtable); +map_anon_folio_pmd_nopf (folio, pmd, vma, pmd_addr); + }else { +/* +* Some architectures (e.g. MIPS) walk the live page table in +* their implementation. update_mmu_cache_range() must be called +* with a valid page table hierarchy and the PTE lock held. +* Acquire it nested inside pmd_ptl when they are distinct locks. +*/ +if (pte_ptl != pmd_ptl) +spin_lock_nested (pte_ptl,SINGLE_DEPTH_NESTING ); +pmd_populate (mm, pmd,pmd_pgtable (_pmd)); +map_anon_folio_pte_nopf (folio, pte, vma, start_addr, +/*uffd_wp=*/ false); +if (pte_ptl != pmd_ptl) +spin_unlock (pte_ptl); + }spin_unlock (pmd_ptl); folio =NULL ; result =SCAN_SUCCEED ; out_up_write: +if (anon_vma_locked) +anon_vma_unlock_write (vma->anon_vma); +if (pte) +pte_unmap (pte);mmap_write_unlock (mm); out_nolock:if (folio)
@@ -1550,7 +1579,7 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,/* collapse_huge_page expects the lock to be dropped before calling */ mmap_read_unlock (mm); result =collapse_huge_page (mm, start_addr, referenced, - unmapped, cc); + unmapped, cc,HPAGE_PMD_ORDER );/* collapse_huge_page will return with the mmap_lock released */ *lock_dropped = true; }
Signature · 1 line
2.54.0
Re: [PATCH mm-unstable v19 06/14] mm/khugepaged: generalize collapse_huge_page for mTHP collapse
Quoted 18 lines · Nico Pache
Pass an order to
collapse_huge_pageto support collapsing anon memory to arbitrary orders within a PMD. order indicates what mTHP size we are attempting to collapse to.For non-PMD collapse we must leave the anon VMA write locked until after we collapse the mTHP-- in the PMD case all the pages are isolated, but in the mTHP case this is not true, and we must keep the lock to prevent access/changes to the page tables. This can happen if the rmap walkers hit a
pmd_nonewhile the PMD entry is currently unavailable due to being temporarily removed during the collapse phase.To properly establish the page table hierarchy without violating any expectations from certain architectures (e.g. MIPS), we must make sure to have the PMD reinstalled before the PTEs, and hold both PTE/PMD locks before calling
update_mmu_cache_range()(if they are distinct locks).Signed-off-by Nico Pache <[email protected]>---
[...]
Quoted 28 lines
(quoted diff) +20
-5*/ __folio_mark_uptodate(folio); - pgtable = pmd_pgtable(_pmd); - spin_lock(pmd_ptl); - BUG_ON(!pmd_none(*pmd)); - pgtable_trans_huge_deposit(mm, pmd, pgtable); - map_anon_folio_pmd_nopf(folio, pmd, vma, address); + VM_WARN_ON_ONCE(!pmd_none(*pmd)); + if (is_pmd_order(order)) { + pgtable = pmd_pgtable(_pmd); + pgtable_trans_huge_deposit(mm, pmd, pgtable); + map_anon_folio_pmd_nopf(folio, pmd, vma, pmd_addr); + } else { + /* + * Some architectures (e.g. MIPS) walk the live page table in + * their implementation. update_mmu_cache_range() must be called + * with a valid page table hierarchy and the PTE lock held. + * Acquire it nested inside pmd_ptl when they are distinct locks. + */ + if (pte_ptl != pmd_ptl) + spin_lock_nested(pte_ptl, SINGLE_DEPTH_NESTING); + pmd_populate(mm, pmd, pmd_pgtable(_pmd)); + map_anon_folio_pte_nopf(folio, pte, vma, start_addr, + /*uffd_wp=*/ false); + if (pte_ptl != pmd_ptl) + spin_unlock(pte_ptl); + }
Review
Quoted 10 lines
(quoted diff) +4
-0spin_unlock(pmd_ptl); folio = NULL; result = SCAN_SUCCEED; out_up_write: + if (anon_vma_locked) + anon_vma_unlock_write(vma->anon_vma); + if (pte) + pte_unmap(pte);
We re-enable some page table walkers before we unmap the PTE.
We still hold the mmap lock in write mode, so nothing would currently try reclaiming the page table concurrently.
So I guess this works right now, but we should likely rework that code later to either revert both statements. Or maybe we can simply unmap like we did, and simply remap before we call map_anon_folio_pte_nopf()? Remapping should not fail.
Alternatively to an unmap+remap, I think we could also unmap earlier for PMD
mm/khugepaged.c +0 -0
@@ -1378,6 +1378,8 @@ static enum scan_result collapse_huge_page(struct
mm_struct *mm, unsigned long s
if (is_pmd_order(order)) {
anon_vma_unlock_write(vma->anon_vma);
anon_vma_locked = false;+ pte_unmap(pte);
+ pte = NULL;
}
result = __collapse_huge_page_copy(pte, folio, pmd, _pmd,
But this can also be handled later.
We now hold an anon_vma lock a bit longer for !pmd-collapse. But there is also less to copy. If that bites us, we can try optimizing later.
So after another skim, I think this patch is ready for primetime. We can address the things mentioned above later ... and any fallout can be fixed later, if any.
Signature · 3 lines
Cheers, David
Re: [PATCH mm-unstable v19 06/14] mm/khugepaged: generalize collapse_huge_page for mTHP collapse
Quoted 63 lines · David Hildenbrand (Arm)
Quoted 18 lines · Nico Pache
Pass an order to
collapse_huge_pageto support collapsing anon memory to arbitrary orders within a PMD. order indicates what mTHP size we are attempting to collapse to.For non-PMD collapse we must leave the anon VMA write locked until after we collapse the mTHP-- in the PMD case all the pages are isolated, but in the mTHP case this is not true, and we must keep the lock to prevent access/changes to the page tables. This can happen if the rmap walkers hit a
pmd_nonewhile the PMD entry is currently unavailable due to being temporarily removed during the collapse phase.To properly establish the page table hierarchy without violating any expectations from certain architectures (e.g. MIPS), we must make sure to have the PMD reinstalled before the PTEs, and hold both PTE/PMD locks before calling
update_mmu_cache_range()(if they are distinct locks).Signed-off-by Nico Pache <[email protected]>---
[...]
Quoted 28 lines
(quoted diff) +20
-5*/ __folio_mark_uptodate(folio); - pgtable = pmd_pgtable(_pmd); - spin_lock(pmd_ptl); - BUG_ON(!pmd_none(*pmd)); - pgtable_trans_huge_deposit(mm, pmd, pgtable); - map_anon_folio_pmd_nopf(folio, pmd, vma, address); + VM_WARN_ON_ONCE(!pmd_none(*pmd)); + if (is_pmd_order(order)) { + pgtable = pmd_pgtable(_pmd); + pgtable_trans_huge_deposit(mm, pmd, pgtable); + map_anon_folio_pmd_nopf(folio, pmd, vma, pmd_addr); + } else { + /* + * Some architectures (e.g. MIPS) walk the live page table in + * their implementation. update_mmu_cache_range() must be called + * with a valid page table hierarchy and the PTE lock held. + * Acquire it nested inside pmd_ptl when they are distinct locks. + */ + if (pte_ptl != pmd_ptl) + spin_lock_nested(pte_ptl, SINGLE_DEPTH_NESTING); + pmd_populate(mm, pmd, pmd_pgtable(_pmd)); + map_anon_folio_pte_nopf(folio, pte, vma, start_addr, + /*uffd_wp=*/ false); + if (pte_ptl != pmd_ptl) + spin_unlock(pte_ptl); + }Review
Quoted 10 lines
(quoted diff) +4
-0spin_unlock(pmd_ptl); folio = NULL; result = SCAN_SUCCEED; out_up_write: + if (anon_vma_locked) + anon_vma_unlock_write(vma->anon_vma); + if (pte) + pte_unmap(pte);We re-enable some page table walkers before we unmap the PTE.
Quoted 2 lines
We still hold the mmap lock in write mode, so nothing would currently try reclaiming the page table concurrently.
Reclaim uses rmap walkers though?
Oh you mean as in page table teardown, we're safe from higher level page table teardown, but we're not safe from zap PTE page table teardown, as CONFIG_PT_RECLAIM makes this possible on zap now.
That is RCU safe, so the unmap would keep us safe here, but now we could lose the PTE page table.
But, only MADV_DONTNEED sets reclaim_pt = true, and that holds the VMA read lock so we're safe.
And anyway:
MADV_DONTNEED - VMA read lock (we hold VMA write lock) zap_vma_for_reaping() - mmap read lock process teardown, munmap - mmap read lock fault - vma/mmap read lock
So the vma/mmap locks save us from those.
So rmap-wise, only the i_mmap walkers remain (truncate, hole punch, et al. and also hugetlbfs truncate/hole-punch which does its own nonsense too), but none of those allow for reclaim_pt to happen in any case.
So yeah we're safe but we should what, reorder these 2 statements?
But yes I agree that can be a follow-up, nothing's broken AFAICT.
Quoted 22 lines
So I guess this works right now, but we should likely rework that code later to either revert both statements. Or maybe we can simply unmap like we did, and simply remap before we call
map_anon_folio_pte_nopf()? Remapping should not fail.Alternatively to an unmap+remap, I think we could also unmap earlier for PMD
mm/khugepaged.c +0
-0@@ -1378,6 +1378,8 @@ static enum scan_result collapse_huge_page(struct
mm_struct*mm, unsigned long sif (is_pmd_order(order)) { anon_vma_unlock_write(vma->anon_vma); anon_vma_locked = false;mm/khugepaged.c +2
-0+pte_unmap (pte); + pte =NULL ; } result = __collapse_huge_page_copy(pte, folio, pmd, _pmd,
Quoted 1 line
But this can also be handled later.
Yup I mean it'd be nicer to do it in one place if we can (+ impact of holding RCU lock longer not an issue), but all this code needs rewokr anyway.
Quoted 3 lines
We now hold an
anon_vmalock a bit longer for !pmd-collapse. But there is also less to copy. If that bites us, we can try optimizing later.
Yeah I do worry about holding these locks longer. But we'll see.
Quoted 6 lines
So after another skim, I think this patch is ready for primetime. We can address the things mentioned above later ... and any fallout can be fixed later, if any.
Yes, also from my side - after a git range-diff and looking into above, LGTM, so:
Now to go look at the core algo patch :)
Quoted 6 lines
--
Cheers,David
Cheers, Lorenzo
Re: [PATCH mm-unstable v19 06/14] mm/khugepaged: generalize collapse_huge_page for mTHP collapse
In reply to Nico PacheQuoted 11 lines · Nico Pache
Pass an order to
collapse_huge_pageto support collapsing anon memory to arbitrary orders within a PMD. order indicates what mTHP size we are attempting to collapse to.For non-PMD collapse we must leave the anon VMA write locked until after we collapse the mTHP-- in the PMD case all the pages are isolated, but in the mTHP case this is not true, and we must keep the lock to prevent access/changes to the page tables. This can happen if the rmap walkers hit a
pmd_nonewhile the PMD entry is currently unavailable due to being temporarily removed during the collapse phase.
Quoted 6 lines
To properly establish the page table hierarchy without violating any expectations from certain architectures (e.g. MIPS), we must make sure to have the PMD reinstalled before the PTEs, and hold both PTE/PMD locks before calling
update_mmu_cache_range()(if they are distinct locks).Signed-off-by Nico Pache <[email protected]>
In case Andrew missing my tag in the lengthily reply in [0]:
:)
(Though probably he has a script that does this for him!)
[0]:https://lore.kernel.org/linux-mm/aiMNT7fBUkZS1EJK@lucifer/
Cheers, Lorenzo
Quoted 219 lines
--- mm/khugepaged.c | 105 ++++++++++++++++++++++++++++++------------------ 1 file changed, 67 insertions(+), 38 deletions(-)mm/khugepaged.c +67
-39@@ -1228,34 +1228,36 @@ static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_stru* while allocating a THP, as that could trigger direct reclaim/compaction. * Note that the VMA must be rechecked after grabbing the mmap_lock again. */ -static enum scan_result collapse_huge_page (struct mm_struct *mm,unsigned long address, -int referenced,int unmapped,struct collapse_control *cc) +static enum scan_result collapse_huge_page (struct mm_struct *mm,unsigned long start_addr, +int referenced,int unmapped,struct collapse_control *cc, +unsigned int order) { +const unsigned long pmd_addr = start_addr &HPAGE_PMD_MASK ; +const unsigned long end_addr = start_addr + (PAGE_SIZE << order);LIST_HEAD (compound_pagelist);pmd_t *pmd, _pmd; -pte_t *pte; +pte_t *pte =NULL ;pgtable_t pgtable;struct folio *folio;spinlock_t *pmd_ptl, *pte_ptl;enum scan_result result =SCAN_FAIL ;struct vm_area_struct *vma;struct mmu_notifier_range range; +bool anon_vma_locked = false; -VM_BUG_ON (address & ~HPAGE_PMD_MASK ); - - result =alloc_charge_folio (&folio, mm, cc,HPAGE_PMD_ORDER ); + result =alloc_charge_folio (&folio, mm, cc, order);if (result !=SCAN_SUCCEED ) goto out_nolock;mmap_read_lock (mm); - result =hugepage_vma_revalidate (mm, address, true, &vma, cc, -HPAGE_PMD_ORDER ); + result =hugepage_vma_revalidate (mm, pmd_addr,/*expect_anon=*/ true, + &vma, cc, order);if (result !=SCAN_SUCCEED ) {mmap_read_unlock (mm); goto out_nolock; } - result =find_pmd_or_thp_or_none (mm, address, &pmd); + result =find_pmd_or_thp_or_none (mm, pmd_addr, &pmd);if (result !=SCAN_SUCCEED ) {mmap_read_unlock (mm); goto out_nolock;@@ -1267,8 +1269,8 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* released when it fails. So we jump out_nolock directly in * that case. Continuing to collapse causes inconsistency. */ - result =__collapse_huge_page_swapin (mm, vma, address, pmd, - referenced,HPAGE_PMD_ORDER ); + result =__collapse_huge_page_swapin (mm, vma, start_addr, pmd, + referenced, order);if (result !=SCAN_SUCCEED ) goto out_nolock; }@@ -1283,20 +1285,28 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* mmap_lock. */ mmap_write_lock (mm); - result =hugepage_vma_revalidate (mm, address, true, &vma, cc, -HPAGE_PMD_ORDER ); + result =hugepage_vma_revalidate (mm, pmd_addr,/*expect_anon=*/ true, + &vma, cc, order);if (result !=SCAN_SUCCEED ) goto out_up_write;/* check if the pmd is still valid */ vma_start_write (vma); - result =check_pmd_still_valid (mm, address, pmd); + result =check_pmd_still_valid (mm, pmd_addr, pmd);if (result !=SCAN_SUCCEED ) goto out_up_write;anon_vma_lock_write (vma->anon_vma); + anon_vma_locked = true; -mmu_notifier_range_init (&range,MMU_NOTIFY_CLEAR ,0 , mm, address, - address +HPAGE_PMD_SIZE ); +/* +* Only notify about the PTE range we will actually modify. While we +* temporary unmap the whole PTE table for mTHP collapse, we'll remap +* it later, leaving other PTEs effectively unmodified. The locks we +* hold prevent anybody from stumbling over such temporarily unmapped +* PTE tables. +*/ +mmu_notifier_range_init (&range,MMU_NOTIFY_CLEAR ,0 , mm, start_addr, + end_addr);mmu_notifier_invalidate_range_start (&range); pmd_ptl =pmd_lock (mm, pmd);/* probably unnecessary */ @@ -1308,26 +1318,23 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* Parallel GUP-fast is fine since GUP-fast will back off when * it detects PMD is changed. */ - _pmd =pmdp_collapse_flush (vma, address, pmd); + _pmd =pmdp_collapse_flush (vma, pmd_addr, pmd);spin_unlock (pmd_ptl);mmu_notifier_invalidate_range_end (&range);tlb_remove_table_sync_one (); - pte =pte_offset_map_lock (mm, &_pmd, address, &pte_ptl); + pte =pte_offset_map_lock (mm, &_pmd, start_addr, &pte_ptl);if (pte) { - result =__collapse_huge_page_isolate (vma, address, pte, cc, -HPAGE_PMD_ORDER , - &compound_pagelist); + result =__collapse_huge_page_isolate (vma, start_addr, pte, cc, + order, &compound_pagelist);spin_unlock (pte_ptl); }else { result =SCAN_NO_PTE_TABLE ; }if (unlikely (result !=SCAN_SUCCEED )) { -if (pte) -pte_unmap (pte);spin_lock (pmd_ptl); -BUG_ON (!pmd_none (*pmd)); +VM_WARN_ON_ONCE (!pmd_none (*pmd));/* * We can only use set_pmd_at when establishing * hugepmds and never for establishing regular pmds that @@ -1335,21 +1342,24 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a*/ pmd_populate (mm, pmd,pmd_pgtable (_pmd));spin_unlock (pmd_ptl); -anon_vma_unlock_write (vma->anon_vma); goto out_up_write; }/* -* All pages are isolated and locked so anon_vma rmap -* can't run anymore. +* For PMD collapse all pages are isolated and locked so anon_vma +* rmap can't run anymore. For mTHP collapse the PMD entry has been +* removed and not all pages are isolated and locked, so we must hold +* the lock to prevent neighboring folios from attempting to access +* this PMD until its reinstalled. */ -anon_vma_unlock_write (vma->anon_vma); +if (is_pmd_order (order)) { +anon_vma_unlock_write (vma->anon_vma); + anon_vma_locked = false; + } result =__collapse_huge_page_copy (pte, folio, pmd, _pmd, - vma, address, pte_ptl, -HPAGE_PMD_ORDER , - &compound_pagelist); -pte_unmap (pte); + vma, start_addr, pte_ptl, + order, &compound_pagelist);if (unlikely (result !=SCAN_SUCCEED )) goto out_up_write;@@ -1359,18 +1369,37 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long a* write. */ __folio_mark_uptodate (folio); - pgtable =pmd_pgtable (_pmd); -spin_lock (pmd_ptl); -BUG_ON (!pmd_none (*pmd)); -pgtable_trans_huge_deposit (mm, pmd, pgtable); -map_anon_folio_pmd_nopf (folio, pmd, vma, address); +VM_WARN_ON_ONCE (!pmd_none (*pmd)); +if (is_pmd_order (order)) { + pgtable =pmd_pgtable (_pmd); +pgtable_trans_huge_deposit (mm, pmd, pgtable); +map_anon_folio_pmd_nopf (folio, pmd, vma, pmd_addr); + }else { +/* +* Some architectures (e.g. MIPS) walk the live page table in +* their implementation. update_mmu_cache_range() must be called +* with a valid page table hierarchy and the PTE lock held. +* Acquire it nested inside pmd_ptl when they are distinct locks. +*/ +if (pte_ptl != pmd_ptl) +spin_lock_nested (pte_ptl,SINGLE_DEPTH_NESTING ); +pmd_populate (mm, pmd,pmd_pgtable (_pmd)); +map_anon_folio_pte_nopf (folio, pte, vma, start_addr, +/*uffd_wp=*/ false); +if (pte_ptl != pmd_ptl) +spin_unlock (pte_ptl); + }spin_unlock (pmd_ptl); folio =NULL ; result =SCAN_SUCCEED ; out_up_write: +if (anon_vma_locked) +anon_vma_unlock_write (vma->anon_vma); +if (pte) +pte_unmap (pte);mmap_write_unlock (mm); out_nolock:if (folio)@@ -1550,7 +1579,7 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,/* collapse_huge_page expects the lock to be dropped before calling */ mmap_read_unlock (mm); result =collapse_huge_page (mm, start_addr, referenced, - unmapped, cc); + unmapped, cc,HPAGE_PMD_ORDER );/* collapse_huge_page will return with the mmap_lock released */ *lock_dropped = true; } --2.54.0
Re: [PATCH mm-unstable v19 06/14] mm/khugepaged: generalize collapse_huge_page for mTHP collapse
In reply to Nico PacheQuoted 11 lines · Nico Pache
Pass an order to
collapse_huge_pageto support collapsing anon memory to arbitrary orders within a PMD. order indicates what mTHP size we are attempting to collapse to.For non-PMD collapse we must leave the anon VMA write locked until after we collapse the mTHP-- in the PMD case all the pages are isolated, but in the mTHP case this is not true, and we must keep the lock to prevent access/changes to the page tables. This can happen if the rmap walkers hit a
pmd_nonewhile the PMD entry is currently unavailable due to being temporarily removed during the collapse phase.
Quoted 7 lines
To properly establish the page table hierarchy without violating any expectations from certain architectures (e.g. MIPS), we must make sure to have the PMD reinstalled before the PTEs, and hold both PTE/PMD locks before calling
update_mmu_cache_range()(if they are distinct locks).Signed-off-by Nico Pache <[email protected]>---
Nothing else jumped out at me. Anything left can be sorted out later, as David and Lorenzo said :)
PATCH v19 7/14 mm/khugepaged: skip collapsing mTHP to smaller orders
In reply to Nico Pachekhugepaged may try to collapse a mTHP to a folio of equal or smaller size, possibly resulting in a partially mapped source folio, which is undesired. Skip these cases until we have a way to check if its ok to collapse to a smaller mTHP size (like in the case of a partially mapped folio). This check is not done during the scan phase as the current collapse order is unknown at that time.
This patch is inspired by Dev Jain's work on khugepaged mTHP support [1].
[1] https://lore.kernel.org/lkml/[email protected]/
--- mm/khugepaged.c | 8 ++++++++ 1 file changed, 8 insertions(+)
mm/khugepaged.c +8 -0
@@ -697,6 +697,14 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma, goto out; } } +/* +* TODO: In some cases of partially-mapped folios, we'd actually +* want to collapse. +*/ +if (!is_pmd_order (order) &&folio_order (folio) >= order) { + result =SCAN_PTE_MAPPED_HUGEPAGE ; + goto out; + }if (folio_test_large (folio)) {struct folio *f;
Signature · 1 line
2.54.0
Re: [PATCH mm-unstable v19 07/14] mm/khugepaged: skip collapsing mTHP to smaller orders
Quoted 27 lines · Nico Pache
khugepaged may try to collapse a mTHP to a folio of equal or smaller size, possibly resulting in a partially mapped source folio, which is undesired. Skip these cases until we have a way to check if its ok to collapse to a smaller mTHP size (like in the case of a partially mapped folio). This check is not done during the scan phase as the current collapse order is unknown at that time.
This patch is inspired by Dev Jain's work on khugepaged mTHP support [1].
[1] https://lore.kernel.org/lkml/[email protected]/
Reviewed-by Lorenzo Stoakes <[email protected]>Reviewed-by Baolin Wang <[email protected]>Acked-by Usama Arif <[email protected]>Co-developed-by Dev Jain <[email protected]>Signed-off-by Dev Jain <[email protected]>Signed-off-by Nico Pache <[email protected]>---
mm/khugepaged.c| 8 ++++++++1 file changed, 8 insertions(+)mm/khugepaged.c +0
-0
mm/khugepaged.c static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma, · line 703
Quoted 7 lines
mm/khugepaged.c +4
-0@@ -697,6 +697,14 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma, goto out; } } +/* +* TODO: In some cases of partially-mapped folios, we'd actually +* want to collapse. +*/
Partially mapped folios can be handled later :)
Quoted 11 lines
mm/khugepaged.c +4
-0+if (!is_pmd_order (order) &&folio_order (folio) >= order) { + result =SCAN_PTE_MAPPED_HUGEPAGE ; + goto out; + }if (folio_test_large (folio)) {struct folio *f;Signature · 1 line
2.54.0
PATCH v19 8/14 mm/khugepaged: add per-order mTHP collapse failure statistics
In reply to Nico PacheAdd three new mTHP statistics to track collapse failures for different orders when encountering swap PTEs, excessive none PTEs, and shared PTEs:
- collapse_exceed_swap_pte: Increment when mTHP collapse fails due to encountering a swap PTE.
- collapse_exceed_none_pte: Counts when mTHP collapse fails due to exceeding the none PTE threshold for the given order
- collapse_exceed_shared_pte: Counts when mTHP collapse fails due to encountering a shared PTE.
These statistics complement the existing THP_SCAN_EXCEED_* events by providing per-order granularity for mTHP collapse attempts. The stats are exposed via sysfs under /sys/kernel/mm/transparent_hugepage/hugepages-*/stats/ for each supported hugepage size.
As we currently do not support collapsing mTHPs that contain a swap or shared entry, those statistics keep track of how often we are encountering failed mTHP collapses due to these restrictions.
We will add support for mTHP collapse for anonymous pages next; lets also track when this happens at the PMD level within the per-mTHP stats.
--- Documentation/admin-guide/mm/transhuge.rst | 14 ++++++++++++++ include/linux/huge_mm.h | 3 +++ mm/huge_memory.c | 7 +++++++ mm/khugepaged.c | 15 +++++++++++++-- 4 files changed, 37 insertions(+), 2 deletions(-)
Documentation/admin-guide/mm/transhuge.rst +14 -0
@@ -714,6 +714,20 @@ nr_anon_partially_mapped an anonymous THP as "partially mapped" and count it here, even though it is not actually partially mapped anymore. +collapse_exceed_none_pte + The number of collapse attempts that failed due to exceeding the + max_ptes_none threshold. + +collapse_exceed_swap_pte + The number of collapse attempts that failed due to exceeding the + max_ptes_swap threshold. For non-PMD orders this occurs if a mTHP range + contains at least one swap PTE. + +collapse_exceed_shared_pte + The number of collapse attempts that failed due to exceeding the + max_ptes_shared threshold. For non-PMD orders this occurs if a mTHP range + contains at least one shared PTE. + As the system ages, allocating huge pages may be expensive as the system uses memory compaction to copy data around memory to free a huge page for use. There are some counters in ``/proc/vmstat`` to help
include/linux/huge_mm.h +3 -0
@@ -144,6 +144,9 @@ enum mthp_stat_item {MTHP_STAT_SPLIT_DEFERRED ,MTHP_STAT_NR_ANON ,MTHP_STAT_NR_ANON_PARTIALLY_MAPPED , +MTHP_STAT_COLLAPSE_EXCEED_SWAP , +MTHP_STAT_COLLAPSE_EXCEED_NONE , +MTHP_STAT_COLLAPSE_EXCEED_SHARED , __MTHP_STAT_COUNT };
mm/huge_memory.c +7 -0
@@ -717,6 +717,10 @@ DEFINE_MTHP_STAT_ATTR(split_failed, MTHP_STAT_SPLIT_FAILED);DEFINE_MTHP_STAT_ATTR (split_deferred,MTHP_STAT_SPLIT_DEFERRED );DEFINE_MTHP_STAT_ATTR (nr_anon,MTHP_STAT_NR_ANON );DEFINE_MTHP_STAT_ATTR (nr_anon_partially_mapped,MTHP_STAT_NR_ANON_PARTIALLY_MAPPED ); +DEFINE_MTHP_STAT_ATTR (collapse_exceed_swap_pte,MTHP_STAT_COLLAPSE_EXCEED_SWAP ); +DEFINE_MTHP_STAT_ATTR (collapse_exceed_none_pte,MTHP_STAT_COLLAPSE_EXCEED_NONE ); +DEFINE_MTHP_STAT_ATTR (collapse_exceed_shared_pte,MTHP_STAT_COLLAPSE_EXCEED_SHARED ); +static struct attribute *anon_stats_attrs[] = { &anon_fault_alloc_attr.attr,
@@ -733,6 +737,9 @@ static struct attribute *anon_stats_attrs[] = { &split_deferred_attr.attr, &nr_anon_attr.attr, &nr_anon_partially_mapped_attr.attr, + &collapse_exceed_swap_pte_attr.attr, + &collapse_exceed_none_pte_attr.attr, + &collapse_exceed_shared_pte_attr.attr, NULL, };
mm/khugepaged.c +13 -2
@@ -651,7 +651,9 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,if (pte_none_or_zero (pteval)) {if (++none_or_zero > max_ptes_none) { result =SCAN_EXCEED_NONE_PTE ; -count_vm_event (THP_SCAN_EXCEED_NONE_PTE ); +if (is_pmd_order (order)) +count_vm_event (THP_SCAN_EXCEED_NONE_PTE ); +count_mthp_stat (order,MTHP_STAT_COLLAPSE_EXCEED_NONE ); goto out; }continue ;
@@ -693,7 +695,9 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,*/ if (++shared > max_ptes_shared) { result =SCAN_EXCEED_SHARED_PTE ; -count_vm_event (THP_SCAN_EXCEED_SHARED_PTE ); +if (is_pmd_order (order)) +count_vm_event (THP_SCAN_EXCEED_SHARED_PTE ); +count_mthp_stat (order,MTHP_STAT_COLLAPSE_EXCEED_SHARED ); goto out; } }
@@ -1152,6 +1156,7 @@ static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm,* range. */ if (!is_pmd_order (order)) { +count_mthp_stat (order,MTHP_STAT_COLLAPSE_EXCEED_SWAP );pte_unmap (pte);mmap_read_unlock (mm); result =SCAN_EXCEED_SWAP_PTE ;
@@ -1459,6 +1464,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,if (++none_or_zero > max_ptes_none) { result =SCAN_EXCEED_NONE_PTE ;count_vm_event (THP_SCAN_EXCEED_NONE_PTE ); +count_mthp_stat (HPAGE_PMD_ORDER , +MTHP_STAT_COLLAPSE_EXCEED_NONE ); goto out_unmap; }continue ;
@@ -1467,6 +1474,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,if (++unmapped > max_ptes_swap) { result =SCAN_EXCEED_SWAP_PTE ;count_vm_event (THP_SCAN_EXCEED_SWAP_PTE ); +count_mthp_stat (HPAGE_PMD_ORDER , +MTHP_STAT_COLLAPSE_EXCEED_SWAP ); goto out_unmap; }/*
@@ -1524,6 +1533,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,if (++shared > max_ptes_shared) { result =SCAN_EXCEED_SHARED_PTE ;count_vm_event (THP_SCAN_EXCEED_SHARED_PTE ); +count_mthp_stat (HPAGE_PMD_ORDER , +MTHP_STAT_COLLAPSE_EXCEED_SHARED ); goto out_unmap; } }
Signature · 1 line
2.54.0
Re: [PATCH mm-unstable v19 08/14] mm/khugepaged: add per-order mTHP collapse failure statistics
Quoted 22 lines · Nico Pache
Add three new mTHP statistics to track collapse failures for different orders when encountering swap PTEs, excessive none PTEs, and shared PTEs:
-
collapse_exceed_swap_pte: Increment when mTHP collapse fails due to encountering a swap PTE.-
collapse_exceed_none_pte: Counts when mTHP collapse fails due to exceeding the none PTE threshold for the given order-
collapse_exceed_shared_pte: Counts when mTHP collapse fails due to encountering a shared PTE.These statistics complement the existing THP_SCAN_EXCEED_* events by providing per-order granularity for mTHP collapse attempts. The stats are exposed via sysfs under
/sys/kernel/mm/transparent_hugepage/hugepages-*/stats/for each supported hugepage size.As we currently do not support collapsing mTHPs that contain a swap or shared entry, those statistics keep track of how often we are encountering failed mTHP collapses due to these restrictions.
Quoted 7 lines
We will add support for mTHP collapse for anonymous pages next; lets also track when this happens at the PMD level within the per-mTHP stats.
Reviewed-by Lorenzo Stoakes <[email protected]>Signed-off-by Nico Pache <[email protected]>---
PATCH v19 9/14 mm/khugepaged: improve tracepoints for mTHP orders
In reply to Nico PacheAdd the order to the mm_collapse_huge_page<_swapin,_isolate> tracepoints to give better insight into what order is being operated at for.
--- include/trace/events/huge_memory.h | 34 +++++++++++++++++++----------- mm/khugepaged.c | 9 ++++---- 2 files changed, 27 insertions(+), 16 deletions(-)
include/trace/events/huge_memory.h +22 -12
@@ -89,40 +89,44 @@ TRACE_EVENT(mm_khugepaged_scan_pmd,TRACE_EVENT (mm_collapse_huge_page, - TP_PROTO(struct mm_struct *mm, int isolated, int status), + TP_PROTO(struct mm_struct *mm, int isolated, int status, unsigned int order), -TP_ARGS (mm, isolated, status), +TP_ARGS (mm, isolated, status, order),TP_STRUCT__entry ( __field(struct mm_struct *, mm) __field(int, isolated) __field(int, status) + __field(unsigned int, order) ),TP_fast_assign ( __entry->mm = mm; __entry->isolated = isolated; __entry->status = status; + __entry->order = order; ), -TP_printk ("mm=%p, isolated=%d, status=%s" , +TP_printk ("mm=%p, isolated=%d, status=%s, order=%u" , __entry->mm, __entry->isolated, -__print_symbolic (__entry->status,SCAN_STATUS )) +__print_symbolic (__entry->status,SCAN_STATUS ), + __entry->order) ); TRACE_EVENT(mm_collapse_huge_page_isolate, TP_PROTO(struct folio *folio, int none_or_zero, - int referenced, int status), + int referenced, int status, unsigned int order), - TP_ARGS(folio, none_or_zero, referenced, status), + TP_ARGS(folio, none_or_zero, referenced, status, order), TP_STRUCT__entry( __field(unsigned long, pfn) __field(int, none_or_zero) __field(int, referenced) __field(int, status) + __field(unsigned int, order) ), TP_fast_assign(
@@ -130,26 +134,30 @@ TRACE_EVENT(mm_collapse_huge_page_isolate, __entry->none_or_zero = none_or_zero; __entry->referenced = referenced; __entry->status = status; + __entry->order = order; ), -TP_printk ("scan_pfn=0x%lx, none_or_zero=%d, referenced=%d, status=%s" , +TP_printk ("scan_pfn=0x%lx, none_or_zero=%d, referenced=%d, status=%s, order=%u" , __entry->pfn, __entry->none_or_zero, __entry->referenced, -__print_symbolic (__entry->status,SCAN_STATUS )) +__print_symbolic (__entry->status,SCAN_STATUS ), + __entry->order) ); TRACE_EVENT(mm_collapse_huge_page_swapin, - TP_PROTO(struct mm_struct *mm, int swapped_in, int referenced, int ret), + TP_PROTO(struct mm_struct *mm, int swapped_in, int referenced, int ret, + unsigned int order), - TP_ARGS(mm, swapped_in, referenced, ret), + TP_ARGS(mm, swapped_in, referenced, ret, order), TP_STRUCT__entry( __field(struct mm_struct *, mm) __field(int, swapped_in) __field(int, referenced) __field(int, ret) + __field(unsigned int, order) ), TP_fast_assign(
@@ -157,13 +165,15 @@ TRACE_EVENT(mm_collapse_huge_page_swapin, __entry->swapped_in = swapped_in; __entry->referenced = referenced; __entry->ret = ret; + __entry->order = order; ), -TP_printk ("mm=%p, swapped_in=%d, referenced=%d, ret=%d" , +TP_printk ("mm=%p, swapped_in=%d, referenced=%d, ret=%d, order=%u" , __entry->mm, __entry->swapped_in, __entry->referenced, - __entry->ret) + __entry->ret, + __entry->order) ); TRACE_EVENT(mm_khugepaged_scan_file,
mm/khugepaged.c +5 -4
@@ -785,13 +785,13 @@ static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma, }else { result =SCAN_SUCCEED ;trace_mm_collapse_huge_page_isolate (folio, none_or_zero, - referenced, result); + referenced, result, order);return result; } out:release_pte_pages (pte, _pte, compound_pagelist);trace_mm_collapse_huge_page_isolate (folio, none_or_zero, - referenced, result); + referenced, result, order);return result; }
@@ -1197,7 +1197,8 @@ static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm, result =SCAN_SUCCEED ; out: -trace_mm_collapse_huge_page_swapin (mm, swapped_in, referenced, result); +trace_mm_collapse_huge_page_swapin (mm, swapped_in, referenced, result, + order);return result; }
@@ -1417,7 +1418,7 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s out_nolock:if (folio)folio_put (folio); -trace_mm_collapse_huge_page (mm, result ==SCAN_SUCCEED , result); +trace_mm_collapse_huge_page (mm, result ==SCAN_SUCCEED , result, order);return result; }
Signature · 1 line
2.54.0
Re: [PATCH mm-unstable v19 09/14] mm/khugepaged: improve tracepoints for mTHP orders
Quoted 8 lines · Nico Pache
Add the order to the mm_collapse_huge_page<_swapin,_isolate> tracepoints to give better insight into what order is being operated at for.
Reviewed-by Lorenzo Stoakes <[email protected]>Reviewed-by Baolin Wang <[email protected]>Signed-off-by Nico Pache <[email protected]>---
PATCH v19 10/14 mm/khugepaged: introduce collapse_possible_orders helper functions
In reply to Nico PacheAdd collapse_possible_orders() to generalize THP order eligibility. The function determines which THP orders are permitted based on collapse context (khugepaged vs madv_collapse). We also add collapse_possible() as a thin wrapper around collapse_possible_orders() that returns a bool rather than the whole bitmap.
This consolidates collapse configuration logic and provides a clean interface for future mTHP collapse support where the orders may be different.
--- mm/khugepaged.c | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-)
mm/khugepaged.c +21 -3
@@ -554,12 +554,30 @@ void __khugepaged_enter(struct mm_struct *mm)wake_up_interruptible (&khugepaged_wait); } +/* +* Check what orders are possible based on the vma and collapse type. +* This is used to determine if mTHP collapse is a viable option. +*/ +static unsigned long collapse_possible_orders (struct vm_area_struct *vma, +vm_flags_t vm_flags,enum tva_type tva_flags) +{ +const unsigned long orders =BIT (HPAGE_PMD_ORDER ); + +return thp_vma_allowable_orders (vma, vm_flags, tva_flags, orders); +} + +static bool collapse_possible (struct vm_area_struct *vma, +vm_flags_t vm_flags,enum tva_type tva_flags) +{ +return collapse_possible_orders (vma, vm_flags, tva_flags); +} +void khugepaged_enter_vma (struct vm_area_struct *vma,vm_flags_t vm_flags) {if (!mm_flags_test (MMF_VM_HUGEPAGE , vma->vm_mm) &&hugepage_pmd_enabled ()) { -if (thp_vma_allowable_order (vma, vm_flags,TVA_KHUGEPAGED ,PMD_ORDER )) +if (collapse_possible (vma, vm_flags,TVA_KHUGEPAGED ))__khugepaged_enter (vma->vm_mm); } }
@@ -2700,7 +2718,7 @@ static void collapse_scan_mm_slot(unsigned int progress_max, cc->progress++;break ; } -if (!thp_vma_allowable_order (vma, vma->vm_flags,TVA_KHUGEPAGED ,PMD_ORDER )) { +if (!collapse_possible (vma, vma->vm_flags,TVA_KHUGEPAGED )) { cc->progress++;continue ; }
@@ -3010,7 +3028,7 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,BUG_ON (vma->vm_start > start);BUG_ON (vma->vm_end < end); -if (!thp_vma_allowable_order (vma, vma->vm_flags,TVA_FORCED_COLLAPSE ,PMD_ORDER )) +if (!collapse_possible (vma, vma->vm_flags,TVA_FORCED_COLLAPSE ))return -EINVAL ; cc =kmalloc_obj (*cc);
Signature · 1 line
2.54.0
Re: [PATCH mm-unstable v19 10/14] mm/khugepaged: introduce collapse_possible_orders helper functions
Quoted 6 lines · Nico Pache
Add
collapse_possible_orders()to generalize THP order eligibility. The function determines which THP orders are permitted based on collapse context (khugepaged vsmadv_collapse). We also addcollapse_possible()as a thin wrapper aroundcollapse_possible_orders()that returns a bool rather than the whole bitmap.
Quoted 7 lines
This consolidates collapse configuration logic and provides a clean interface for future mTHP collapse support where the orders may be different.
Reviewed-by Baolin Wang <[email protected]>Signed-off-by Nico Pache <[email protected]>
LGTM, so:
Quoted 61 lines
--- mm/khugepaged.c | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-)mm/khugepaged.c +21
-4@@ -554,12 +554,30 @@ void __khugepaged_enter(struct mm_struct *mm)wake_up_interruptible (&khugepaged_wait); } +/* +* Check what orders are possible based on the vma and collapse type. +* This is used to determine if mTHP collapse is a viable option. +*/ +static unsigned long collapse_possible_orders (struct vm_area_struct *vma, +vm_flags_t vm_flags,enum tva_type tva_flags) +{ +const unsigned long orders =BIT (HPAGE_PMD_ORDER ); + +return thp_vma_allowable_orders (vma, vm_flags, tva_flags, orders); +} + +static bool collapse_possible (struct vm_area_struct *vma, +vm_flags_t vm_flags,enum tva_type tva_flags) +{ +return collapse_possible_orders (vma, vm_flags, tva_flags); +} +void khugepaged_enter_vma (struct vm_area_struct *vma,vm_flags_t vm_flags) {if (!mm_flags_test (MMF_VM_HUGEPAGE , vma->vm_mm) &&hugepage_pmd_enabled ()) { -if (thp_vma_allowable_order (vma, vm_flags,TVA_KHUGEPAGED ,PMD_ORDER )) +if (collapse_possible (vma, vm_flags,TVA_KHUGEPAGED ))__khugepaged_enter (vma->vm_mm); } }@@ -2700,7 +2718,7 @@ static void collapse_scan_mm_slot(unsigned int progress_max, cc->progress++;break ; } -if (!thp_vma_allowable_order (vma, vma->vm_flags,TVA_KHUGEPAGED ,PMD_ORDER )) { +if (!collapse_possible (vma, vma->vm_flags,TVA_KHUGEPAGED )) { cc->progress++;continue ; }@@ -3010,7 +3028,7 @@ int madvise_collapse(struct vm_area_struct *vma, unsigned long start,BUG_ON (vma->vm_start > start);BUG_ON (vma->vm_end < end); -if (!thp_vma_allowable_order (vma, vma->vm_flags,TVA_FORCED_COLLAPSE ,PMD_ORDER )) +if (!collapse_possible (vma, vma->vm_flags,TVA_FORCED_COLLAPSE ))return -EINVAL ; cc =kmalloc_obj (*cc); --2.54.0
Re: [PATCH mm-unstable v19 10/14] mm/khugepaged: introduce collapse_possible_orders helper functions
In reply to Nico PacheQuoted 6 lines · Nico Pache
Add
collapse_possible_orders()to generalize THP order eligibility. The function determines which THP orders are permitted based on collapse context (khugepaged vsmadv_collapse). We also addcollapse_possible()as a thin wrapper aroundcollapse_possible_orders()that returns a bool rather than the whole bitmap.
Quoted 8 lines
This consolidates collapse configuration logic and provides a clean interface for future mTHP collapse support where the orders may be different.
Reviewed-by Baolin Wang <[email protected]>Signed-off-by Nico Pache <[email protected]>---
PATCH v19 11/14 mm/khugepaged: Introduce mTHP collapse support
In reply to Nico PacheEnable khugepaged to collapse to mTHP orders. This patch implements the main scanning logic using a bitmap to track occupied pages and the algorithm to find optimal collapse sizes.
Previous to this patch, PMD collapse had 3 main phases, a light weight scanning phase (mmap_read_lock) that determines a potential PMD collapse, an alloc phase (mmap unlocked), then finally heavier collapse phase (mmap_write_lock).
To enabled mTHP collapse we make the following changes:
During PMD scan phase, track occupied pages in a bitmap. When mTHP orders are enabled, we remove the restriction of max_ptes_none during the scan phase to avoid missing potential mTHP collapse candidates. Once we have scanned the full PMD range and updated the bitmap to track occupied pages, we use the bitmap to find the optimal mTHP size.
Implement mthp_collapse() to walk forward through the bitmap and determine the best eligible order for each naturally-aligned region. The algorithm starts at the beginning of the PMD range and, for each offset, tries the highest order that fits the alignment. If the number of occupied PTEs in that region satisfies the max_ptes_none threshold for that order, a collapse is attempted. On failure, the order is decremented and the same offset is retried at the next smaller size. Once the smallest enabled order is exhausted (or a collapse succeeds), the offset advances past the region just processed, and the next attempt starts at the highest order permitted by the new offset's natural alignment.
The algorithm works as follows:
1) set offset=0 and order=HPAGE_PMD_ORDER
2) if the order is not enabled, go to step (5)
3) count occupied PTEs in the (offset, order) range using bitmap_weight_from()
4) if the count satisfies the max_ptes_none threshold, attempt collapse; on success, advance to step (6)
5) if a smaller enabled order exists, decrement order and retry from step (2) at the same offset
6) advance offset past the current region and compute the next order from the new offset's natural alignment via __ffs(offset), capped at HPAGE_PMD_ORDER
7) repeat from step (2) until the full PMD range is covered
mTHP collapses reject regions containing swapped out or shared pages. This is because adding new entries can lead to new none pages, and these may lead to constant promotion into a higher order mTHP. A similar issue can occur with "max_ptes_none > HPAGE_PMD_NR/2" due to a collapse introducing at least 2x the number of pages, and on a future scan will satisfy the promotion condition once again. This issue is prevented via the collapse_max_ptes_none() function which imposes the max_ptes_none restrictions above.
We currently only support mTHP collapse for max_ptes_none values of 0 and HPAGE_PMD_NR - 1. resulting in the following behavior:
- max_ptes_none=0: Never introduce new empty pages during collapse
- max_ptes_none=HPAGE_PMD_NR-1: Always try collapse to the highest available mTHP order
Any other max_ptes_none value will emit a warning and default mTHP collapse to max_ptes_none=0. There should be no behavior change for PMD collapse.
Once we determine what mTHP sizes fits best in that PMD range a collapse is attempted. A minimum collapse order of 2 is used as this is the lowest order supported by anon memory as defined by THP_ORDERS_ALL_ANON.
Currently madv_collapse is not supported and will only attempt PMD collapse.
We can also remove the check for is_khugepaged inside the PMD scan as the collapse_max_ptes_none() function handles this logic now.
--- mm/khugepaged.c | 146 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 138 insertions(+), 8 deletions(-)
mm/khugepaged.c +138 -8
@@ -99,6 +99,8 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);static struct kmem_cache *mm_slot_cache__ro_after_init ; +#define KHUGEPAGED_MIN_MTHP_ORDER 2 +struct collapse_control {bool is_khugepaged;
@@ -110,6 +112,9 @@ struct collapse_control {/* nodemask for allocation fallback */ nodemask_t alloc_nmask; + +/* Each bit represents a single occupied (!none/zero) page. */ +DECLARE_BITMAP (mthp_present_ptes,MAX_PTRS_PER_PTE ); };/**
@@ -1440,20 +1445,130 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long sreturn result; } +/* Return the highest naturally aligned order that fits at @offset within a PMD. */ +static unsigned int max_order_from_offset (unsigned int offset) +{ +if (offset ==0 ) +return HPAGE_PMD_ORDER ; + + return min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER); +} + +/* +* mthp_collapse() consumes the bitmap that is generated during +* collapse_scan_pmd() to determine what regions and mTHP orders fit best. +* +* Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero) +* page. We start at the PMD order and check if it is eligible for collapse; +* if not, we check the left and right halves of the PTE page table we are +* examining at a lower order. +* +* For each of these, we determine how many PTE entries are occupied in the +* range of PTE entries we propose to collapse, then we compare this to a +* threshold number of PTE entries which would need to be occupied for a +* collapse to be permitted at that order (accounting for max_ptes_none). +* +* If a collapse is permitted, we attempt to collapse the PTE range into a +* mTHP. +*/ +static enum scan_result mthp_collapse (struct mm_struct *mm, +unsigned long address,int referenced,int unmapped, +struct collapse_control *cc,unsigned long enabled_orders) +{ +unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none; +enum scan_result last_result =SCAN_FAIL ; +int collapsed =0 ; +bool alloc_failed = false; +unsigned long collapse_address; +unsigned int offset =0 ; +unsigned int order =HPAGE_PMD_ORDER ; + +while (offset <HPAGE_PMD_NR ) { + nr_ptes =1UL << order; + +if (!test_bit (order, &enabled_orders)) + goto next_order; + + max_ptes_none =collapse_max_ptes_none (cc,NULL , order); + nr_occupied_ptes =bitmap_weight_from (cc->mthp_present_ptes, offset, + offset + nr_ptes); + +if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { +enum scan_result ret; + + collapse_address = address + offset *PAGE_SIZE ; + ret =collapse_huge_page (mm, collapse_address, referenced, + unmapped, cc, order); +switch (ret) { +/* Cases where we continue to next collapse candidate */ +case SCAN_SUCCEED : + collapsed += nr_ptes; + fallthrough; +case SCAN_PTE_MAPPED_HUGEPAGE : + goto next_offset; +/* Cases where lower orders might still succeed */ +case SCAN_ALLOC_HUGE_PAGE_FAIL : + alloc_failed = true; + last_result = ret; + goto next_order; +/* Cases where no further collapse is possible */ +case SCAN_PMD_MAPPED : + fallthrough; +default : + last_result = ret; + goto done; + } + } + +next_order: +/* +* Continue with the next smaller order if there is still +* any smaller order enabled. When at the smallest order +* we must always move to the next offset. +*/ +if (order >KHUGEPAGED_MIN_MTHP_ORDER && + (enabled_orders &GENMASK (order -1 ,0 ))) { + order--; +continue ; + } +next_offset: +/* +* Advance past the region we just processed and determine the +* highest order we can attempt next. Since huge pages must be +* naturally aligned, the max order we can attempt next is +* limited by the alignment of the new offset. +* E.g. if we collapsed a order-2 mTHP at offset 0, offset +* becomes 4 and __ffs(4) == 2, so the next attempt starts at +* order 2. +*/ + offset += nr_ptes; + order =max_order_from_offset (offset); + } +done: +if (collapsed) +return SCAN_SUCCEED ; +if (alloc_failed) +return SCAN_ALLOC_HUGE_PAGE_FAIL ; +return last_result; +} +static enum scan_result collapse_scan_pmd (struct mm_struct *mm,struct vm_area_struct *vma,unsigned long start_addr,bool *lock_dropped,struct collapse_control *cc) { -const unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma,HPAGE_PMD_ORDER );const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc,HPAGE_PMD_ORDER );const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc,HPAGE_PMD_ORDER ); +unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma,HPAGE_PMD_ORDER ); +enum tva_type tva_flags = cc->is_khugepaged ?TVA_KHUGEPAGED :TVA_FORCED_COLLAPSE ;pmd_t *pmd; -pte_t *pte, *_pte; +pte_t *pte, *_pte, pteval; +int i;int none_or_zero =0 , shared =0 , referenced =0 ;enum scan_result result =SCAN_FAIL ;struct page *page =NULL ;struct folio *folio =NULL ;unsigned long addr; +unsigned long enabled_orders;spinlock_t *ptl;int node =NUMA_NO_NODE , unmapped =0 ;
@@ -1465,8 +1580,19 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, goto out; } +bitmap_zero (cc->mthp_present_ptes,MAX_PTRS_PER_PTE );memset (cc->node_load,0 ,sizeof (cc->node_load));nodes_clear (cc->alloc_nmask); + + enabled_orders =collapse_possible_orders (vma, vma->vm_flags, tva_flags); + +/* +* If PMD is the only enabled order, enforce max_ptes_none, otherwise +* scan all pages to populate the bitmap for mTHP collapse. +*/ +if (enabled_orders !=BIT (HPAGE_PMD_ORDER )) + max_ptes_none =KHUGEPAGED_MAX_PTES_LIMIT ; + pte =pte_offset_map_lock (mm, pmd, start_addr, &ptl);if (!pte) { cc->progress++;
@@ -1474,11 +1600,13 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, goto out; } -for (addr = start_addr, _pte = pte; _pte < pte +HPAGE_PMD_NR ; - _pte++, addr +=PAGE_SIZE ) { +for (i =0 ; i <HPAGE_PMD_NR ; i++) { + _pte = pte + i; + addr = start_addr + i *PAGE_SIZE ; + pteval =ptep_get (_pte); + cc->progress++; -pte_t pteval =ptep_get (_pte);if (pte_none_or_zero (pteval)) {if (++none_or_zero > max_ptes_none) { result =SCAN_EXCEED_NONE_PTE ;
@@ -1558,6 +1686,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, } } +/* Set bit for occupied pages */ +__set_bit (i, cc->mthp_present_ptes);/* * Record which node the original page is from and save this * information to cc->node_load[].
@@ -1616,9 +1746,9 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,if (result ==SCAN_SUCCEED ) {/* collapse_huge_page expects the lock to be dropped before calling */ mmap_read_unlock (mm); - result =collapse_huge_page (mm, start_addr, referenced, - unmapped, cc,HPAGE_PMD_ORDER ); -/* collapse_huge_page will return with the mmap_lock released */ + result =mthp_collapse (mm, start_addr, referenced, + unmapped, cc, enabled_orders); +/* mmap_lock was released above, set lock_dropped */ *lock_dropped = true; } out:
Signature · 1 line
2.54.0
Re: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 67 lines · Nico Pache
Enable khugepaged to collapse to mTHP orders. This patch implements the main scanning logic using a bitmap to track occupied pages and the algorithm to find optimal collapse sizes.
Previous to this patch, PMD collapse had 3 main phases, a light weight scanning phase (
mmap_read_lock) that determines a potential PMD collapse, an alloc phase (mmap unlocked), then finally heavier collapse phase (mmap_write_lock).To enabled mTHP collapse we make the following changes:
During PMD scan phase, track occupied pages in a bitmap. When mTHP orders are enabled, we remove the restriction of
max_ptes_noneduring the scan phase to avoid missing potential mTHP collapse candidates. Once we have scanned the full PMD range and updated the bitmap to track occupied pages, we use the bitmap to find the optimal mTHP size.Implement
mthp_collapse()to walk forward through the bitmap and determine the best eligible order for each naturally-aligned region. The algorithm starts at the beginning of the PMD range and, for each offset, tries the highest order that fits the alignment. If the number of occupied PTEs in that region satisfies themax_ptes_nonethreshold for that order, a collapse is attempted. On failure, the order is decremented and the same offset is retried at the next smaller size. Once the smallest enabled order is exhausted (or a collapse succeeds), the offset advances past the region just processed, and the next attempt starts at the highest order permitted by the new offset's natural alignment.The algorithm works as follows:
1) set offset=0 and order=HPAGE_PMD_ORDER
2) if the order is not enabled, go to step (5)
3) count occupied PTEs in the (offset, order) range usingbitmap_weight_from()
4) if the count satisfies themax_ptes_nonethreshold, attempt collapse; on success, advance to step (6)
5) if a smaller enabled order exists, decrement order and retry from step (2) at the same offset
6) advance offset past the current region and compute the next order from the new offset's natural alignment via__ffs(offset), capped atHPAGE_PMD_ORDER
7) repeat from step (2) until the full PMD range is coveredmTHP collapses reject regions containing swapped out or shared pages. This is because adding new entries can lead to new none pages, and these may lead to constant promotion into a higher order mTHP. A similar issue can occur with "
max_ptes_none> HPAGE_PMD_NR/2" due to a collapse introducing at least 2x the number of pages, and on a future scan will satisfy the promotion condition once again. This issue is prevented via thecollapse_max_ptes_none()function which imposes themax_ptes_nonerestrictions above.We currently only support mTHP collapse for
max_ptes_nonevalues of 0 andHPAGE_PMD_NR- 1. resulting in the following behavior:- max_ptes_none=0: Never introduce new empty pages during collapse
- max_ptes_none=HPAGE_PMD_NR-1: Always try collapse to the highest available mTHP orderAny other
max_ptes_nonevalue will emit a warning and default mTHP collapse to max_ptes_none=0. There should be no behavior change for PMD collapse.Once we determine what mTHP sizes fits best in that PMD range a collapse is attempted. A minimum collapse order of 2 is used as this is the lowest order supported by anon memory as defined by
THP_ORDERS_ALL_ANON.
Quoted 8 lines
Currently
madv_collapseis not supported and will only attempt PMD collapse.We can also remove the check for
is_khugepagedinside the PMD scan as thecollapse_max_ptes_none()function handles this logic now.Signed-off-by Nico Pache <[email protected]>---
Yeah, overall much simpler and much easier to get. As discussed, we can optimize this later to traverse enabled orders more efficiently.
mm/khugepaged.c static enum scan_result collapse_scan_pmd(struct mm_struct *mm, · line 1592
Quoted 10 lines
mm/khugepaged.c +8
-0+bitmap_zero (cc->mthp_present_ptes,MAX_PTRS_PER_PTE );memset (cc->node_load,0 ,sizeof (cc->node_load));nodes_clear (cc->alloc_nmask); + + enabled_orders =collapse_possible_orders (vma, vma->vm_flags, tva_flags); + +/* +* If PMD is the only enabled order, enforce max_ptes_none, otherwise +* scan all pages to populate the bitmap for mTHP collapse. +*/
I think it would have been good to mention where the check is performed for mTHP collapse. Can be added later.
Signature · 3 lines
Cheers, David
Re: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
In reply to Nico PacheQuoted 17 lines · Nico Pache
Enable khugepaged to collapse to mTHP orders. This patch implements the main scanning logic using a bitmap to track occupied pages and the algorithm to find optimal collapse sizes.
Previous to this patch, PMD collapse had 3 main phases, a light weight scanning phase (
mmap_read_lock) that determines a potential PMD collapse, an alloc phase (mmap unlocked), then finally heavier collapse phase (mmap_write_lock).To enabled mTHP collapse we make the following changes:
During PMD scan phase, track occupied pages in a bitmap. When mTHP orders are enabled, we remove the restriction of
max_ptes_noneduring the scan phase to avoid missing potential mTHP collapse candidates. Once we have scanned the full PMD range and updated the bitmap to track occupied pages, we use the bitmap to find the optimal mTHP size.
Quoted 11 lines
Implement
mthp_collapse()to walk forward through the bitmap and determine the best eligible order for each naturally-aligned region. The algorithm starts at the beginning of the PMD range and, for each offset, tries the highest order that fits the alignment. If the number of occupied PTEs in that region satisfies themax_ptes_nonethreshold for that order, a collapse is attempted. On failure, the order is decremented and the same offset is retried at the next smaller size. Once the smallest enabled order is exhausted (or a collapse succeeds), the offset advances past the region just processed, and the next attempt starts at the highest order permitted by the new offset's natural alignment.
I think still it might have been nice to discuss why we are not e.g. greedily trying to find the biggest possible mTHP size (if we did, we would try the highest offset first), but we can save that for adding some documentation somewhere later tbh.
This commit message is long enough as it is :>)
Quoted 39 lines
The algorithm works as follows:
1) set offset=0 and order=HPAGE_PMD_ORDER
2) if the order is not enabled, go to step (5)
3) count occupied PTEs in the (offset, order) range usingbitmap_weight_from()
4) if the count satisfies themax_ptes_nonethreshold, attempt collapse; on success, advance to step (6)
5) if a smaller enabled order exists, decrement order and retry from step (2) at the same offset
6) advance offset past the current region and compute the next order from the new offset's natural alignment via__ffs(offset), capped atHPAGE_PMD_ORDER
7) repeat from step (2) until the full PMD range is coveredmTHP collapses reject regions containing swapped out or shared pages. This is because adding new entries can lead to new none pages, and these may lead to constant promotion into a higher order mTHP. A similar issue can occur with "
max_ptes_none> HPAGE_PMD_NR/2" due to a collapse introducing at least 2x the number of pages, and on a future scan will satisfy the promotion condition once again. This issue is prevented via thecollapse_max_ptes_none()function which imposes themax_ptes_nonerestrictions above.We currently only support mTHP collapse for
max_ptes_nonevalues of 0 andHPAGE_PMD_NR- 1. resulting in the following behavior:- max_ptes_none=0: Never introduce new empty pages during collapse
- max_ptes_none=HPAGE_PMD_NR-1: Always try collapse to the highest available mTHP orderAny other
max_ptes_nonevalue will emit a warning and default mTHP collapse to max_ptes_none=0. There should be no behavior change for PMD collapse.Once we determine what mTHP sizes fits best in that PMD range a collapse is attempted. A minimum collapse order of 2 is used as this is the lowest order supported by anon memory as defined by
THP_ORDERS_ALL_ANON.
Quoted 5 lines
Currently
madv_collapseis not supported and will only attempt PMD collapse.We can also remove the check for
is_khugepagedinside the PMD scan as thecollapse_max_ptes_none()function handles this logic now.
It'd be nice to have kept the ASCII diagram here too :'( but this is fine,
Quoted 2 lines
Signed-off-by Nico Pache <[email protected]>
This all LGTM, and we can fix up any issues that arise later if anything does break. So:
Quoted 29 lines
--- mm/khugepaged.c | 146 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 138 insertions(+), 8 deletions(-)mm/khugepaged.c +5
-0@@ -99,6 +99,8 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);static struct kmem_cache *mm_slot_cache__ro_after_init ; +#define KHUGEPAGED_MIN_MTHP_ORDER 2 +struct collapse_control {bool is_khugepaged;@@ -110,6 +112,9 @@ struct collapse_control {/* nodemask for allocation fallback */ nodemask_t alloc_nmask; + +/* Each bit represents a single occupied (!none/zero) page. */ +DECLARE_BITMAP (mthp_present_ptes,MAX_PTRS_PER_PTE ); };/** @@ -1440,20 +1445,130 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long sreturn result;
mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1455
Quoted 10 lines
mm/khugepaged.c +8
-0} +/* Return the highest naturally aligned order that fits at @offset within a PMD. */ +static unsigned int max_order_from_offset (unsigned int offset) +{ +if (offset ==0 ) +return HPAGE_PMD_ORDER ; + + return min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER); +}
Thanks this is better! I wonder if we can ever actually see an __ffs(offset) that's > HPAGE_PMD_ORDER but probably better safe than sorry here with the min_t.
Quoted 65 lines
mm/khugepaged.c +65
-0+ +/* +* mthp_collapse() consumes the bitmap that is generated during +* collapse_scan_pmd() to determine what regions and mTHP orders fit best. +* +* Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero) +* page. We start at the PMD order and check if it is eligible for collapse; +* if not, we check the left and right halves of the PTE page table we are +* examining at a lower order. +* +* For each of these, we determine how many PTE entries are occupied in the +* range of PTE entries we propose to collapse, then we compare this to a +* threshold number of PTE entries which would need to be occupied for a +* collapse to be permitted at that order (accounting for max_ptes_none). +* +* If a collapse is permitted, we attempt to collapse the PTE range into a +* mTHP. +*/ +static enum scan_result mthp_collapse (struct mm_struct *mm, +unsigned long address,int referenced,int unmapped, +struct collapse_control *cc,unsigned long enabled_orders) +{ +unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none; +enum scan_result last_result =SCAN_FAIL ; +int collapsed =0 ; +bool alloc_failed = false; +unsigned long collapse_address; +unsigned int offset =0 ; +unsigned int order =HPAGE_PMD_ORDER ; + +while (offset <HPAGE_PMD_NR ) { + nr_ptes =1UL << order; + +if (!test_bit (order, &enabled_orders)) + goto next_order; + + max_ptes_none =collapse_max_ptes_none (cc,NULL , order); + nr_occupied_ptes =bitmap_weight_from (cc->mthp_present_ptes, offset, + offset + nr_ptes); + +if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { +enum scan_result ret; + + collapse_address = address + offset *PAGE_SIZE ; + ret =collapse_huge_page (mm, collapse_address, referenced, + unmapped, cc, order); +switch (ret) { +/* Cases where we continue to next collapse candidate */ +case SCAN_SUCCEED : + collapsed += nr_ptes; + fallthrough; +case SCAN_PTE_MAPPED_HUGEPAGE : + goto next_offset; +/* Cases where lower orders might still succeed */ +case SCAN_ALLOC_HUGE_PAGE_FAIL : + alloc_failed = true; + last_result = ret; + goto next_order; +/* Cases where no further collapse is possible */ +case SCAN_PMD_MAPPED : + fallthrough; +default : + last_result = ret; + goto done; + }
mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1530
Quoted 10 lines
mm/khugepaged.c +10
-0+ } + +next_order: +/* +* Continue with the next smaller order if there is still +* any smaller order enabled. When at the smallest order +* we must always move to the next offset. +*/ +if (order >KHUGEPAGED_MIN_MTHP_ORDER && + (enabled_orders &GENMASK (order -1 ,0 ))) {
Honestly wasn't aware of GENMASK() before :)
mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1543
Quoted 13 lines
mm/khugepaged.c +13
-0+ order--; +continue ; + } +next_offset: +/* +* Advance past the region we just processed and determine the +* highest order we can attempt next. Since huge pages must be +* naturally aligned, the max order we can attempt next is +* limited by the alignment of the new offset. +* E.g. if we collapsed a order-2 mTHP at offset 0, offset +* becomes 4 and __ffs(4) == 2, so the next attempt starts at +* order 2. +*/
Great comment thanks!
Quoted 93 lines
mm/khugepaged.c +37
-9+ offset += nr_ptes; + order =max_order_from_offset (offset); + } +done: +if (collapsed) +return SCAN_SUCCEED ; +if (alloc_failed) +return SCAN_ALLOC_HUGE_PAGE_FAIL ; +return last_result; +} +static enum scan_result collapse_scan_pmd (struct mm_struct *mm,struct vm_area_struct *vma,unsigned long start_addr,bool *lock_dropped,struct collapse_control *cc) { -const unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma,HPAGE_PMD_ORDER );const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc,HPAGE_PMD_ORDER );const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc,HPAGE_PMD_ORDER ); +unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma,HPAGE_PMD_ORDER ); +enum tva_type tva_flags = cc->is_khugepaged ?TVA_KHUGEPAGED :TVA_FORCED_COLLAPSE ;pmd_t *pmd; -pte_t *pte, *_pte; +pte_t *pte, *_pte, pteval; +int i;int none_or_zero =0 , shared =0 , referenced =0 ;enum scan_result result =SCAN_FAIL ;struct page *page =NULL ;struct folio *folio =NULL ;unsigned long addr; +unsigned long enabled_orders;spinlock_t *ptl;int node =NUMA_NO_NODE , unmapped =0 ;@@ -1465,8 +1580,19 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, goto out; } +bitmap_zero (cc->mthp_present_ptes,MAX_PTRS_PER_PTE );memset (cc->node_load,0 ,sizeof (cc->node_load));nodes_clear (cc->alloc_nmask); + + enabled_orders =collapse_possible_orders (vma, vma->vm_flags, tva_flags); + +/* +* If PMD is the only enabled order, enforce max_ptes_none, otherwise +* scan all pages to populate the bitmap for mTHP collapse. +*/ +if (enabled_orders !=BIT (HPAGE_PMD_ORDER )) + max_ptes_none =KHUGEPAGED_MAX_PTES_LIMIT ; + pte =pte_offset_map_lock (mm, pmd, start_addr, &ptl);if (!pte) { cc->progress++;@@ -1474,11 +1600,13 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, goto out; } -for (addr = start_addr, _pte = pte; _pte < pte +HPAGE_PMD_NR ; - _pte++, addr +=PAGE_SIZE ) { +for (i =0 ; i <HPAGE_PMD_NR ; i++) { + _pte = pte + i; + addr = start_addr + i *PAGE_SIZE ; + pteval =ptep_get (_pte); + cc->progress++; -pte_t pteval =ptep_get (_pte);if (pte_none_or_zero (pteval)) {if (++none_or_zero > max_ptes_none) { result =SCAN_EXCEED_NONE_PTE ;@@ -1558,6 +1686,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, } } +/* Set bit for occupied pages */ +__set_bit (i, cc->mthp_present_ptes);/* * Record which node the original page is from and save this * information to cc->node_load[]. @@ -1616,9 +1746,9 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,if (result ==SCAN_SUCCEED ) {/* collapse_huge_page expects the lock to be dropped before calling */ mmap_read_unlock (mm); - result =collapse_huge_page (mm, start_addr, referenced, - unmapped, cc,HPAGE_PMD_ORDER ); -/* collapse_huge_page will return with the mmap_lock released */ + result =mthp_collapse (mm, start_addr, referenced, + unmapped, cc, enabled_orders); +/* mmap_lock was released above, set lock_dropped */ *lock_dropped = true; } out: --
Quoted 2 lines
2.54.0
Cheers, Lorenzo
Re: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 31 lines · Lorenzo Stoakes
Quoted 17 lines · Nico Pache
Enable khugepaged to collapse to mTHP orders. This patch implements the main scanning logic using a bitmap to track occupied pages and the algorithm to find optimal collapse sizes.
Previous to this patch, PMD collapse had 3 main phases, a light weight scanning phase (
mmap_read_lock) that determines a potential PMD collapse, an alloc phase (mmap unlocked), then finally heavier collapse phase (mmap_write_lock).To enabled mTHP collapse we make the following changes:
During PMD scan phase, track occupied pages in a bitmap. When mTHP orders are enabled, we remove the restriction of
max_ptes_noneduring the scan phase to avoid missing potential mTHP collapse candidates. Once we have scanned the full PMD range and updated the bitmap to track occupied pages, we use the bitmap to find the optimal mTHP size.Quoted 11 lines
Implement
mthp_collapse()to walk forward through the bitmap and determine the best eligible order for each naturally-aligned region. The algorithm starts at the beginning of the PMD range and, for each offset, tries the highest order that fits the alignment. If the number of occupied PTEs in that region satisfies themax_ptes_nonethreshold for that order, a collapse is attempted. On failure, the order is decremented and the same offset is retried at the next smaller size. Once the smallest enabled order is exhausted (or a collapse succeeds), the offset advances past the region just processed, and the next attempt starts at the highest order permitted by the new offset's natural alignment.
Quoted 4 lines
I think still it might have been nice to discuss why we are not e.g. greedily trying to find the biggest possible mTHP size (if we did, we would try the highest offset first), but we can save that for adding some documentation somewhere later tbh.
We are, the algorithm tries PMD, then order 8, then order 7, and so on. Due to the required alignment, if the N-1 order succeeds, we try the same order at the neighboring offset.
So if we collapse a order 8, the following collapse attempt will be order 8 at 256. We always try the highest order allowed for a given offset :)
Quoted 51 lines
This commit message is long enough as it is :>)
Quoted 39 lines
The algorithm works as follows:
1) set offset=0 and order=HPAGE_PMD_ORDER
2) if the order is not enabled, go to step (5)
3) count occupied PTEs in the (offset, order) range usingbitmap_weight_from()
4) if the count satisfies themax_ptes_nonethreshold, attempt collapse; on success, advance to step (6)
5) if a smaller enabled order exists, decrement order and retry from step (2) at the same offset
6) advance offset past the current region and compute the next order from the new offset's natural alignment via__ffs(offset), capped atHPAGE_PMD_ORDER
7) repeat from step (2) until the full PMD range is coveredmTHP collapses reject regions containing swapped out or shared pages. This is because adding new entries can lead to new none pages, and these may lead to constant promotion into a higher order mTHP. A similar issue can occur with "
max_ptes_none> HPAGE_PMD_NR/2" due to a collapse introducing at least 2x the number of pages, and on a future scan will satisfy the promotion condition once again. This issue is prevented via thecollapse_max_ptes_none()function which imposes themax_ptes_nonerestrictions above.We currently only support mTHP collapse for
max_ptes_nonevalues of 0 andHPAGE_PMD_NR- 1. resulting in the following behavior:- max_ptes_none=0: Never introduce new empty pages during collapse
- max_ptes_none=HPAGE_PMD_NR-1: Always try collapse to the highest available mTHP orderAny other
max_ptes_nonevalue will emit a warning and default mTHP collapse to max_ptes_none=0. There should be no behavior change for PMD collapse.Once we determine what mTHP sizes fits best in that PMD range a collapse is attempted. A minimum collapse order of 2 is used as this is the lowest order supported by anon memory as defined by
THP_ORDERS_ALL_ANON.Quoted 5 lines
Currently
madv_collapseis not supported and will only attempt PMD collapse.We can also remove the check for
is_khugepagedinside the PMD scan as thecollapse_max_ptes_none()function handles this logic now.It'd be nice to have kept the ASCII diagram here too :'( but this is fine,
Quoted 1 line
Quoted 6 lines
Quoted 1 line
Signed-off-by Nico Pache <[email protected]>This all LGTM, and we can fix up any issues that arise later if anything does break. So:
Reviewed-by Lorenzo Stoakes <[email protected]>
Thanks for reviewing :)
Quoted 32 lines
Quoted 32 lines
--- mm/khugepaged.c | 146 +++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 138 insertions(+), 8 deletions(-)mm/khugepaged.c +5
-0@@ -99,6 +99,8 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);static struct kmem_cache *mm_slot_cache__ro_after_init ; +#define KHUGEPAGED_MIN_MTHP_ORDER 2 +struct collapse_control {bool is_khugepaged;@@ -110,6 +112,9 @@ struct collapse_control {/* nodemask for allocation fallback */ nodemask_t alloc_nmask; + +/* Each bit represents a single occupied (!none/zero) page. */ +DECLARE_BITMAP (mthp_present_ptes,MAX_PTRS_PER_PTE ); };/** @@ -1440,20 +1445,130 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long sreturn result; }
Quoted 12 lines
mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1455
Quoted 8 lines
mm/khugepaged.c +8
-0+/* Return the highest naturally aligned order that fits at @offset within a PMD. */ +static unsigned int max_order_from_offset (unsigned int offset) +{ +if (offset ==0 ) +return HPAGE_PMD_ORDER ; + + return min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER); +}Thanks this is better! I wonder if we can ever actually see an
__ffs(offset)that's >HPAGE_PMD_ORDERbut probably better safe than sorry here with themin_t.
I don't think so unless offset somehow exceeds 512 (it shouldn't), but like you said, better safe than sorry.
Quoted 70 lines
Quoted 70 lines
mm/khugepaged.c +69
-0+ +/* +* mthp_collapse() consumes the bitmap that is generated during +* collapse_scan_pmd() to determine what regions and mTHP orders fit best. +* +* Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero) +* page. We start at the PMD order and check if it is eligible for collapse; +* if not, we check the left and right halves of the PTE page table we are +* examining at a lower order. +* +* For each of these, we determine how many PTE entries are occupied in the +* range of PTE entries we propose to collapse, then we compare this to a +* threshold number of PTE entries which would need to be occupied for a +* collapse to be permitted at that order (accounting for max_ptes_none). +* +* If a collapse is permitted, we attempt to collapse the PTE range into a +* mTHP. +*/ +static enum scan_result mthp_collapse (struct mm_struct *mm, +unsigned long address,int referenced,int unmapped, +struct collapse_control *cc,unsigned long enabled_orders) +{ +unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none; +enum scan_result last_result =SCAN_FAIL ; +int collapsed =0 ; +bool alloc_failed = false; +unsigned long collapse_address; +unsigned int offset =0 ; +unsigned int order =HPAGE_PMD_ORDER ; + +while (offset <HPAGE_PMD_NR ) { + nr_ptes =1UL << order; + +if (!test_bit (order, &enabled_orders)) + goto next_order; + + max_ptes_none =collapse_max_ptes_none (cc,NULL , order); + nr_occupied_ptes =bitmap_weight_from (cc->mthp_present_ptes, offset, + offset + nr_ptes); + +if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { +enum scan_result ret; + + collapse_address = address + offset *PAGE_SIZE ; + ret =collapse_huge_page (mm, collapse_address, referenced, + unmapped, cc, order); +switch (ret) { +/* Cases where we continue to next collapse candidate */ +case SCAN_SUCCEED : + collapsed += nr_ptes; + fallthrough; +case SCAN_PTE_MAPPED_HUGEPAGE : + goto next_offset; +/* Cases where lower orders might still succeed */ +case SCAN_ALLOC_HUGE_PAGE_FAIL : + alloc_failed = true; + last_result = ret; + goto next_order; +/* Cases where no further collapse is possible */ +case SCAN_PMD_MAPPED : + fallthrough; +default : + last_result = ret; + goto done; + } + } + +next_order: +/*
Quoted 8 lines
mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1530
Quoted 6 lines
mm/khugepaged.c +6
-0+* Continue with the next smaller order if there is still +* any smaller order enabled. When at the smallest order +* we must always move to the next offset. +*/ +if (order >KHUGEPAGED_MIN_MTHP_ORDER && + (enabled_orders &GENMASK (order -1 ,0 ))) {Honestly wasn't aware of
GENMASK()before :)
I wasn't either! (thanks David ;) )
Quoted 115 lines
Quoted 4 lines
mm/khugepaged.c +3
-0+ order--; +continue ; + }mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1543
Quoted 10 lines
mm/khugepaged.c +10
-0+next_offset: +/* +* Advance past the region we just processed and determine the +* highest order we can attempt next. Since huge pages must be +* naturally aligned, the max order we can attempt next is +* limited by the alignment of the new offset. +* E.g. if we collapsed a order-2 mTHP at offset 0, offset +* becomes 4 and __ffs(4) == 2, so the next attempt starts at +* order 2. +*/ Great comment thanks!
Quoted 93 lines
mm/khugepaged.c +37
-9+ offset += nr_ptes; + order =max_order_from_offset (offset); + } +done: +if (collapsed) +return SCAN_SUCCEED ; +if (alloc_failed) +return SCAN_ALLOC_HUGE_PAGE_FAIL ; +return last_result; +} +static enum scan_result collapse_scan_pmd (struct mm_struct *mm,struct vm_area_struct *vma,unsigned long start_addr,bool *lock_dropped,struct collapse_control *cc) { -const unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma,HPAGE_PMD_ORDER );const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc,HPAGE_PMD_ORDER );const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc,HPAGE_PMD_ORDER ); +unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma,HPAGE_PMD_ORDER ); +enum tva_type tva_flags = cc->is_khugepaged ?TVA_KHUGEPAGED :TVA_FORCED_COLLAPSE ;pmd_t *pmd; -pte_t *pte, *_pte; +pte_t *pte, *_pte, pteval; +int i;int none_or_zero =0 , shared =0 , referenced =0 ;enum scan_result result =SCAN_FAIL ;struct page *page =NULL ;struct folio *folio =NULL ;unsigned long addr; +unsigned long enabled_orders;spinlock_t *ptl;int node =NUMA_NO_NODE , unmapped =0 ;@@ -1465,8 +1580,19 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, goto out; } +bitmap_zero (cc->mthp_present_ptes,MAX_PTRS_PER_PTE );memset (cc->node_load,0 ,sizeof (cc->node_load));nodes_clear (cc->alloc_nmask); + + enabled_orders =collapse_possible_orders (vma, vma->vm_flags, tva_flags); + +/* +* If PMD is the only enabled order, enforce max_ptes_none, otherwise +* scan all pages to populate the bitmap for mTHP collapse. +*/ +if (enabled_orders !=BIT (HPAGE_PMD_ORDER )) + max_ptes_none =KHUGEPAGED_MAX_PTES_LIMIT ; + pte =pte_offset_map_lock (mm, pmd, start_addr, &ptl);if (!pte) { cc->progress++;@@ -1474,11 +1600,13 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, goto out; } -for (addr = start_addr, _pte = pte; _pte < pte +HPAGE_PMD_NR ; - _pte++, addr +=PAGE_SIZE ) { +for (i =0 ; i <HPAGE_PMD_NR ; i++) { + _pte = pte + i; + addr = start_addr + i *PAGE_SIZE ; + pteval =ptep_get (_pte); + cc->progress++; -pte_t pteval =ptep_get (_pte);if (pte_none_or_zero (pteval)) {if (++none_or_zero > max_ptes_none) { result =SCAN_EXCEED_NONE_PTE ;@@ -1558,6 +1686,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, } } +/* Set bit for occupied pages */ +__set_bit (i, cc->mthp_present_ptes);/* * Record which node the original page is from and save this * information to cc->node_load[]. @@ -1616,9 +1746,9 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,if (result ==SCAN_SUCCEED ) {/* collapse_huge_page expects the lock to be dropped before calling */ mmap_read_unlock (mm); - result =collapse_huge_page (mm, start_addr, referenced, - unmapped, cc,HPAGE_PMD_ORDER ); -/* collapse_huge_page will return with the mmap_lock released */ + result =mthp_collapse (mm, start_addr, referenced, + unmapped, cc, enabled_orders); +/* mmap_lock was released above, set lock_dropped */ *lock_dropped = true; } out: --Quoted 2 lines
2.54.0
Cheers, Lorenzo
Lance Yang
reviewerRe: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
In reply to Nico PacheQuoted 144 lines · Nico Pache
Enable khugepaged to collapse to mTHP orders. This patch implements the main scanning logic using a bitmap to track occupied pages and the algorithm to find optimal collapse sizes.
Previous to this patch, PMD collapse had 3 main phases, a light weight scanning phase (
mmap_read_lock) that determines a potential PMD collapse, an alloc phase (mmap unlocked), then finally heavier collapse phase (mmap_write_lock).To enabled mTHP collapse we make the following changes:
During PMD scan phase, track occupied pages in a bitmap. When mTHP orders are enabled, we remove the restriction of
max_ptes_noneduring the scan phase to avoid missing potential mTHP collapse candidates. Once we have scanned the full PMD range and updated the bitmap to track occupied pages, we use the bitmap to find the optimal mTHP size.Implement
mthp_collapse()to walk forward through the bitmap and determine the best eligible order for each naturally-aligned region. The algorithm starts at the beginning of the PMD range and, for each offset, tries the highest order that fits the alignment. If the number of occupied PTEs in that region satisfies themax_ptes_nonethreshold for that order, a collapse is attempted. On failure, the order is decremented and the same offset is retried at the next smaller size. Once the smallest enabled order is exhausted (or a collapse succeeds), the offset advances past the region just processed, and the next attempt starts at the highest order permitted by the new offset's natural alignment.The algorithm works as follows:
1) set offset=0 and order=HPAGE_PMD_ORDER
2) if the order is not enabled, go to step (5)
3) count occupied PTEs in the (offset, order) range usingbitmap_weight_from()
4) if the count satisfies themax_ptes_nonethreshold, attempt collapse; on success, advance to step (6)
5) if a smaller enabled order exists, decrement order and retry from step (2) at the same offset
6) advance offset past the current region and compute the next order from the new offset's natural alignment via__ffs(offset), capped atHPAGE_PMD_ORDER
7) repeat from step (2) until the full PMD range is coveredmTHP collapses reject regions containing swapped out or shared pages. This is because adding new entries can lead to new none pages, and these may lead to constant promotion into a higher order mTHP. A similar issue can occur with "
max_ptes_none> HPAGE_PMD_NR/2" due to a collapse introducing at least 2x the number of pages, and on a future scan will satisfy the promotion condition once again. This issue is prevented via thecollapse_max_ptes_none()function which imposes themax_ptes_nonerestrictions above.We currently only support mTHP collapse for
max_ptes_nonevalues of 0 andHPAGE_PMD_NR- 1. resulting in the following behavior:- max_ptes_none=0: Never introduce new empty pages during collapse
- max_ptes_none=HPAGE_PMD_NR-1: Always try collapse to the highest available mTHP orderAny other
max_ptes_nonevalue will emit a warning and default mTHP collapse to max_ptes_none=0. There should be no behavior change for PMD collapse.Once we determine what mTHP sizes fits best in that PMD range a collapse is attempted. A minimum collapse order of 2 is used as this is the lowest order supported by anon memory as defined by
THP_ORDERS_ALL_ANON.Currently
madv_collapseis not supported and will only attempt PMD collapse.We can also remove the check for
is_khugepagedinside the PMD scan as thecollapse_max_ptes_none()function handles this logic now.Signed-off-by Nico Pache <[email protected]>---
mm/khugepaged.c| 146 +++++++++++++++++++++++++++++++++++++++++++++---1 file changed, 138 insertions(+), 8 deletions(-)mm/khugepaged.c +44
-0@@ -99,6 +99,8 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);static struct kmem_cache *mm_slot_cache__ro_after_init ; +#define KHUGEPAGED_MIN_MTHP_ORDER 2 +struct collapse_control {bool is_khugepaged;@@ -110,6 +112,9 @@ struct collapse_control {/* nodemask for allocation fallback */ nodemask_t alloc_nmask; + +/* Each bit represents a single occupied (!none/zero) page. */ +DECLARE_BITMAP (mthp_present_ptes,MAX_PTRS_PER_PTE ); };/** @@ -1440,20 +1445,130 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long sreturn result; } +/* Return the highest naturally aligned order that fits at @offset within a PMD. */ +static unsigned int max_order_from_offset (unsigned int offset) +{ +if (offset ==0 ) +return HPAGE_PMD_ORDER ; + + return min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER); +} + +/* +* mthp_collapse() consumes the bitmap that is generated during +* collapse_scan_pmd() to determine what regions and mTHP orders fit best. +* +* Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero) +* page. We start at the PMD order and check if it is eligible for collapse; +* if not, we check the left and right halves of the PTE page table we are +* examining at a lower order. +* +* For each of these, we determine how many PTE entries are occupied in the +* range of PTE entries we propose to collapse, then we compare this to a +* threshold number of PTE entries which would need to be occupied for a +* collapse to be permitted at that order (accounting for max_ptes_none). +* +* If a collapse is permitted, we attempt to collapse the PTE range into a +* mTHP. +*/ +static enum scan_result mthp_collapse (struct mm_struct *mm, +unsigned long address,int referenced,int unmapped, +struct collapse_control *cc,unsigned long enabled_orders) +{ +unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none; +enum scan_result last_result =SCAN_FAIL ; +int collapsed =0 ; +bool alloc_failed = false; +unsigned long collapse_address; +unsigned int offset =0 ; +unsigned int order =HPAGE_PMD_ORDER ; + +while (offset <HPAGE_PMD_NR ) {
mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1496
Quoted 10 lines
mm/khugepaged.c +10
-0+ nr_ptes =1UL << order; + +if (!test_bit (order, &enabled_orders)) + goto next_order; + + max_ptes_none =collapse_max_ptes_none (cc,NULL , order); + nr_occupied_ptes =bitmap_weight_from (cc->mthp_present_ptes, offset, + offset + nr_ptes); + +if (nr_occupied_ptes >= nr_ptes - max_ptes_none) {
Looks broken for swap PTEs in PMD collapse ...
collapse_scan_pmd() allows them up to max_ptes_swap and record them in unmapped, but they don't get a bit in mthp_present_ptes. And then mthp_collapse() does the check above:
nr_occupied_ptes >= nr_ptes - max_ptes_none
So max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call collapse_huge_page() for PMD order.
Shouldn't we account for them in the PMD-order check? Something like:
if (is_pmd_order(order))
nr_occupied_ptes += unmapped;
Cheers, Lance
Quoted 143 lines
mm/khugepaged.c +84
-8+enum scan_result ret; + + collapse_address = address + offset *PAGE_SIZE ; + ret =collapse_huge_page (mm, collapse_address, referenced, + unmapped, cc, order); +switch (ret) { +/* Cases where we continue to next collapse candidate */ +case SCAN_SUCCEED : + collapsed += nr_ptes; + fallthrough; +case SCAN_PTE_MAPPED_HUGEPAGE : + goto next_offset; +/* Cases where lower orders might still succeed */ +case SCAN_ALLOC_HUGE_PAGE_FAIL : + alloc_failed = true; + last_result = ret; + goto next_order; +/* Cases where no further collapse is possible */ +case SCAN_PMD_MAPPED : + fallthrough; +default : + last_result = ret; + goto done; + } + } + +next_order: +/* +* Continue with the next smaller order if there is still +* any smaller order enabled. When at the smallest order +* we must always move to the next offset. +*/ +if (order >KHUGEPAGED_MIN_MTHP_ORDER && + (enabled_orders &GENMASK (order -1 ,0 ))) { + order--; +continue ; + } +next_offset: +/* +* Advance past the region we just processed and determine the +* highest order we can attempt next. Since huge pages must be +* naturally aligned, the max order we can attempt next is +* limited by the alignment of the new offset. +* E.g. if we collapsed a order-2 mTHP at offset 0, offset +* becomes 4 and __ffs(4) == 2, so the next attempt starts at +* order 2. +*/ + offset += nr_ptes; + order =max_order_from_offset (offset); + } +done: +if (collapsed) +return SCAN_SUCCEED ; +if (alloc_failed) +return SCAN_ALLOC_HUGE_PAGE_FAIL ; +return last_result; +} +static enum scan_result collapse_scan_pmd (struct mm_struct *mm,struct vm_area_struct *vma,unsigned long start_addr,bool *lock_dropped,struct collapse_control *cc) { -const unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma,HPAGE_PMD_ORDER );const unsigned int max_ptes_shared =collapse_max_ptes_shared (cc,HPAGE_PMD_ORDER );const unsigned int max_ptes_swap =collapse_max_ptes_swap (cc,HPAGE_PMD_ORDER ); +unsigned int max_ptes_none =collapse_max_ptes_none (cc, vma,HPAGE_PMD_ORDER ); +enum tva_type tva_flags = cc->is_khugepaged ?TVA_KHUGEPAGED :TVA_FORCED_COLLAPSE ;pmd_t *pmd; -pte_t *pte, *_pte; +pte_t *pte, *_pte, pteval; +int i;int none_or_zero =0 , shared =0 , referenced =0 ;enum scan_result result =SCAN_FAIL ;struct page *page =NULL ;struct folio *folio =NULL ;unsigned long addr; +unsigned long enabled_orders;spinlock_t *ptl;int node =NUMA_NO_NODE , unmapped =0 ;@@ -1465,8 +1580,19 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, goto out; } +bitmap_zero (cc->mthp_present_ptes,MAX_PTRS_PER_PTE );memset (cc->node_load,0 ,sizeof (cc->node_load));nodes_clear (cc->alloc_nmask); + + enabled_orders =collapse_possible_orders (vma, vma->vm_flags, tva_flags); + +/* +* If PMD is the only enabled order, enforce max_ptes_none, otherwise +* scan all pages to populate the bitmap for mTHP collapse. +*/ +if (enabled_orders !=BIT (HPAGE_PMD_ORDER )) + max_ptes_none =KHUGEPAGED_MAX_PTES_LIMIT ; + pte =pte_offset_map_lock (mm, pmd, start_addr, &ptl);if (!pte) { cc->progress++;@@ -1474,11 +1600,13 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, goto out; } -for (addr = start_addr, _pte = pte; _pte < pte +HPAGE_PMD_NR ; - _pte++, addr +=PAGE_SIZE ) { +for (i =0 ; i <HPAGE_PMD_NR ; i++) { + _pte = pte + i; + addr = start_addr + i *PAGE_SIZE ; + pteval =ptep_get (_pte); + cc->progress++; -pte_t pteval =ptep_get (_pte);if (pte_none_or_zero (pteval)) {if (++none_or_zero > max_ptes_none) { result =SCAN_EXCEED_NONE_PTE ;@@ -1558,6 +1686,8 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm, } } +/* Set bit for occupied pages */ +__set_bit (i, cc->mthp_present_ptes);/* * Record which node the original page is from and save this * information to cc->node_load[]. @@ -1616,9 +1746,9 @@ static enum scan_result collapse_scan_pmd(struct mm_struct *mm,if (result ==SCAN_SUCCEED ) {/* collapse_huge_page expects the lock to be dropped before calling */ mmap_read_unlock (mm); - result =collapse_huge_page (mm, start_addr, referenced, - unmapped, cc,HPAGE_PMD_ORDER ); -/* collapse_huge_page will return with the mmap_lock released */ + result =mthp_collapse (mm, start_addr, referenced, + unmapped, cc, enabled_orders); +/* mmap_lock was released above, set lock_dropped */ *lock_dropped = true; }out:
Signature · 1 line
2.54.0
David Hildenbrand (Arm)
maintainerRe: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 159 lines · Lance Yang
Quoted 144 lines · Nico Pache
Enable khugepaged to collapse to mTHP orders. This patch implements the main scanning logic using a bitmap to track occupied pages and the algorithm to find optimal collapse sizes.
Previous to this patch, PMD collapse had 3 main phases, a light weight scanning phase (
mmap_read_lock) that determines a potential PMD collapse, an alloc phase (mmap unlocked), then finally heavier collapse phase (mmap_write_lock).To enabled mTHP collapse we make the following changes:
During PMD scan phase, track occupied pages in a bitmap. When mTHP orders are enabled, we remove the restriction of
max_ptes_noneduring the scan phase to avoid missing potential mTHP collapse candidates. Once we have scanned the full PMD range and updated the bitmap to track occupied pages, we use the bitmap to find the optimal mTHP size.Implement
mthp_collapse()to walk forward through the bitmap and determine the best eligible order for each naturally-aligned region. The algorithm starts at the beginning of the PMD range and, for each offset, tries the highest order that fits the alignment. If the number of occupied PTEs in that region satisfies themax_ptes_nonethreshold for that order, a collapse is attempted. On failure, the order is decremented and the same offset is retried at the next smaller size. Once the smallest enabled order is exhausted (or a collapse succeeds), the offset advances past the region just processed, and the next attempt starts at the highest order permitted by the new offset's natural alignment.The algorithm works as follows:
1) set offset=0 and order=HPAGE_PMD_ORDER
2) if the order is not enabled, go to step (5)
3) count occupied PTEs in the (offset, order) range usingbitmap_weight_from()
4) if the count satisfies themax_ptes_nonethreshold, attempt collapse; on success, advance to step (6)
5) if a smaller enabled order exists, decrement order and retry from step (2) at the same offset
6) advance offset past the current region and compute the next order from the new offset's natural alignment via__ffs(offset), capped atHPAGE_PMD_ORDER
7) repeat from step (2) until the full PMD range is coveredmTHP collapses reject regions containing swapped out or shared pages. This is because adding new entries can lead to new none pages, and these may lead to constant promotion into a higher order mTHP. A similar issue can occur with "
max_ptes_none> HPAGE_PMD_NR/2" due to a collapse introducing at least 2x the number of pages, and on a future scan will satisfy the promotion condition once again. This issue is prevented via thecollapse_max_ptes_none()function which imposes themax_ptes_nonerestrictions above.We currently only support mTHP collapse for
max_ptes_nonevalues of 0 andHPAGE_PMD_NR- 1. resulting in the following behavior:- max_ptes_none=0: Never introduce new empty pages during collapse
- max_ptes_none=HPAGE_PMD_NR-1: Always try collapse to the highest available mTHP orderAny other
max_ptes_nonevalue will emit a warning and default mTHP collapse to max_ptes_none=0. There should be no behavior change for PMD collapse.Once we determine what mTHP sizes fits best in that PMD range a collapse is attempted. A minimum collapse order of 2 is used as this is the lowest order supported by anon memory as defined by
THP_ORDERS_ALL_ANON.Currently
madv_collapseis not supported and will only attempt PMD collapse.We can also remove the check for
is_khugepagedinside the PMD scan as thecollapse_max_ptes_none()function handles this logic now.Signed-off-by Nico Pache <[email protected]>---
mm/khugepaged.c| 146 +++++++++++++++++++++++++++++++++++++++++++++---1 file changed, 138 insertions(+), 8 deletions(-)mm/khugepaged.c +44
-0@@ -99,6 +99,8 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);static struct kmem_cache *mm_slot_cache__ro_after_init ; +#define KHUGEPAGED_MIN_MTHP_ORDER 2 +struct collapse_control {bool is_khugepaged;@@ -110,6 +112,9 @@ struct collapse_control {/* nodemask for allocation fallback */ nodemask_t alloc_nmask; + +/* Each bit represents a single occupied (!none/zero) page. */ +DECLARE_BITMAP (mthp_present_ptes,MAX_PTRS_PER_PTE ); };/** @@ -1440,20 +1445,130 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long sreturn result; } +/* Return the highest naturally aligned order that fits at @offset within a PMD. */ +static unsigned int max_order_from_offset (unsigned int offset) +{ +if (offset ==0 ) +return HPAGE_PMD_ORDER ; + + return min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER); +} + +/* +* mthp_collapse() consumes the bitmap that is generated during +* collapse_scan_pmd() to determine what regions and mTHP orders fit best. +* +* Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero) +* page. We start at the PMD order and check if it is eligible for collapse; +* if not, we check the left and right halves of the PTE page table we are +* examining at a lower order. +* +* For each of these, we determine how many PTE entries are occupied in the +* range of PTE entries we propose to collapse, then we compare this to a +* threshold number of PTE entries which would need to be occupied for a +* collapse to be permitted at that order (accounting for max_ptes_none). +* +* If a collapse is permitted, we attempt to collapse the PTE range into a +* mTHP. +*/ +static enum scan_result mthp_collapse (struct mm_struct *mm, +unsigned long address,int referenced,int unmapped, +struct collapse_control *cc,unsigned long enabled_orders) +{ +unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none; +enum scan_result last_result =SCAN_FAIL ; +int collapsed =0 ; +bool alloc_failed = false; +unsigned long collapse_address; +unsigned int offset =0 ; +unsigned int order =HPAGE_PMD_ORDER ; + +while (offset <HPAGE_PMD_NR ) {mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1496
Quoted 10 lines
mm/khugepaged.c +10
-0+ nr_ptes =1UL << order; + +if (!test_bit (order, &enabled_orders)) + goto next_order; + + max_ptes_none =collapse_max_ptes_none (cc,NULL , order); + nr_occupied_ptes =bitmap_weight_from (cc->mthp_present_ptes, offset, + offset + nr_ptes); + +if (nr_occupied_ptes >= nr_ptes - max_ptes_none) {Looks broken for swap PTEs in PMD collapse ...
Quoted 3 lines
collapse_scan_pmd()allows them up tomax_ptes_swapand record them in unmapped, but they don't get a bit inmthp_present_ptes. And thenmthp_collapse()does the check above:
Right. I assumed this is implicitly handled by the optimization in collapse_scan_pmd:
if (enabled_orders != BIT(HPAGE_PMD_ORDER)) max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;
But we perform the check a second time.
Quoted 10 lines
nr_occupied_ptes>=nr_ptes-max_ptes_noneSo max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call
collapse_huge_page()for PMD order.Shouldn't we account for them in the PMD-order check? Something like:
if (
is_pmd_order(order))nr_occupied_ptes += unmapped;
As an alternative, we could either 1) skip the check there for pmd order (as the check was already done); or 2) introduce+maintain a bitmap that tracks non-present PTEs.
@@ -1475,7 +1477,9 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,
nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset,
offset + nr_ptes);- if (nr_occupied_ptes >= nr_ptes - max_ptes_none) {
+ /* Check was already done in the caller. */
+ if (is_pmd_order(order) ||
+ nr_occupied_ptes >= nr_ptes - max_ptes_none) {
enum scan_result ret;
collapse_address = address + offset * PAGE_SIZE;2) would probably be cleanest long-term.
Signature · 3 lines
Cheers, David
Lance Yang
reviewerRe: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 164 lines · David Hildenbrand (Arm)
Quoted 159 lines · Lance Yang
Quoted 144 lines · Nico Pache
Enable khugepaged to collapse to mTHP orders. This patch implements the main scanning logic using a bitmap to track occupied pages and the algorithm to find optimal collapse sizes.
Previous to this patch, PMD collapse had 3 main phases, a light weight scanning phase (
mmap_read_lock) that determines a potential PMD collapse, an alloc phase (mmap unlocked), then finally heavier collapse phase (mmap_write_lock).To enabled mTHP collapse we make the following changes:
During PMD scan phase, track occupied pages in a bitmap. When mTHP orders are enabled, we remove the restriction of
max_ptes_noneduring the scan phase to avoid missing potential mTHP collapse candidates. Once we have scanned the full PMD range and updated the bitmap to track occupied pages, we use the bitmap to find the optimal mTHP size.Implement
mthp_collapse()to walk forward through the bitmap and determine the best eligible order for each naturally-aligned region. The algorithm starts at the beginning of the PMD range and, for each offset, tries the highest order that fits the alignment. If the number of occupied PTEs in that region satisfies themax_ptes_nonethreshold for that order, a collapse is attempted. On failure, the order is decremented and the same offset is retried at the next smaller size. Once the smallest enabled order is exhausted (or a collapse succeeds), the offset advances past the region just processed, and the next attempt starts at the highest order permitted by the new offset's natural alignment.The algorithm works as follows:
1) set offset=0 and order=HPAGE_PMD_ORDER
2) if the order is not enabled, go to step (5)
3) count occupied PTEs in the (offset, order) range usingbitmap_weight_from()
4) if the count satisfies themax_ptes_nonethreshold, attempt collapse; on success, advance to step (6)
5) if a smaller enabled order exists, decrement order and retry from step (2) at the same offset
6) advance offset past the current region and compute the next order from the new offset's natural alignment via__ffs(offset), capped atHPAGE_PMD_ORDER
7) repeat from step (2) until the full PMD range is coveredmTHP collapses reject regions containing swapped out or shared pages. This is because adding new entries can lead to new none pages, and these may lead to constant promotion into a higher order mTHP. A similar issue can occur with "
max_ptes_none> HPAGE_PMD_NR/2" due to a collapse introducing at least 2x the number of pages, and on a future scan will satisfy the promotion condition once again. This issue is prevented via thecollapse_max_ptes_none()function which imposes themax_ptes_nonerestrictions above.We currently only support mTHP collapse for
max_ptes_nonevalues of 0 andHPAGE_PMD_NR- 1. resulting in the following behavior:- max_ptes_none=0: Never introduce new empty pages during collapse
- max_ptes_none=HPAGE_PMD_NR-1: Always try collapse to the highest available mTHP orderAny other
max_ptes_nonevalue will emit a warning and default mTHP collapse to max_ptes_none=0. There should be no behavior change for PMD collapse.Once we determine what mTHP sizes fits best in that PMD range a collapse is attempted. A minimum collapse order of 2 is used as this is the lowest order supported by anon memory as defined by
THP_ORDERS_ALL_ANON.Currently
madv_collapseis not supported and will only attempt PMD collapse.We can also remove the check for
is_khugepagedinside the PMD scan as thecollapse_max_ptes_none()function handles this logic now.Signed-off-by Nico Pache <[email protected]>---
mm/khugepaged.c| 146 +++++++++++++++++++++++++++++++++++++++++++++---1 file changed, 138 insertions(+), 8 deletions(-)mm/khugepaged.c +44
-0@@ -99,6 +99,8 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);static struct kmem_cache *mm_slot_cache__ro_after_init ; +#define KHUGEPAGED_MIN_MTHP_ORDER 2 +struct collapse_control {bool is_khugepaged;@@ -110,6 +112,9 @@ struct collapse_control {/* nodemask for allocation fallback */ nodemask_t alloc_nmask; + +/* Each bit represents a single occupied (!none/zero) page. */ +DECLARE_BITMAP (mthp_present_ptes,MAX_PTRS_PER_PTE ); };/** @@ -1440,20 +1445,130 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long sreturn result; } +/* Return the highest naturally aligned order that fits at @offset within a PMD. */ +static unsigned int max_order_from_offset (unsigned int offset) +{ +if (offset ==0 ) +return HPAGE_PMD_ORDER ; + + return min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER); +} + +/* +* mthp_collapse() consumes the bitmap that is generated during +* collapse_scan_pmd() to determine what regions and mTHP orders fit best. +* +* Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero) +* page. We start at the PMD order and check if it is eligible for collapse; +* if not, we check the left and right halves of the PTE page table we are +* examining at a lower order. +* +* For each of these, we determine how many PTE entries are occupied in the +* range of PTE entries we propose to collapse, then we compare this to a +* threshold number of PTE entries which would need to be occupied for a +* collapse to be permitted at that order (accounting for max_ptes_none). +* +* If a collapse is permitted, we attempt to collapse the PTE range into a +* mTHP. +*/ +static enum scan_result mthp_collapse (struct mm_struct *mm, +unsigned long address,int referenced,int unmapped, +struct collapse_control *cc,unsigned long enabled_orders) +{ +unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none; +enum scan_result last_result =SCAN_FAIL ; +int collapsed =0 ; +bool alloc_failed = false; +unsigned long collapse_address; +unsigned int offset =0 ; +unsigned int order =HPAGE_PMD_ORDER ; + +while (offset <HPAGE_PMD_NR ) {mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1496
Quoted 10 lines
mm/khugepaged.c +10
-0+ nr_ptes =1UL << order; + +if (!test_bit (order, &enabled_orders)) + goto next_order; + + max_ptes_none =collapse_max_ptes_none (cc,NULL , order); + nr_occupied_ptes =bitmap_weight_from (cc->mthp_present_ptes, offset, + offset + nr_ptes); + +if (nr_occupied_ptes >= nr_ptes - max_ptes_none) {Looks broken for swap PTEs in PMD collapse ...
Quoted 3 lines
collapse_scan_pmd()allows them up tomax_ptes_swapand record them in unmapped, but they don't get a bit inmthp_present_ptes. And thenmthp_collapse()does the check above:
Quoted 6 lines
Right. I assumed this is implicitly handled by the optimization in
collapse_scan_pmd:if (enabled_orders != BIT(HPAGE_PMD_ORDER)) max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;But we perform the check a second time.
Note that once lower orders are enabled, the scan *relaxes* max_ptes_none only so it can cover the whole PMD and build the bitmap ...
Quoted 6 lines
Quoted 6 lines
nr_occupied_ptes>=nr_ptes-max_ptes_noneSo max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call
collapse_huge_page()for PMD order.
Quoted 6 lines
Quoted 4 lines
Shouldn't we account for them in the PMD-order check? Something like:
if (
is_pmd_order(order))nr_occupied_ptes += unmapped;As an alternative, we could either 1) skip the check there for pmd order (as the check was already done); or 2) introduce+maintain
Yeah, skipping the check would do the trick, since isolate will check max_ptes_none again later :)
Review static enum scan_result mthp_collapse(struct mm_struct *mm, · line 1480
Quoted 8 lines
a bitmap that tracks non-present PTEs.
(quoted diff) +1
-1@@ -1475,7 +1477,9 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset, offset + nr_ptes); - if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { + /* Check was already done in the caller. */
This check is not quite redundant for PMD order, though. It avoids entering collapse_huge_page() for a range that already exceeds max_ptes_none for that order.
Quoted 7 lines
(quoted diff) +2
-0+ if (is_pmd_order(order) || + nr_occupied_ptes >= nr_ptes - max_ptes_none) { enum scan_result ret; collapse_address = address + offset * PAGE_SIZE;2) would probably be cleanest long-term.
Yeah, Agreed.
Lance Yang
reviewerRe: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 184 lines · Lance Yang
Quoted 164 lines · David Hildenbrand (Arm)
Quoted 159 lines · Lance Yang
Quoted 144 lines · Nico Pache
Enable khugepaged to collapse to mTHP orders. This patch implements the main scanning logic using a bitmap to track occupied pages and the algorithm to find optimal collapse sizes.
Previous to this patch, PMD collapse had 3 main phases, a light weight scanning phase (
mmap_read_lock) that determines a potential PMD collapse, an alloc phase (mmap unlocked), then finally heavier collapse phase (mmap_write_lock).To enabled mTHP collapse we make the following changes:
During PMD scan phase, track occupied pages in a bitmap. When mTHP orders are enabled, we remove the restriction of
max_ptes_noneduring the scan phase to avoid missing potential mTHP collapse candidates. Once we have scanned the full PMD range and updated the bitmap to track occupied pages, we use the bitmap to find the optimal mTHP size.Implement
mthp_collapse()to walk forward through the bitmap and determine the best eligible order for each naturally-aligned region. The algorithm starts at the beginning of the PMD range and, for each offset, tries the highest order that fits the alignment. If the number of occupied PTEs in that region satisfies themax_ptes_nonethreshold for that order, a collapse is attempted. On failure, the order is decremented and the same offset is retried at the next smaller size. Once the smallest enabled order is exhausted (or a collapse succeeds), the offset advances past the region just processed, and the next attempt starts at the highest order permitted by the new offset's natural alignment.The algorithm works as follows:
1) set offset=0 and order=HPAGE_PMD_ORDER
2) if the order is not enabled, go to step (5)
3) count occupied PTEs in the (offset, order) range usingbitmap_weight_from()
4) if the count satisfies themax_ptes_nonethreshold, attempt collapse; on success, advance to step (6)
5) if a smaller enabled order exists, decrement order and retry from step (2) at the same offset
6) advance offset past the current region and compute the next order from the new offset's natural alignment via__ffs(offset), capped atHPAGE_PMD_ORDER
7) repeat from step (2) until the full PMD range is coveredmTHP collapses reject regions containing swapped out or shared pages. This is because adding new entries can lead to new none pages, and these may lead to constant promotion into a higher order mTHP. A similar issue can occur with "
max_ptes_none> HPAGE_PMD_NR/2" due to a collapse introducing at least 2x the number of pages, and on a future scan will satisfy the promotion condition once again. This issue is prevented via thecollapse_max_ptes_none()function which imposes themax_ptes_nonerestrictions above.We currently only support mTHP collapse for
max_ptes_nonevalues of 0 andHPAGE_PMD_NR- 1. resulting in the following behavior:- max_ptes_none=0: Never introduce new empty pages during collapse
- max_ptes_none=HPAGE_PMD_NR-1: Always try collapse to the highest available mTHP orderAny other
max_ptes_nonevalue will emit a warning and default mTHP collapse to max_ptes_none=0. There should be no behavior change for PMD collapse.Once we determine what mTHP sizes fits best in that PMD range a collapse is attempted. A minimum collapse order of 2 is used as this is the lowest order supported by anon memory as defined by
THP_ORDERS_ALL_ANON.Currently
madv_collapseis not supported and will only attempt PMD collapse.We can also remove the check for
is_khugepagedinside the PMD scan as thecollapse_max_ptes_none()function handles this logic now.Signed-off-by Nico Pache <[email protected]>---
mm/khugepaged.c| 146 +++++++++++++++++++++++++++++++++++++++++++++---1 file changed, 138 insertions(+), 8 deletions(-)mm/khugepaged.c +44
-0@@ -99,6 +99,8 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);static struct kmem_cache *mm_slot_cache__ro_after_init ; +#define KHUGEPAGED_MIN_MTHP_ORDER 2 +struct collapse_control {bool is_khugepaged;@@ -110,6 +112,9 @@ struct collapse_control {/* nodemask for allocation fallback */ nodemask_t alloc_nmask; + +/* Each bit represents a single occupied (!none/zero) page. */ +DECLARE_BITMAP (mthp_present_ptes,MAX_PTRS_PER_PTE ); };/** @@ -1440,20 +1445,130 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long sreturn result; } +/* Return the highest naturally aligned order that fits at @offset within a PMD. */ +static unsigned int max_order_from_offset (unsigned int offset) +{ +if (offset ==0 ) +return HPAGE_PMD_ORDER ; + + return min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER); +} + +/* +* mthp_collapse() consumes the bitmap that is generated during +* collapse_scan_pmd() to determine what regions and mTHP orders fit best. +* +* Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero) +* page. We start at the PMD order and check if it is eligible for collapse; +* if not, we check the left and right halves of the PTE page table we are +* examining at a lower order. +* +* For each of these, we determine how many PTE entries are occupied in the +* range of PTE entries we propose to collapse, then we compare this to a +* threshold number of PTE entries which would need to be occupied for a +* collapse to be permitted at that order (accounting for max_ptes_none). +* +* If a collapse is permitted, we attempt to collapse the PTE range into a +* mTHP. +*/ +static enum scan_result mthp_collapse (struct mm_struct *mm, +unsigned long address,int referenced,int unmapped, +struct collapse_control *cc,unsigned long enabled_orders) +{ +unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none; +enum scan_result last_result =SCAN_FAIL ; +int collapsed =0 ; +bool alloc_failed = false; +unsigned long collapse_address; +unsigned int offset =0 ; +unsigned int order =HPAGE_PMD_ORDER ; + +while (offset <HPAGE_PMD_NR ) {mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1496
Quoted 10 lines
mm/khugepaged.c +10
-0+ nr_ptes =1UL << order; + +if (!test_bit (order, &enabled_orders)) + goto next_order; + + max_ptes_none =collapse_max_ptes_none (cc,NULL , order); + nr_occupied_ptes =bitmap_weight_from (cc->mthp_present_ptes, offset, + offset + nr_ptes); + +if (nr_occupied_ptes >= nr_ptes - max_ptes_none) {Looks broken for swap PTEs in PMD collapse ...
Quoted 3 lines
collapse_scan_pmd()allows them up tomax_ptes_swapand record them in unmapped, but they don't get a bit inmthp_present_ptes. And thenmthp_collapse()does the check above:Quoted 6 lines
Right. I assumed this is implicitly handled by the optimization in
collapse_scan_pmd:if (enabled_orders != BIT(HPAGE_PMD_ORDER)) max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;But we perform the check a second time.
Note that once lower orders are enabled, the scan *relaxes*
max_ptes_noneonly so it can cover the whole PMD and build the bitmap ...Quoted 8 lines
Quoted 8 lines
nr_occupied_ptes>=nr_ptes-max_ptes_noneSo max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call
collapse_huge_page()for PMD order.Shouldn't we account for them in the PMD-order check? Something like:
Quoted 7 lines
Quoted 4 lines
Quoted 2 lines
if (
is_pmd_order(order))nr_occupied_ptes += unmapped;As an alternative, we could either 1) skip the check there for pmd order (as the check was already done); or 2) introduce+maintain
Yeah, skipping the check would do the trick, since isolate will check
max_ptes_noneagain later :)
In addition, that later check is rather late, we may have already allocated the folio and swapped in pages before isolate rejects the range :)
Quoted 7 lines
Review static enum scan_result mthp_collapse(struct mm_struct *mm, · line 1478
Quoted 7 lines
a bitmap that tracks non-present PTEs.
(quoted diff) +0
-1@@ -1475,7 +1477,9 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset, offset + nr_ptes); - if (nr_occupied_ptes >= nr_ptes - max_ptes_none) {
So I'd still slightly prefer keeping this check and accounting unmapped for PMD order.
if (is_pmd_order(order))
nr_occupied_ptes += unmapped;
Quoted 15 lines
Review static enum scan_result mthp_collapse(struct mm_struct *mm, · line 1480
Quoted 1 line
(quoted diff) +1
-0+ /* Check was already done in the caller. */This check is not quite redundant for PMD order, though. It avoids entering
collapse_huge_page()for a range that already exceedsmax_ptes_nonefor that order.Quoted 7 lines
(quoted diff) +2
-0+ if (is_pmd_order(order) || + nr_occupied_ptes >= nr_ptes - max_ptes_none) { enum scan_result ret; collapse_address = address + offset * PAGE_SIZE;2) would probably be cleanest long-term.
Yeah, Agreed.
Re: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
In reply to David Hildenbrand (Arm)Quoted 165 lines · David Hildenbrand (Arm)
Quoted 159 lines · Lance Yang
Quoted 144 lines · Nico Pache
Enable khugepaged to collapse to mTHP orders. This patch implements the main scanning logic using a bitmap to track occupied pages and the algorithm to find optimal collapse sizes.
Previous to this patch, PMD collapse had 3 main phases, a light weight scanning phase (
mmap_read_lock) that determines a potential PMD collapse, an alloc phase (mmap unlocked), then finally heavier collapse phase (mmap_write_lock).To enabled mTHP collapse we make the following changes:
During PMD scan phase, track occupied pages in a bitmap. When mTHP orders are enabled, we remove the restriction of
max_ptes_noneduring the scan phase to avoid missing potential mTHP collapse candidates. Once we have scanned the full PMD range and updated the bitmap to track occupied pages, we use the bitmap to find the optimal mTHP size.Implement
mthp_collapse()to walk forward through the bitmap and determine the best eligible order for each naturally-aligned region. The algorithm starts at the beginning of the PMD range and, for each offset, tries the highest order that fits the alignment. If the number of occupied PTEs in that region satisfies themax_ptes_nonethreshold for that order, a collapse is attempted. On failure, the order is decremented and the same offset is retried at the next smaller size. Once the smallest enabled order is exhausted (or a collapse succeeds), the offset advances past the region just processed, and the next attempt starts at the highest order permitted by the new offset's natural alignment.The algorithm works as follows:
1) set offset=0 and order=HPAGE_PMD_ORDER
2) if the order is not enabled, go to step (5)
3) count occupied PTEs in the (offset, order) range usingbitmap_weight_from()
4) if the count satisfies themax_ptes_nonethreshold, attempt collapse; on success, advance to step (6)
5) if a smaller enabled order exists, decrement order and retry from step (2) at the same offset
6) advance offset past the current region and compute the next order from the new offset's natural alignment via__ffs(offset), capped atHPAGE_PMD_ORDER
7) repeat from step (2) until the full PMD range is coveredmTHP collapses reject regions containing swapped out or shared pages. This is because adding new entries can lead to new none pages, and these may lead to constant promotion into a higher order mTHP. A similar issue can occur with "
max_ptes_none> HPAGE_PMD_NR/2" due to a collapse introducing at least 2x the number of pages, and on a future scan will satisfy the promotion condition once again. This issue is prevented via thecollapse_max_ptes_none()function which imposes themax_ptes_nonerestrictions above.We currently only support mTHP collapse for
max_ptes_nonevalues of 0 andHPAGE_PMD_NR- 1. resulting in the following behavior:- max_ptes_none=0: Never introduce new empty pages during collapse
- max_ptes_none=HPAGE_PMD_NR-1: Always try collapse to the highest available mTHP orderAny other
max_ptes_nonevalue will emit a warning and default mTHP collapse to max_ptes_none=0. There should be no behavior change for PMD collapse.Once we determine what mTHP sizes fits best in that PMD range a collapse is attempted. A minimum collapse order of 2 is used as this is the lowest order supported by anon memory as defined by
THP_ORDERS_ALL_ANON.Currently
madv_collapseis not supported and will only attempt PMD collapse.We can also remove the check for
is_khugepagedinside the PMD scan as thecollapse_max_ptes_none()function handles this logic now.Signed-off-by Nico Pache <[email protected]>---
mm/khugepaged.c| 146 +++++++++++++++++++++++++++++++++++++++++++++---1 file changed, 138 insertions(+), 8 deletions(-)mm/khugepaged.c +44
-0@@ -99,6 +99,8 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_slots_hash, MM_SLOTS_HASH_BITS);static struct kmem_cache *mm_slot_cache__ro_after_init ; +#define KHUGEPAGED_MIN_MTHP_ORDER 2 +struct collapse_control {bool is_khugepaged;@@ -110,6 +112,9 @@ struct collapse_control {/* nodemask for allocation fallback */ nodemask_t alloc_nmask; + +/* Each bit represents a single occupied (!none/zero) page. */ +DECLARE_BITMAP (mthp_present_ptes,MAX_PTRS_PER_PTE ); };/** @@ -1440,20 +1445,130 @@ static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long sreturn result; } +/* Return the highest naturally aligned order that fits at @offset within a PMD. */ +static unsigned int max_order_from_offset (unsigned int offset) +{ +if (offset ==0 ) +return HPAGE_PMD_ORDER ; + + return min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER); +} + +/* +* mthp_collapse() consumes the bitmap that is generated during +* collapse_scan_pmd() to determine what regions and mTHP orders fit best. +* +* Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero) +* page. We start at the PMD order and check if it is eligible for collapse; +* if not, we check the left and right halves of the PTE page table we are +* examining at a lower order. +* +* For each of these, we determine how many PTE entries are occupied in the +* range of PTE entries we propose to collapse, then we compare this to a +* threshold number of PTE entries which would need to be occupied for a +* collapse to be permitted at that order (accounting for max_ptes_none). +* +* If a collapse is permitted, we attempt to collapse the PTE range into a +* mTHP. +*/ +static enum scan_result mthp_collapse (struct mm_struct *mm, +unsigned long address,int referenced,int unmapped, +struct collapse_control *cc,unsigned long enabled_orders) +{ +unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none; +enum scan_result last_result =SCAN_FAIL ; +int collapsed =0 ; +bool alloc_failed = false; +unsigned long collapse_address; +unsigned int offset =0 ; +unsigned int order =HPAGE_PMD_ORDER ; + +while (offset <HPAGE_PMD_NR ) {mm/khugepaged.c static enum scan_result collapse_huge_page(struct mm_struct *mm, unsigned long s · line 1496
Quoted 10 lines
mm/khugepaged.c +10
-0+ nr_ptes =1UL << order; + +if (!test_bit (order, &enabled_orders)) + goto next_order; + + max_ptes_none =collapse_max_ptes_none (cc,NULL , order); + nr_occupied_ptes =bitmap_weight_from (cc->mthp_present_ptes, offset, + offset + nr_ptes); + +if (nr_occupied_ptes >= nr_ptes - max_ptes_none) {Looks broken for swap PTEs in PMD collapse ...
Quoted 3 lines
collapse_scan_pmd()allows them up tomax_ptes_swapand record them in unmapped, but they don't get a bit inmthp_present_ptes. And thenmthp_collapse()does the check above:
Quoted 17 lines
Right. I assumed this is implicitly handled by the optimization in
collapse_scan_pmd:if (enabled_orders != BIT(HPAGE_PMD_ORDER)) max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;But we perform the check a second time.
Quoted 10 lines
nr_occupied_ptes>=nr_ptes-max_ptes_noneSo max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call
collapse_huge_page()for PMD order.Shouldn't we account for them in the PMD-order check? Something like:
if (
is_pmd_order(order))nr_occupied_ptes += unmapped;
This solution seems good for a temporary fixup. but longterm we may want something else. I'm still not sure how we plan on supporting swapin without causing creep. So I'd be ok with adding a fix for legacy PMD behavior until we know how to handle mTHP creep correctly.
Quoted 16 lines
As an alternative, we could either 1) skip the check there for pmd order (as the check was already done); or 2) introduce+maintain a bitmap that tracks non-present PTEs.
(quoted diff) +3
-1@@ -1475,7 +1477,9 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset, offset + nr_ptes); - if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { + /* Check was already done in the caller. */ + if (is_pmd_order(order) || + nr_occupied_ptes >= nr_ptes - max_ptes_none) { enum scan_result ret; collapse_address = address + offset * PAGE_SIZE;
Quoted 1 line
2) would probably be cleanest long-term.
That would be best for future swapin support in mTHP, but I still don't think it solves the creep issue. Perhaps we could combine the two bitmaps to determine if it would make the future collapse eligible again? Not sure but ill start thinking about it.
Should I send a fixup for this using Lance's solution? Or does Lance want to send a patch out with the fixes tag?
Quoted 6 lines
--
Cheers,David
David Hildenbrand (Arm)
maintainerRe: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 48 lines · Nico Pache
Quoted 10 lines · David Hildenbrand (Arm)
Quoted 7 lines · Lance Yang
Looks broken for swap PTEs in PMD collapse ...
collapse_scan_pmd()allows them up tomax_ptes_swapand record them in unmapped, but they don't get a bit inmthp_present_ptes. And thenmthp_collapse()does the check above:Quoted 17 lines
Right. I assumed this is implicitly handled by the optimization in
collapse_scan_pmd:if (enabled_orders != BIT(HPAGE_PMD_ORDER)) max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;But we perform the check a second time.
Quoted 10 lines
nr_occupied_ptes>=nr_ptes-max_ptes_noneSo max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call
collapse_huge_page()for PMD order.Shouldn't we account for them in the PMD-order check? Something like:
if (
is_pmd_order(order))nr_occupied_ptes += unmapped;This solution seems good for a temporary fixup. but longterm we may want something else. I'm still not sure how we plan on supporting swapin without causing creep. So I'd be ok with adding a fix for legacy PMD behavior until we know how to handle mTHP creep correctly.
Quoted 14 lines
As an alternative, we could either 1) skip the check there for pmd order (as the check was already done); or 2) introduce+maintain a bitmap that tracks non-present PTEs.
(quoted diff) +3
-1@@ -1475,7 +1477,9 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset, offset + nr_ptes); - if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { + /* Check was already done in the caller. */ + if (is_pmd_order(order) || + nr_occupied_ptes >= nr_ptes - max_ptes_none) { enum scan_result ret;
Quoted 6 lines
Quoted 3 lines
(quoted diff) +0
-0collapse_address = address + offset * PAGE_SIZE;2) would probably be cleanest long-term.
That would be best for future swapin support in mTHP, but I still don't think it solves the creep issue.
It wouldn't, we'd simply maintain the state we collect + rely on in separate bitmaps. On swapin, we'd have to update/refresh bitmaps I guess.
Quoted 6 lines
Perhaps we could combine the
two bitmaps to determine if it would make the future collapse eligible again? Not sure but ill start thinking about it.Should I send a fixup for this using Lance's solution? Or does Lance want to send a patch out with the fixes tag?
If Lance could send a fixup, explaining the situation, that would be nice.
Signature · 3 lines
Cheers, David
Re: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 52 lines · David Hildenbrand (Arm)
Quoted 50 lines · Nico Pache
Quoted 10 lines · David Hildenbrand (Arm)
Quoted 7 lines · Lance Yang
Looks broken for swap PTEs in PMD collapse ...
collapse_scan_pmd()allows them up tomax_ptes_swapand record them in unmapped, but they don't get a bit inmthp_present_ptes. And thenmthp_collapse()does the check above:Quoted 17 lines
Right. I assumed this is implicitly handled by the optimization in
collapse_scan_pmd:if (enabled_orders != BIT(HPAGE_PMD_ORDER)) max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;But we perform the check a second time.
Quoted 10 lines
nr_occupied_ptes>=nr_ptes-max_ptes_noneSo max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call
collapse_huge_page()for PMD order.Shouldn't we account for them in the PMD-order check? Something like:
if (
is_pmd_order(order))nr_occupied_ptes += unmapped;This solution seems good for a temporary fixup. but longterm we may want something else. I'm still not sure how we plan on supporting swapin without causing creep. So I'd be ok with adding a fix for legacy PMD behavior until we know how to handle mTHP creep correctly.
Quoted 16 lines
As an alternative, we could either 1) skip the check there for pmd order (as the check was already done); or 2) introduce+maintain a bitmap that tracks non-present PTEs.
(quoted diff) +3
-1@@ -1475,7 +1477,9 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset, offset + nr_ptes); - if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { + /* Check was already done in the caller. */ + if (is_pmd_order(order) || + nr_occupied_ptes >= nr_ptes - max_ptes_none) { enum scan_result ret; collapse_address = address + offset * PAGE_SIZE;
Quoted 7 lines
Quoted 4 lines
Quoted 1 line
2) would probably be cleanest long-term.
That would be best for future swapin support in mTHP, but I still don't think it solves the creep issue.
It wouldn't, we'd simply maintain the state we collect + rely on in separate bitmaps. On swapin, we'd have to update/refresh bitmaps I guess.
Yeah, I'm saying for the future, it obviously solves this issue here as well, but if we have positional tracking of the swapout, shared, and none PTEs, I think we can use this to determine whether the collapse would lead to creep. If we detect creep would happen it may be best to automatically collapse to the N+1 (or greater) candidate. Just thinking outloud here.
Quoted 9 lines
Quoted 7 lines
Perhaps we could combine the
two bitmaps to determine if it would make the future collapse eligible again? Not sure but ill start thinking about it.Should I send a fixup for this using Lance's solution? Or does Lance want to send a patch out with the fixes tag?
If Lance could send a fixup, explaining the situation, that would be nice.
OK, I'd appreciate that :)
Cheers,
-- Nico
Quoted 6 lines
--
Cheers,David
Lance Yang
reviewerRe: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 61 lines · Nico Pache
Quoted 52 lines · David Hildenbrand (Arm)
Quoted 50 lines · Nico Pache
Quoted 10 lines · David Hildenbrand (Arm)
Quoted 7 lines · Lance Yang
Looks broken for swap PTEs in PMD collapse ...
collapse_scan_pmd()allows them up tomax_ptes_swapand record them in unmapped, but they don't get a bit inmthp_present_ptes. And thenmthp_collapse()does the check above:Quoted 17 lines
Right. I assumed this is implicitly handled by the optimization in
collapse_scan_pmd:if (enabled_orders != BIT(HPAGE_PMD_ORDER)) max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;But we perform the check a second time.
Quoted 10 lines
nr_occupied_ptes>=nr_ptes-max_ptes_noneSo max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call
collapse_huge_page()for PMD order.Shouldn't we account for them in the PMD-order check? Something like:
if (
is_pmd_order(order))nr_occupied_ptes += unmapped;This solution seems good for a temporary fixup. but longterm we may want something else. I'm still not sure how we plan on supporting swapin without causing creep. So I'd be ok with adding a fix for legacy PMD behavior until we know how to handle mTHP creep correctly.
Quoted 16 lines
As an alternative, we could either 1) skip the check there for pmd order (as the check was already done); or 2) introduce+maintain a bitmap that tracks non-present PTEs.
(quoted diff) +3
-1@@ -1475,7 +1477,9 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset, offset + nr_ptes); - if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { + /* Check was already done in the caller. */ + if (is_pmd_order(order) || + nr_occupied_ptes >= nr_ptes - max_ptes_none) { enum scan_result ret; collapse_address = address + offset * PAGE_SIZE;Quoted 7 lines
Quoted 4 lines
Quoted 1 line
2) would probably be cleanest long-term.
That would be best for future swapin support in mTHP, but I still don't think it solves the creep issue.
It wouldn't, we'd simply maintain the state we collect + rely on in separate bitmaps. On swapin, we'd have to update/refresh bitmaps I guess.
Quoted 16 lines
Yeah, I'm saying for the future, it obviously solves this issue here as well, but if we have positional tracking of the swapout, shared, and none PTEs, I think we can use this to determine whether the collapse would lead to creep. If we detect creep would happen it may be best to automatically collapse to the N+1 (or greater) candidate. Just thinking outloud here.
Quoted 9 lines
Quoted 7 lines
Perhaps we could combine the
two bitmaps to determine if it would make the future collapse eligible again? Not sure but ill start thinking about it.Should I send a fixup for this using Lance's solution? Or does Lance want to send a patch out with the fixes tag?
If Lance could send a fixup, explaining the situation, that would be nice.
Sure, happy to send a fixup :P
Should I send it as a fixup to be folded into this patch, or as a separate patch with a Fixes: tag?
Will get one out soon :)
Quoted 1 line
OK, I'd appreciate that :)
Cheers!
Re: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 80 lines · Lance Yang
Quoted 76 lines · Nico Pache
Quoted 52 lines · David Hildenbrand (Arm)
Quoted 50 lines · Nico Pache
Quoted 10 lines · David Hildenbrand (Arm)
Quoted 7 lines · Lance Yang
Looks broken for swap PTEs in PMD collapse ...
collapse_scan_pmd()allows them up tomax_ptes_swapand record them in unmapped, but they don't get a bit inmthp_present_ptes. And thenmthp_collapse()does the check above:Quoted 17 lines
Right. I assumed this is implicitly handled by the optimization in
collapse_scan_pmd:if (enabled_orders != BIT(HPAGE_PMD_ORDER)) max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;But we perform the check a second time.
Quoted 10 lines
nr_occupied_ptes>=nr_ptes-max_ptes_noneSo max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call
collapse_huge_page()for PMD order.Shouldn't we account for them in the PMD-order check? Something like:
if (
is_pmd_order(order))nr_occupied_ptes += unmapped;This solution seems good for a temporary fixup. but longterm we may want something else. I'm still not sure how we plan on supporting swapin without causing creep. So I'd be ok with adding a fix for legacy PMD behavior until we know how to handle mTHP creep correctly.
Quoted 16 lines
As an alternative, we could either 1) skip the check there for pmd order (as the check was already done); or 2) introduce+maintain a bitmap that tracks non-present PTEs.
(quoted diff) +3
-1@@ -1475,7 +1477,9 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset, offset + nr_ptes); - if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { + /* Check was already done in the caller. */ + if (is_pmd_order(order) || + nr_occupied_ptes >= nr_ptes - max_ptes_none) { enum scan_result ret; collapse_address = address + offset * PAGE_SIZE;Quoted 7 lines
Quoted 4 lines
Quoted 1 line
2) would probably be cleanest long-term.
That would be best for future swapin support in mTHP, but I still don't think it solves the creep issue.
It wouldn't, we'd simply maintain the state we collect + rely on in separate bitmaps. On swapin, we'd have to update/refresh bitmaps I guess.
Yeah, I'm saying for the future, it obviously solves this issue here as well, but if we have positional tracking of the swapout, shared, and none PTEs, I think we can use this to determine whether the collapse would lead to creep. If we detect creep would happen it may be best to automatically collapse to the N+1 (or greater) candidate. Just thinking outloud here.
Quoted 8 lines
Quoted 7 lines
Perhaps we could combine the
two bitmaps to determine if it would make the future collapse eligible again? Not sure but ill start thinking about it.Should I send a fixup for this using Lance's solution? Or does Lance want to send a patch out with the fixes tag?
Quoted 6 lines
Quoted 1 line
Quoted 1 line
If Lance could send a fixup, explaining the situation, that would be nice.
Sure, happy to send a fixup :P
Should I send it as a fixup to be folded into this patch, or as a separate patch with a Fixes: tag?
Id assume a seperate patch so you can keep credit for the discovery :)
Thank you for all the review you provided on this series, its been really helpful!
-- Nico
Quoted 7 lines
Will get one out soon :)
Quoted 1 line
OK, I'd appreciate that :)
Cheers!
Lance Yang
reviewerRe: [PATCH mm-unstable v19 11/14] mm/khugepaged: Introduce mTHP collapse support
Quoted 81 lines · Nico Pache
Quoted 80 lines · Lance Yang
Quoted 76 lines · Nico Pache
Quoted 52 lines · David Hildenbrand (Arm)
Quoted 50 lines · Nico Pache
Quoted 10 lines · David Hildenbrand (Arm)
Quoted 7 lines · Lance Yang
Looks broken for swap PTEs in PMD collapse ...
collapse_scan_pmd()allows them up tomax_ptes_swapand record them in unmapped, but they don't get a bit inmthp_present_ptes. And thenmthp_collapse()does the check above:Quoted 17 lines
Right. I assumed this is implicitly handled by the optimization in
collapse_scan_pmd:if (enabled_orders != BIT(HPAGE_PMD_ORDER)) max_ptes_none = KHUGEPAGED_MAX_PTES_LIMIT;But we perform the check a second time.
Quoted 10 lines
nr_occupied_ptes>=nr_ptes-max_ptes_noneSo max_ptes_none=0 + 511 present PTEs + one allowed swap PTE won't even call
collapse_huge_page()for PMD order.Shouldn't we account for them in the PMD-order check? Something like:
if (
is_pmd_order(order))nr_occupied_ptes += unmapped;This solution seems good for a temporary fixup. but longterm we may want something else. I'm still not sure how we plan on supporting swapin without causing creep. So I'd be ok with adding a fix for legacy PMD behavior until we know how to handle mTHP creep correctly.
Quoted 16 lines
As an alternative, we could either 1) skip the check there for pmd order (as the check was already done); or 2) introduce+maintain a bitmap that tracks non-present PTEs.
(quoted diff) +3
-1@@ -1475,7 +1477,9 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, nr_occupied_ptes = bitmap_weight_from(cc->mthp_present_ptes, offset, offset + nr_ptes); - if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { + /* Check was already done in the caller. */ + if (is_pmd_order(order) || + nr_occupied_ptes >= nr_ptes - max_ptes_none) { enum scan_result ret; collapse_address = address + offset * PAGE_SIZE;Quoted 7 lines
Quoted 4 lines
Quoted 1 line
2) would probably be cleanest long-term.
That would be best for future swapin support in mTHP, but I still don't think it solves the creep issue.
It wouldn't, we'd simply maintain the state we collect + rely on in separate bitmaps. On swapin, we'd have to update/refresh bitmaps I guess.
Yeah, I'm saying for the future, it obviously solves this issue here as well, but if we have positional tracking of the swapout, shared, and none PTEs, I think we can use this to determine whether the collapse would lead to creep. If we detect creep would happen it may be best to automatically collapse to the N+1 (or greater) candidate. Just thinking outloud here.
Quoted 8 lines
Quoted 7 lines
Perhaps we could combine the
two bitmaps to determine if it would make the future collapse eligible again? Not sure but ill start thinking about it.Should I send a fixup for this using Lance's solution? Or does Lance want to send a patch out with the fixes tag?
Quoted 8 lines
Quoted 6 lines
Quoted 1 line
Quoted 1 line
If Lance could send a fixup, explaining the situation, that would be nice.
Sure, happy to send a fixup :P
Should I send it as a fixup to be folded into this patch, or as a separate patch with a Fixes: tag?
Id assume a seperate patch so you can keep credit for the discovery :)
Okay :D
Quoted 2 lines
Thank you for all the review you provided on this series, its been really helpful!
Appreciate it!
Nice work getting it this far. Nice one, Nico :P
PATCH v19 12/14 mm/khugepaged: avoid unnecessary mTHP collapse attempts
In reply to Nico PacheThere are cases where, if an attempted collapse fails, all subsequent orders are guaranteed to also fail. Avoid these collapse attempts by bailing out early.
--- mm/khugepaged.c | 13 +++++++++++++ 1 file changed, 13 insertions(+)
mm/khugepaged.c +13 -0
@@ -1499,6 +1499,7 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, collapse_address = address + offset *PAGE_SIZE ; ret =collapse_huge_page (mm, collapse_address, referenced, unmapped, cc, order); +switch (ret) {/* Cases where we continue to next collapse candidate */ case SCAN_SUCCEED :
@@ -1509,6 +1510,18 @@ static enum scan_result mthp_collapse(struct mm_struct *mm,/* Cases where lower orders might still succeed */ case SCAN_ALLOC_HUGE_PAGE_FAIL : alloc_failed = true; + fallthrough; +case SCAN_LACK_REFERENCED_PAGE : +case SCAN_EXCEED_NONE_PTE : +case SCAN_EXCEED_SWAP_PTE : +case SCAN_EXCEED_SHARED_PTE : +case SCAN_PAGE_LOCK : +case SCAN_PAGE_COUNT : +case SCAN_PAGE_NULL : +case SCAN_DEL_PAGE_LRU : +case SCAN_PTE_NON_PRESENT : +case SCAN_PTE_UFFD_WP : +case SCAN_PAGE_LAZYFREE : last_result = ret; goto next_order;/* Cases where no further collapse is possible */
Signature · 1 line
2.54.0
David Hildenbrand (Arm)
maintainerRe: [PATCH mm-unstable v19 12/14] mm/khugepaged: avoid unnecessary mTHP collapse attempts
Quoted 17 lines · Nico Pache
There are cases where, if an attempted collapse fails, all subsequent orders are guaranteed to also fail. Avoid these collapse attempts by bailing out early.
Reviewed-by Lorenzo Stoakes <[email protected]>Acked-by Usama Arif <[email protected]>Signed-off-by Nico Pache <[email protected]>--- mm/khugepaged.c | 13 +++++++++++++ 1 file changed, 13 insertions(+)mm/khugepaged.c +0
-0
mm/khugepaged.c static enum scan_result mthp_collapse(struct mm_struct *mm, · line 1502
Quoted 4 lines
mm/khugepaged.c +1
-0@@ -1499,6 +1499,7 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, collapse_address = address + offset *PAGE_SIZE ; ret =collapse_huge_page (mm, collapse_address, referenced, unmapped, cc, order); +
Unrelated to this patch, but not the end of the world :)
Signature · 3 lines
Cheers, David
Lorenzo Stoakes
reviewerRe: [PATCH mm-unstable v19 12/14] mm/khugepaged: avoid unnecessary mTHP collapse attempts
Quoted 13 lines · David Hildenbrand (Arm)
Quoted 12 lines · Nico Pache
There are cases where, if an attempted collapse fails, all subsequent orders are guaranteed to also fail. Avoid these collapse attempts by bailing out early.
Reviewed-by Lorenzo Stoakes <[email protected]>Acked-by Usama Arif <[email protected]>Signed-off-by Nico Pache <[email protected]>--- mm/khugepaged.c | 13 +++++++++++++ 1 file changed, 13 insertions(+)
Quoted 11 lines
mm/khugepaged.c static enum scan_result mthp_collapse(struct mm_struct *mm, · line 1502
Quoted 9 lines
mm/khugepaged.c +1
-0@@ -1499,6 +1499,7 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, collapse_address = address + offset *PAGE_SIZE ; ret =collapse_huge_page (mm, collapse_address, referenced, unmapped, cc, order); +Unrelated to this patch, but not the end of the world :)
NA....h that's fine ;)
Quoted 5 lines
--
Cheers,David
Cheers, Lorenzo
Re: [PATCH mm-unstable v19 12/14] mm/khugepaged: avoid unnecessary mTHP collapse attempts
In reply to Nico PacheQuoted 9 lines · Nico Pache
There are cases where, if an attempted collapse fails, all subsequent orders are guaranteed to also fail. Avoid these collapse attempts by bailing out early.
Reviewed-by Lorenzo Stoakes <[email protected]>Acked-by Usama Arif <[email protected]>Signed-off-by Nico Pache <[email protected]>---
PATCH v19 13/14 mm/khugepaged: run khugepaged for all orders
In reply to Nico PacheFrom: Baolin Wang <[email protected]>
If any order (m)THP is enabled we should allow running khugepaged to attempt scanning and collapsing mTHPs. In order for khugepaged to operate when only mTHP sizes are specified in sysfs, we must modify the predicate function that determines whether it ought to run to do so.
This function is currently called hugepage_pmd_enabled(), this patch renames it to hugepage_enabled() and updates the logic to check to determine whether any valid orders may exist which would justify khugepaged running.
We must also update collapse_possible_orders() to check all orders if the vma is anonymous and the collapse is khugepaged.
After this patch khugepaged mTHP collapse is fully enabled.
--- mm/khugepaged.c | 36 ++++++++++++++++++++---------------- 1 file changed, 20 insertions(+), 16 deletions(-)
mm/khugepaged.c +20 -16
@@ -503,23 +503,23 @@ static inline int collapse_test_exit_or_disable(struct mm_struct *mm)mm_flags_test (MMF_DISABLE_THP_COMPLETELY , mm); } -static bool hugepage_pmd_enabled (void ) +static bool hugepage_enabled (void ) {/* * We cover the anon, shmem and the file-backed case here; file-backed * hugepages, when configured in, are determined by the global control. -* Anon pmd-sized hugepages are determined by the pmd-size control. +* Anon hugepages are determined by its per-size mTHP control. * Shmem pmd-sized hugepages are also determined by its pmd-size control, * except when the global shmem_huge is set to SHMEM_HUGE_DENY. */ if (IS_ENABLED (CONFIG_READ_ONLY_THP_FOR_FS ) &&hugepage_global_enabled ())return true; -if (test_bit (PMD_ORDER , &huge_anon_orders_always)) +if (READ_ONCE (huge_anon_orders_always))return true; -if (test_bit (PMD_ORDER , &huge_anon_orders_madvise)) +if (READ_ONCE (huge_anon_orders_madvise))return true; -if (test_bit (PMD_ORDER , &huge_anon_orders_inherit) && +if (READ_ONCE (huge_anon_orders_inherit) &&hugepage_global_enabled ())return true;if (IS_ENABLED (CONFIG_SHMEM ) &&shmem_hpage_pmd_enabled ())
@@ -566,7 +566,13 @@ void __khugepaged_enter(struct mm_struct *mm)static unsigned long collapse_possible_orders (struct vm_area_struct *vma,vm_flags_t vm_flags,enum tva_type tva_flags) { -const unsigned long orders =BIT (HPAGE_PMD_ORDER ); +unsigned long orders; + +/* If khugepaged is scanning an anonymous vma, allow mTHP collapse */ +if ((tva_flags ==TVA_KHUGEPAGED ) &&vma_is_anonymous (vma)) + orders =THP_ORDERS_ALL_ANON ; +else + orders =BIT (HPAGE_PMD_ORDER );return thp_vma_allowable_orders (vma, vm_flags, tva_flags, orders); }
@@ -580,11 +586,9 @@ static bool collapse_possible(struct vm_area_struct *vma,void khugepaged_enter_vma (struct vm_area_struct *vma,vm_flags_t vm_flags) { -if (!mm_flags_test (MMF_VM_HUGEPAGE , vma->vm_mm) && -hugepage_pmd_enabled ()) { -if (collapse_possible (vma, vm_flags,TVA_KHUGEPAGED )) -__khugepaged_enter (vma->vm_mm); - } +if (!mm_flags_test (MMF_VM_HUGEPAGE , vma->vm_mm) &&hugepage_enabled () + &&collapse_possible (vma, vm_flags,TVA_KHUGEPAGED )) +__khugepaged_enter (vma->vm_mm); }void __khugepaged_exit (struct mm_struct *mm)
@@ -2936,7 +2940,7 @@ static void collapse_scan_mm_slot(unsigned int progress_max,static int khugepaged_has_work (void ) { -return !list_empty (&khugepaged_scan.mm_head) &&hugepage_pmd_enabled (); +return !list_empty (&khugepaged_scan.mm_head) &&hugepage_enabled (); }static int khugepaged_wait_event (void )
@@ -3009,7 +3013,7 @@ static void khugepaged_wait_work(void)return ; } -if (hugepage_pmd_enabled ()) +if (hugepage_enabled ())wait_event_freezable (khugepaged_wait,khugepaged_wait_event ()); }
@@ -3040,7 +3044,7 @@ void set_recommended_min_free_kbytes(void)int nr_zones =0 ;unsigned long recommended_min; -if (!hugepage_pmd_enabled ()) { +if (!hugepage_enabled ()) {calculate_min_free_kbytes (); goto update_wmarks; }
@@ -3090,7 +3094,7 @@ int start_stop_khugepaged(void)int err =0 ;mutex_lock (&khugepaged_mutex); -if (hugepage_pmd_enabled ()) { +if (hugepage_enabled ()) {if (!khugepaged_thread) khugepaged_thread =kthread_run (khugepaged,NULL ,"khugepaged" );
@@ -3116,7 +3120,7 @@ int start_stop_khugepaged(void)void khugepaged_min_free_kbytes_update (void ) {mutex_lock (&khugepaged_mutex); -if (hugepage_pmd_enabled () && khugepaged_thread) +if (hugepage_enabled () && khugepaged_thread)set_recommended_min_free_kbytes ();mutex_unlock (&khugepaged_mutex); }
Signature · 1 line
2.54.0
PATCH v19 14/14 Documentation: mm: update the admin guide for mTHP collapse
In reply to Nico PacheNow that we can collapse to mTHPs lets update the admin guide to reflect these changes and provide proper guidance on how to utilize it.
--- Documentation/admin-guide/mm/transhuge.rst | 49 ++++++++++++++-------- 1 file changed, 32 insertions(+), 17 deletions(-)
Documentation/admin-guide/mm/transhuge.rst +32 -17
@@ -63,7 +63,8 @@ often. THP can be enabled system wide or restricted to certain tasks or even memory ranges inside task's address space. Unless THP is completely disabled, there is ``khugepaged`` daemon that scans memory and -collapses sequences of basic pages into PMD-sized huge pages. +collapses sequences of basic pages into huge pages of either PMD size +or mTHP sizes, if the system is configured to do so. The THP behaviour is controlled via :ref:`sysfs <thp_sysfs>` interface and using madvise(2) and prctl(2) system calls.
@@ -219,10 +220,10 @@ this behaviour by writing 0 to shrink_underused, and enable it by writing echo 0 > /sys/kernel/mm/transparent_hugepage/shrink_underused echo 1 > /sys/kernel/mm/transparent_hugepage/shrink_underused -khugepaged will be automatically started when PMD-sized THP is enabled +khugepaged will be automatically started when any THP size is enabled (either of the per-size anon control or the top-level control are set to "always" or "madvise"), and it'll be automatically shutdown when -PMD-sized THP is disabled (when both the per-size anon control and the +all THP sizes are disabled (when both the per-size anon control and the top-level control are "never") process THP controls
@@ -265,8 +266,8 @@ Khugepaged controls ------------------- .. note:: - khugepaged currently only searches for opportunities to collapse to - PMD-sized THP and no attempt is made to collapse to other THP + khugepaged currently only searches for opportunities to collapse file/shmem + to PMD-sized THP. Only anonymous memory will attempt to collapse to other THP sizes. khugepaged runs usually at low frequency so while one may not want to
@@ -296,11 +297,11 @@ allocation failure to throttle the next allocation attempt:: The khugepaged progress can be seen in the number of pages collapsed (note that this counter may not be an exact count of the number of pages collapsed, since "collapsed" could mean multiple things: (1) A PTE mapping -being replaced by a PMD mapping, or (2) All 4K physical pages replaced by -one 2M hugepage. Each may happen independently, or together, depending on -the type of memory and the failures that occur. As such, this value should -be interpreted roughly as a sign of progress, and counters in /proc/vmstat -consulted for more accurate accounting):: +being replaced by a PMD mapping, or (2) physical pages replaced by one +hugepage of various sizes (PMD-sized or mTHP). Each may happen independently, +or together, depending on the type of memory and the failures that occur. +As such, this value should be interpreted roughly as a sign of progress, +and counters in /proc/vmstat consulted for more accurate accounting):: /sys/kernel/mm/transparent_hugepage/khugepaged/pages_collapsed
@@ -308,16 +309,21 @@ for each pass:: /sys/kernel/mm/transparent_hugepage/khugepaged/full_scans -``max_ptes_none`` specifies how many extra small pages (that are -not already mapped) can be allocated when collapsing a group -of small pages into one large page:: +``max_ptes_none`` specifies how many empty (none/zero) pages are allowed +when collapsing a group of small pages into one large page:: /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_none -A higher value leads to use additional memory for programs. -A lower value leads to gain less thp performance. Value of -max_ptes_none can waste cpu time very little, you can -ignore it. +For PMD-sized THP collapse, this directly limits the number of empty pages +allowed in the 2MB region. + +For mTHP collapse, only 0 or (HPAGE_PMD_NR - 1) are supported. At +HPAGE_PMD_NR - 1, we collapse to the highest possible order. Any intermediate +value will emit a warning and mTHP collapse will default to max_ptes_none=0. + +A higher value allows more empty pages, potentially leading to more memory +usage but better THP performance. A lower value is more conservative and +may result in fewer THP collapses. ``max_ptes_swap`` specifies how many pages can be brought in from swap when collapsing a group of pages into a transparent huge page::
@@ -337,6 +343,15 @@ that THP is shared. Exceeding the number would block the collapse:: A higher value may increase memory footprint for some workloads. +.. note:: + For mTHP collapse, khugepaged does not support collapsing regions that + contain shared or swapped out pages, as this could lead to continuous + promotion to higher orders. The collapse will fail if any shared or + swapped PTEs are encountered during the scan. + + Currently, madvise_collapse only supports collapsing to PMD-sized THPs + and does not attempt mTHP collapses. + Boot parameters ===============
Signature · 1 line
2.54.0
Re: [PATCH mm-unstable v19 14/14] Documentation: mm: update the admin guide for mTHP collapse
Quoted 7 lines · Nico Pache
Now that we can collapse to mTHPs lets update the admin guide to reflect these changes and provide proper guidance on how to utilize it.
Reviewed-by Lorenzo Stoakes <[email protected]>Reviewed-by Bagas Sanjaya <[email protected]>Signed-off-by Nico Pache <[email protected]>---
Signature · 3 lines
Cheers, David
Lorenzo Stoakes
reviewerRe: [PATCH mm-unstable v19 14/14] Documentation: mm: update the admin guide for mTHP collapse
In reply to Nico PacheQuoted 6 lines · Nico Pache
Now that we can collapse to mTHPs lets update the admin guide to reflect these changes and provide proper guidance on how to utilize it.
Reviewed-by Lorenzo Stoakes <[email protected]>Reviewed-by Bagas Sanjaya <[email protected]>Signed-off-by Nico Pache <[email protected]>
This is completely fine, and no blockers, but just a couple tiny things below Claude brought up for a possible trivial follow up.
Quoted 19 lines
--- Documentation/admin-guide/mm/transhuge.rst | 49 ++++++++++++++-------- 1 file changed, 32 insertions(+), 17 deletions(-)Documentation/admin-guide/mm/transhuge.rst +2
-1@@ -63,7 +63,8 @@ often. THP can be enabled system wide or restricted to certain tasks or even memory ranges inside task's address space. Unless THP is completely disabled, there is ``khugepaged`` daemon that scans memory and -collapses sequences of basic pages into PMD-sized huge pages. +collapses sequences of basic pages into huge pages of either PMD size +or mTHP sizes, if the system is configured to do so. The THP behaviour is controlled via :ref:`sysfs <thp_sysfs>` interface and using madvise(2) and prctl(2) system calls.
Documentation/admin-guide/mm/transhuge.rst this behaviour by writing 0 to shrink_underused, and enable it by writing · line 227
Quoted 10 lines
Documentation/admin-guide/mm/transhuge.rst +2
-2@@ -219,10 +220,10 @@ this behaviour by writing 0 to shrink_underused, and enable it by writing echo 0 > /sys/kernel/mm/transparent_hugepage/shrink_underused echo 1 > /sys/kernel/mm/transparent_hugepage/shrink_underused -khugepaged will be automatically started when PMD-sized THP is enabled +khugepaged will be automatically started when any THP size is enabled (either of the per-size anon control or the top-level control are set to "always" or "madvise"), and it'll be automatically shutdown when -PMD-sized THP is disabled (when both the per-size anon control and the +all THP sizes are disabled (when both the per-size anon control and the top-level control are "never")
Claude was very pedantic and said we need a full stop here :P
This is not a blocker, obviously...!
Quoted 17 lines
Documentation/admin-guide/mm/transhuge.rst +2
-2process THP controls@@ -265,8 +266,8 @@ Khugepaged controls ------------------- .. note:: - khugepaged currently only searches for opportunities to collapse to - PMD-sized THP and no attempt is made to collapse to other THP + khugepaged currently only searches for opportunities to collapse file/shmem + to PMD-sized THP. Only anonymous memory will attempt to collapse to other THP sizes. khugepaged runs usually at low frequency so while one may not want to@@ -296,11 +297,11 @@ allocation failure to throttle the next allocation attempt:: The khugepaged progress can be seen in the number of pages collapsed (note that this counter may not be an exact count of the number of pages collapsed, since "collapsed" could mean multiple things: (1) A PTE mapping
Documentation/admin-guide/mm/transhuge.rst allocation failure to throttle the next allocation attempt:: · line 304
Quoted 10 lines
Documentation/admin-guide/mm/transhuge.rst +5
-5-being replaced by a PMD mapping, or (2) All 4K physical pages replaced by -one 2M hugepage. Each may happen independently, or together, depending on -the type of memory and the failures that occur. As such, this value should -be interpreted roughly as a sign of progress, and counters in /proc/vmstat -consulted for more accurate accounting):: +being replaced by a PMD mapping, or (2) physical pages replaced by one +hugepage of various sizes (PMD-sized or mTHP). Each may happen independently, +or together, depending on the type of memory and the failures that occur. +As such, this value should be interpreted roughly as a sign of progress, +and counters in /proc/vmstat consulted for more accurate accounting)::
So Claude said maybe it's worth mentioning that the per-mTHP counters are only actually exposed through /sys/kernel/mm/transparent_hugepage/hugepages-<size>kB/stats/ and maybe worth mentioning here too?
Quoted 49 lines
Documentation/admin-guide/mm/transhuge.rst +21
-8/sys/kernel/mm/transparent_hugepage/khugepaged/pages_collapsed@@ -308,16 +309,21 @@ for each pass:: /sys/kernel/mm/transparent_hugepage/khugepaged/full_scans -``max_ptes_none`` specifies how many extra small pages (that are -not already mapped) can be allocated when collapsing a group -of small pages into one large page:: +``max_ptes_none`` specifies how many empty (none/zero) pages are allowed +when collapsing a group of small pages into one large page:: /sys/kernel/mm/transparent_hugepage/khugepaged/max_ptes_none -A higher value leads to use additional memory for programs. -A lower value leads to gain less thp performance. Value of -max_ptes_none can waste cpu time very little, you can -ignore it. +For PMD-sized THP collapse, this directly limits the number of empty pages +allowed in the 2MB region. + +For mTHP collapse, only 0 or (HPAGE_PMD_NR - 1) are supported. At +HPAGE_PMD_NR - 1, we collapse to the highest possible order. Any intermediate +value will emit a warning and mTHP collapse will default to max_ptes_none=0. + +A higher value allows more empty pages, potentially leading to more memory +usage but better THP performance. A lower value is more conservative and +may result in fewer THP collapses. ``max_ptes_swap`` specifies how many pages can be brought in from swap when collapsing a group of pages into a transparent huge page::@@ -337,6 +343,15 @@ that THP is shared. Exceeding the number would block the collapse:: A higher value may increase memory footprint for some workloads. +.. note:: + For mTHP collapse, khugepaged does not support collapsing regions that + contain shared or swapped out pages, as this could lead to continuous + promotion to higher orders. The collapse will fail if any shared or + swapped PTEs are encountered during the scan. + + Currently, madvise_collapse only supports collapsing to PMD-sized THPs + and does not attempt mTHP collapses. + Boot parameters =============== --
Quoted 2 lines
2.54.0
Cheers, Lorenzo
Re: [PATCH mm-unstable v19 14/14] Documentation: mm: update the admin guide for mTHP collapse
In reply to Nico PacheQuoted 7 lines · Nico Pache
Now that we can collapse to mTHPs lets update the admin guide to reflect these changes and provide proper guidance on how to utilize it.
Reviewed-by Lorenzo Stoakes <[email protected]>Reviewed-by Bagas Sanjaya <[email protected]>Signed-off-by Nico Pache <[email protected]>---
David Hildenbrand (Arm)
maintainerQuoted 24 lines · Nico Pache
The following series provides khugepaged with the capability to collapse anonymous memory regions to mTHPs.
To achieve this we generalize the khugepaged functions to no longer depend on
PMD_ORDER. Then during the PMD scan, we use a bitmap to track individual pages that are occupied (!none/zero). After the PMD scan is done, we use the bitmap to find the optimal mTHP sizes for the PMD range. The restriction onmax_ptes_noneis removed during the scan, to make sure we account for the whole PMD range in the bitmap. When no mTHP size is enabled, the legacy behavior of khugepaged is maintained.We currently only support
max_ptes_nonevalues of 0 orHPAGE_PMD_NR- 1 (ie 511). If any other value is specified, the kernel will emit a warning and mTHP collapse will default to max_ptes_none=0. If a mTHP collapse is attempted, but contains swapped out, or shared pages, we don't perform the collapse.
It is now also possible to collapse to mTHPs without requiring the PMD THP size to be enabled. These limitations are to prevent collapse "creep" behavior. This prevents constantly promoting mTHPs to the next available size, which would occur because a collapse introduces more non-zero pages that would satisfy the promotion condition on subsequent scans.Patch 1-2: Generalize
hugepage_vma_revalidateandalloc_charge_folio
for arbitrary orders.
Quoted 10 lines
Patch 3: Rework max_ptes_* handling into helper functions Patch 4: Generalize __collapse_huge_page_* for mTHP support Patch 5: Require collapse_huge_page to enter/exit with the lock dropped Patch 6: Generalize collapse_huge_page for mTHP collapse Patch 7: Skip collapsing mTHP to smaller orders Patch 8-9: Add per-order mTHP statistics and tracepoints Patch 10: Introduce collapse_possible_orders helper functions Patch 11-13: Introduce bitmap and mTHP collapse support, fully enabled Patch 14: Documentation
Went through it and didn't find any blockers. Let's wait for Lorenzo's assessment.
If he also doesn't find anything major, I think we can move forward with merging it and handle smaller things as follow-ups.
Signature · 3 lines
Cheers, David
Lorenzo Stoakes
reviewerQuoted 36 lines · David Hildenbrand (Arm)
Quoted 24 lines · Nico Pache
The following series provides khugepaged with the capability to collapse anonymous memory regions to mTHPs.
To achieve this we generalize the khugepaged functions to no longer depend on
PMD_ORDER. Then during the PMD scan, we use a bitmap to track individual pages that are occupied (!none/zero). After the PMD scan is done, we use the bitmap to find the optimal mTHP sizes for the PMD range. The restriction onmax_ptes_noneis removed during the scan, to make sure we account for the whole PMD range in the bitmap. When no mTHP size is enabled, the legacy behavior of khugepaged is maintained.We currently only support
max_ptes_nonevalues of 0 orHPAGE_PMD_NR- 1 (ie 511). If any other value is specified, the kernel will emit a warning and mTHP collapse will default to max_ptes_none=0. If a mTHP collapse is attempted, but contains swapped out, or shared pages, we don't perform the collapse.
It is now also possible to collapse to mTHPs without requiring the PMD THP size to be enabled. These limitations are to prevent collapse "creep" behavior. This prevents constantly promoting mTHPs to the next available size, which would occur because a collapse introduces more non-zero pages that would satisfy the promotion condition on subsequent scans.Patch 1-2: Generalize
hugepage_vma_revalidateandalloc_charge_folio
for arbitrary orders.Quoted 10 lines
Patch 3: Rework max_ptes_* handling into helper functions Patch 4: Generalize __collapse_huge_page_* for mTHP support Patch 5: Require collapse_huge_page to enter/exit with the lock dropped Patch 6: Generalize collapse_huge_page for mTHP collapse Patch 7: Skip collapsing mTHP to smaller orders Patch 8-9: Add per-order mTHP statistics and tracepoints Patch 10: Introduce collapse_possible_orders helper functions Patch 11-13: Introduce bitmap and mTHP collapse support, fully enabled Patch 14: Documentation
Quoted 4 lines
Went through it and didn't find any blockers. Let's wait for Lorenzo's assessment.
If he also doesn't find anything major, I think we can move forward with merging it and handle smaller things as follow-ups.
All LGTM :)
Unless sashiko tells us about something utterly broken (trivial things meh, existing things meh), or we see some massive breakage in testing, I think... *drum roll*
We're good to take this this cycle :)
Thanks Nico for your patience during this process and obviously David and Lance and all the other reviews for taking part.
We got there in the end :)
Quoted 5 lines
--
Cheers,David
Cheers, Lorenzo
Andrew Morton
maintainerQuoted 2 lines · On Fri, 5 Jun 2026 10:14:07 -0600 Nico Pache <[email protected]> wrote:
The following series provides khugepaged with the capability to collapse anonymous memory regions to mTHPs.
Thanks, I updated mm.git's mm-unstable branch to this version.
Sashiko said things:
https://sashiko.dev/#/patchset/[email protected]
Quoted 28 lines
V19 Changes:
- Rebased onto mm-unstable (base:9282f9bdbdf2, where v18 was based)
- Added RBs/Acks
- [patch 04] Makemax_ptes_noneconst; guardpr_warn_oncewith check so we only warn for non-zero intermediate values and use a single "return 0" path (David)
- [patch 06] Add comment explaining themmu_notifier_rangecovers only the modified PTE range (David); changeBUG_ONtoVM_WARN_ON_ONCE(David); fixupdate_mmu_cache_range()arch safety issue: reinstall PMD viapmd_populate()before callingmap_anon_folio_pte_nopf()and hold the PTE lock nested insidepmd_ptlduring the operation (David, Lance); drop the now-unnecessarysmp_wmb()as__folio_mark_uptodate()provides the required ordering (David, Lance)
- [patch 07] Clarify commit message: "mTHP to a folio of equal or smaller size, possibly resulting in a partially mapped source folio" (David)
- [patch 08] Add Lorenzo's RB and David's Ack; move TODO comment about shared pages to patch 4 (David)
- [patch 10] Renamecollapse_allowable_orders()tocollapse_possible_orders()and addcollapse_possible()boolean wrapper for callers that only need a yes/no answer (David)
- [patch 11] Major rework: replace the DFS stack-based algorithm with a simpler linear forward-walking approach using offset + order (David); removemthp_rangestruct, mthp_bitmap_stack[], stack push/pop functions, andMTHP_STACK_SIZE; addmax_order_from_offset()helper using__ffs(offset)for natural alignment; renamemthp_bitmaptomthp_present_ptes(David); remove temporarymthp_bitmap_maskand usebitmap_weight_from()directly (David); fix result propagation so
Quoted 8 lines
mthp_collapse()returns enumscan_resultand properly propagatesSCAN_ALLOC_HUGE_PAGE_FAILandSCAN_PTE_MAPPED_HUGEPAGEto callers (Lance); fold in v18 fixup for potential use-after-free of vma inmthp_collapse()by passing NULL tocollapse_max_ptes_none()
- [patch 12] Rework to match new linear algorithm; expand the set of failures that allow retrying at a lower order
- [patch 14] Re-add note about file/shmem still only collapsing to PMD-sized THPs (David)
Here's how v19 altered mm.git:
mm/khugepaged.c | 222 ++++++++++++++++++++-------------------------- 1 file changed, 100 insertions(+), 122 deletions(-)
mm/khugepaged.c renamed from mm/khugepaged.c~b +100 -122
@@ -100,28 +100,6 @@ static DEFINE_READ_MOSTLY_HASHTABLE(mm_sstatic struct kmem_cache *mm_slot_cache__ro_after_init ;#define KHUGEPAGED_MIN_MTHP_ORDER 2 -/* -* mthp_collapse() does an iterative DFS over a binary tree, from -* HPAGE_PMD_ORDER down to KHUGEPAGED_MIN_MTHP_ORDER. The max stack -* size needed for a DFS on a binary tree is height + 1, where -* height = HPAGE_PMD_ORDER - KHUGEPAGED_MIN_MTHP_ORDER. -* -* ilog2 is used in place of HPAGE_PMD_ORDER because some architectures -* (e.g. ppc64le) do not define HPAGE_PMD_ORDER until after build time. -*/ -#define MTHP_STACK_SIZE (ilog2(MAX_PTRS_PER_PTE) - KHUGEPAGED_MIN_MTHP_ORDER + 1) - -/* -* Defines a range of PTE entries in a PTE page table which are being -* considered for mTHP collapse. -* -* @offset: the offset of the first PTE entry in a PMD range. -* @order: the order of the PTE entries being considered for collapse. -*/ -struct mthp_range { -u16 offset; -u8 order; -};struct collapse_control {bool is_khugepaged;
@@ -136,10 +114,7 @@ struct collapse_control {nodemask_t alloc_nmask;/* Each bit represents a single occupied (!none/zero) page. */ -DECLARE_BITMAP (mthp_bitmap,MAX_PTRS_PER_PTE ); -/* A mask of the current range being considered for mTHP collapse. */ -DECLARE_BITMAP (mthp_bitmap_mask,MAX_PTRS_PER_PTE ); -struct mthp_range mthp_bitmap_stack[MTHP_STACK_SIZE ]; +DECLARE_BITMAP (mthp_present_ptes,MAX_PTRS_PER_PTE ); };/**
@@ -584,8 +559,11 @@ void __khugepaged_enter(struct mm_structwake_up_interruptible (&khugepaged_wait); } -/* Check what orders are allowed based on the vma and collapse type */ -static unsigned long collapse_allowable_orders (struct vm_area_struct *vma, +/* +* Check what orders are possible based on the vma and collapse type. +* This is used to determine if mTHP collapse is a viable option. +*/ +static unsigned long collapse_possible_orders (struct vm_area_struct *vma,vm_flags_t vm_flags,enum tva_type tva_flags) {unsigned long orders;
@@ -599,11 +577,17 @@ static unsigned long collapse_allowable_return thp_vma_allowable_orders (vma, vm_flags, tva_flags, orders); } +static bool collapse_possible (struct vm_area_struct *vma, +vm_flags_t vm_flags,enum tva_type tva_flags) +{ +return collapse_possible_orders (vma, vm_flags, tva_flags); +} +void khugepaged_enter_vma (struct vm_area_struct *vma,vm_flags_t vm_flags) {if (!mm_flags_test (MMF_VM_HUGEPAGE , vma->vm_mm) &&hugepage_enabled () - &&collapse_allowable_orders (vma, vm_flags,TVA_KHUGEPAGED )) + &&collapse_possible (vma, vm_flags,TVA_KHUGEPAGED ))__khugepaged_enter (vma->vm_mm); }
@@ -844,7 +828,7 @@ static void __collapse_huge_page_copy_su struct list_head *compound_pagelist) {const unsigned long nr_pages =1UL << order; -unsigned long end = address + (PAGE_SIZE << order); +unsigned long end = address + (PAGE_SIZE * nr_pages);struct folio *src, *tmp;pte_t pteval;pte_t *_pte;
@@ -1074,7 +1058,13 @@ static enum scan_result hugepage_vma_revif (!vma)return SCAN_VMA_NULL ; -/* Always check the PMD order to ensure its not shared by another VMA */ +/* +* We cannot collapse VMA regions that do not span the full PMD. This is +* due to the potential of the PMD being shared by another VMA leaving +* us vulnerable to a race condition. Always check the PMD order here to +* ensure its not shared by another VMA. We'd need to lock all VMAs in +* the PMD range to support this. +*/ if (!thp_vma_suitable_order (vma, address,PMD_ORDER ))return SCAN_ADDRESS_RANGE ;if (!thp_vma_allowable_orders (vma, vma->vm_flags, type,BIT (order)))
@@ -1390,7 +1380,7 @@ static enum scan_result collapse_huge_paif (unlikely (result !=SCAN_SUCCEED )) {spin_lock (pmd_ptl); -WARN_ON_ONCE (!pmd_none (*pmd)); +VM_WARN_ON_ONCE (!pmd_none (*pmd));/* * We can only use set_pmd_at when establishing * hugepmds and never for establishing regular pmds that
@@ -1433,13 +1423,18 @@ static enum scan_result collapse_huge_pamap_anon_folio_pmd_nopf (folio, pmd, vma, pmd_addr); }else {/* -* set_ptes is called in map_anon_folio_pte_nopf with the -* pmd_ptl lock still held; this is safe as the PMD is expected -* to be none. The pmd entry is then repopulated below. +* Some architectures (e.g. MIPS) walk the live page table in +* their implementation. update_mmu_cache_range() must be called +* with a valid page table hierarchy and the PTE lock held. +* Acquire it nested inside pmd_ptl when they are distinct locks. */ -map_anon_folio_pte_nopf (folio, pte, vma, start_addr,/*uffd_wp=*/ false); -smp_wmb ();/* make PTEs visible before PMD. See pmd_install() */ +if (pte_ptl != pmd_ptl) +spin_lock_nested (pte_ptl,SINGLE_DEPTH_NESTING );pmd_populate (mm, pmd,pmd_pgtable (_pmd)); +map_anon_folio_pte_nopf (folio, pte, vma, start_addr, +/*uffd_wp=*/ false); +if (pte_ptl != pmd_ptl) +spin_unlock (pte_ptl); }spin_unlock (pmd_ptl);
@@ -1459,58 +1454,23 @@ out_nolock:return result; } -static void collapse_mthp_stack_push (struct collapse_control *cc,int *stack_size, -u16 offset,u8 order) -{ -const int size = *stack_size; -struct mthp_range *stack = &cc->mthp_bitmap_stack[size]; - -VM_WARN_ON_ONCE (size >=MTHP_STACK_SIZE ); - stack->order = order; - stack->offset = offset; - (*stack_size)++; -} - -static struct mthp_range collapse_mthp_stack_pop (struct collapse_control *cc, -int *stack_size) +/* Return the highest naturally aligned order that fits at @offset within a PMD. */ +static unsigned int max_order_from_offset (unsigned int offset) { -const int size = *stack_size; +if (offset ==0 ) +return HPAGE_PMD_ORDER ; -VM_WARN_ON_ONCE (size <=0 ); - (*stack_size)--; -return cc->mthp_bitmap_stack[size -1 ]; -} - -static unsigned int collapse_mthp_count_present (struct collapse_control *cc, -u16 offset,unsigned int nr_ptes) -{ -bitmap_zero (cc->mthp_bitmap_mask,MAX_PTRS_PER_PTE ); -bitmap_set (cc->mthp_bitmap_mask, offset, nr_ptes); -return bitmap_weight_and (cc->mthp_bitmap, cc->mthp_bitmap_mask,MAX_PTRS_PER_PTE ); + return min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER); }/* * mthp_collapse() consumes the bitmap that is generated during * collapse_scan_pmd() to determine what regions and mTHP orders fit best. * -* Each bit in cc->mthp_bitmap represents a single occupied (!none/zero) page. -* A stack structure cc->mthp_bitmap_stack is used to check different regions -* of the bitmap for collapse eligibility. The stack maintains a pair of -* variables (offset, order), indicating the number of PTEs from the start of -* the PMD, and the order of the potential collapse candidate respectively. We -* start at the PMD order and check if it is eligible for collapse; if not, we -* add two entries to the stack at a lower order to represent the left and right -* halves of the PTE page table we are examining. -* -* offset mid_offset -* | | -* | | -* v v -* -------------------------------------- -* | cc->mthp_bitmap | -* -------------------------------------- -* <-------><-------> -* order-1 order-1 +* Each bit in cc->mthp_present_ptes represents a single occupied (!none/zero) +* page. We start at the PMD order and check if it is eligible for collapse; +* if not, we check the left and right halves of the PTE page table we are +* examining at a lower order. * * For each of these, we determine how many PTE entries are occupied in the * range of PTE entries we propose to collapse, then we compare this to a
@@ -1520,35 +1480,30 @@ static unsigned int collapse_mthp_count_* If a collapse is permitted, we attempt to collapse the PTE range into a * mTHP. */ -static int mthp_collapse (struct mm_struct *mm,unsigned long address, -int referenced,int unmapped,struct collapse_control *cc, -unsigned long enabled_orders) +static enum scan_result mthp_collapse (struct mm_struct *mm, +unsigned long address,int referenced,int unmapped, +struct collapse_control *cc,unsigned long enabled_orders) {unsigned int nr_occupied_ptes, nr_ptes, max_ptes_none; -int collapsed =0 , stack_size =0 ; +enum scan_result last_result =SCAN_FAIL ; +int collapsed =0 ; +bool alloc_failed = false;unsigned long collapse_address; -struct mthp_range range; -u16 offset; -u8 order; - -collapse_mthp_stack_push (cc, &stack_size,0 ,HPAGE_PMD_ORDER ); - -while (stack_size) { - range =collapse_mthp_stack_pop (cc, &stack_size); - order = range.order; - offset = range.offset; +unsigned int offset =0 ; +unsigned int order =HPAGE_PMD_ORDER ; + +while (offset <HPAGE_PMD_NR ) { nr_ptes =1UL << order;if (!test_bit (order, &enabled_orders)) goto next_order; max_ptes_none =collapse_max_ptes_none (cc,NULL , order); - - nr_occupied_ptes =collapse_mthp_count_present (cc, offset, - nr_ptes); + nr_occupied_ptes =bitmap_weight_from (cc->mthp_present_ptes, offset, + offset + nr_ptes);if (nr_occupied_ptes >= nr_ptes - max_ptes_none) { -int ret; +enum scan_result ret; collapse_address = address + offset *PAGE_SIZE ; ret = collapse_huge_page(mm, collapse_address, referenced,
@@ -1560,8 +1515,11 @@ static int mthp_collapse(struct mm_struc collapsed += nr_ptes; fallthrough;case SCAN_PTE_MAPPED_HUGEPAGE : -continue ; + goto next_offset;/* Cases where lower orders might still succeed */ +case SCAN_ALLOC_HUGE_PAGE_FAIL : + alloc_failed = true; + fallthrough;case SCAN_LACK_REFERENCED_PAGE :case SCAN_EXCEED_NONE_PTE :case SCAN_EXCEED_SWAP_PTE :
@@ -1572,27 +1530,48 @@ static int mthp_collapse(struct mm_struccase SCAN_DEL_PAGE_LRU :case SCAN_PTE_NON_PRESENT :case SCAN_PTE_UFFD_WP : -case SCAN_ALLOC_HUGE_PAGE_FAIL :case SCAN_PAGE_LAZYFREE : + last_result = ret; goto next_order;/* Cases where no further collapse is possible */ +case SCAN_PMD_MAPPED : + fallthrough;default : -return collapsed; + last_result = ret; + goto done; } } next_order: -if ((BIT (order) -1 ) & enabled_orders) { -const u8 next_order = order -1 ; -const u16 mid_offset = offset + (nr_ptes /2 ); - -collapse_mthp_stack_push (cc, &stack_size, mid_offset, - next_order); -collapse_mthp_stack_push (cc, &stack_size, offset, - next_order); - } - } -return collapsed; +/* +* Continue with the next smaller order if there is still +* any smaller order enabled. When at the smallest order +* we must always move to the next offset. +*/ +if (order >KHUGEPAGED_MIN_MTHP_ORDER && + (enabled_orders &GENMASK (order -1 ,0 ))) { + order--; +continue ; + } +next_offset: +/* +* Advance past the region we just processed and determine the +* highest order we can attempt next. Since huge pages must be +* naturally aligned, the max order we can attempt next is +* limited by the alignment of the new offset. +* E.g. if we collapsed a order-2 mTHP at offset 0, offset +* becomes 4 and __ffs(4) == 2, so the next attempt starts at +* order 2. +*/ + offset += nr_ptes; + order =max_order_from_offset (offset); + } +done: +if (collapsed) +return SCAN_SUCCEED ; +if (alloc_failed) +return SCAN_ALLOC_HUGE_PAGE_FAIL ; +return last_result; } static enum scan_result collapse_scan_pmd(struct mm_struct *mm,
@@ -1606,7 +1585,7 @@ static enum scan_result collapse_scan_pmpmd_t *pmd;pte_t *pte, *_pte, pteval;int i; -int none_or_zero =0 , shared =0 , nr_collapsed =0 , referenced =0 ; +int none_or_zero =0 , shared =0 , referenced =0 ;enum scan_result result =SCAN_FAIL ;struct page *page =NULL ;struct folio *folio =NULL ;
@@ -1623,11 +1602,11 @@ static enum scan_result collapse_scan_pm goto out; } -bitmap_zero (cc->mthp_bitmap,MAX_PTRS_PER_PTE ); +bitmap_zero (cc->mthp_present_ptes,MAX_PTRS_PER_PTE );memset (cc->node_load,0 ,sizeof (cc->node_load));nodes_clear (cc->alloc_nmask); - enabled_orders =collapse_allowable_orders (vma, vma->vm_flags, tva_flags); + enabled_orders =collapse_possible_orders (vma, vma->vm_flags, tva_flags);/* * If PMD is the only enabled order, enforce max_ptes_none, otherwise
@@ -1730,7 +1709,7 @@ static enum scan_result collapse_scan_pm }/* Set bit for occupied pages */ -__set_bit (i, cc->mthp_bitmap); +__set_bit (i, cc->mthp_present_ptes);/* * Record which node the original page is from and save this * information to cc->node_load[].
@@ -1789,11 +1768,10 @@ out_unmap:if (result ==SCAN_SUCCEED ) {/* collapse_huge_page expects the lock to be dropped before calling */ mmap_read_unlock (mm); - nr_collapsed =mthp_collapse (mm, start_addr, referenced, - unmapped, cc, enabled_orders); + result =mthp_collapse (mm, start_addr, referenced, + unmapped, cc, enabled_orders);/* mmap_lock was released above, set lock_dropped */ *lock_dropped = true; - result = nr_collapsed ?SCAN_SUCCEED :SCAN_FAIL ; } out: trace_mm_khugepaged_scan_pmd(mm, folio, referenced,
@@ -2892,7 +2870,7 @@ static void collapse_scan_mm_slot(unsign cc->progress++;break ; } -if (!collapse_allowable_orders (vma, vma->vm_flags,TVA_KHUGEPAGED )) { +if (!collapse_possible (vma, vma->vm_flags,TVA_KHUGEPAGED )) { cc->progress++;continue ; }
@@ -3202,7 +3180,7 @@ int madvise_collapse(struct vm_area_struBUG_ON (vma->vm_start > start);BUG_ON (vma->vm_end < end); -if (!collapse_allowable_orders (vma, vma->vm_flags,TVA_FORCED_COLLAPSE )) +if (!collapse_possible (vma, vma->vm_flags,TVA_FORCED_COLLAPSE ))return -EINVAL ; cc =kmalloc_obj (*cc);
_