Linux-mm Archive on lore.kernel.org
 help / color / mirror / Atom feed
* [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
@ 2026-12-02 10:28 Alexandre Ghiti
  2026-12-02 11:22 ` Lorenzo Stoakes (ARM)
                   ` (4 more replies)
  0 siblings, 5 replies; 16+ messages in thread
From: Alexandre Ghiti @ 2026-12-02 10:28 UTC (permalink / raw)
  To: Andrew Morton, David Hildenbrand, Zi Yan
  Cc: Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain,
	Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Shakeel Butt, Pedro Falcato, Jann Horn,
	linux-mm, linux-kernel, Alexandre Ghiti

MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
the PMD and zaps the PTEs of the range. The THP itself is not freed: it
stays allocated and charged as a whole, now partially mapped, until the
deferred split shrinker splits it under memory pressure. Until then the
process has lost the PMD mapping, and the TLB reach that comes with it, for
no memory benefit.

Besides, a THP is checked for being underused only once: it is queued on
the deferred split list when it is created, and the shrinker drops it from
the list for good once it has found it not underused. A long-lived THP
whose pages are freed later is never looked at again, so its unused memory
can't be reclaimed.

When the underused THP shrinker can reclaim the range later, zero it in
place instead: it reads as zeroes, as MADV_DONTNEED requires, and the PMD
mapping stays. The THP is queued again on the deferred split list, so the
shrinker looks at it again.

For an exclusive anonymous THP, MADV_DONTNEED on part of it thus no longer
leaves it partially mapped: the range reads as zeroes at once, and the
memory is given back when reclaim needs it, once the THP holds more than
max_ptes_none zeroed pages. Below that, the THP is not split even under
memory pressure, where the partially mapped THP used to be split: it keeps
up to max_ptes_none zeroed pages, the waste khugepaged already allows when
collapsing.

The range is zapped as before when the zeroed pages could not be freed,
e.g. with max_ptes_none at 511 (the default), or when anyone else may see
the THP, e.g. after fork or through a GUP pin.

Results on a large production workload (THP=always, max_ptes_none=0,
allocator purging with MADV_DONTNEED), same allocator configuration before
and after this patch:

  THPs and memory                       change
  ------------------------------------  ------
  THPs partially mapped                   -97%
  memory mapped by THPs (AnonHugePages)   +29%
  underused THP splits                   +145%
  PMD splits                              +10%
  workload anonymous memory              +0.2%

  Performance                           change
  ------------------------------------  ------
  p50 latency                            -1.7%
  p99 latency                            -2.3%
  throughput                      within noise
  dTLB misses per instruction            -0.4%
  IPC                                    +0.2%

Signed-off-by: Alexandre Ghiti <alex@ghiti.fr>
---
Open questions:

- MADV_DONTNEED now zeroes the range synchronously, up to a whole PMD
  minus one page (2M on x86, 512M with 64K base pages on arm64). Should
  zeroing be capped, falling back to the split above some size?

- A pin taken while the range is being zeroed goes unnoticed, as neither
  GUP-fast nor GUP takes the folio lock: a device write through it (e.g. an
  O_DIRECT read into the range from another thread) can land after
  MADV_DONTNEED returns. Only a process doing I/O into memory it is
  discarding can see it; pins that exist when the THP is checked fall back
  to the zap. Closing the window would take a PMD invalidation and a TLB
  flush per call, which this patch avoids, or GUP backing off on a folio
  being zeroed. Is the race acceptable?

- RSS (and so oom_badness()), /proc/pid/pagemap and mincore() keep showing
  the range as resident until the THP is split, where the zap made it
  disappear at once. memcg usage is unchanged: the THP stayed charged until
  its split before too.

- The cow (THP_RUN_SINGLE_PTE), khugepaged and transhuge-stress selftests
  use a partial MADV_DONTNEED to split a PMD, which MADV_DONTNEED never
  guaranteed. khugepaged sets max_ptes_none to 511 first, but cow and
  transhuge-stress keep the host's value: with a lower max_ptes_none they
  still pass, while silently testing a PMD-mapped THP. They should pin
  max_ptes_none or split the PMD explicitly (MADV_NOHUGEPAGE, mprotect() or
  debugfs).

PTE-mapped large folios (mTHP) are left for later.

 include/linux/huge_mm.h |  2 ++
 include/linux/mm.h      |  2 ++
 mm/huge_memory.c        | 69 +++++++++++++++++++++++++++++++++++++++++
 mm/internal.h           |  3 ++
 mm/madvise.c            |  2 +-
 mm/memory.c             | 14 ++++++---
 6 files changed, 87 insertions(+), 5 deletions(-)

diff --git a/include/linux/huge_mm.h b/include/linux/huge_mm.h
index 087920c38163..4ca675435856 100644
--- a/include/linux/huge_mm.h
+++ b/include/linux/huge_mm.h
@@ -28,6 +28,8 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
 			   pmd_t *pmd, unsigned long addr, unsigned long next);
 bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, pmd_t *pmd,
 		  unsigned long addr);
+bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
+			 unsigned long addr, unsigned long end);
 int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud,
 		 unsigned long addr);
 bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
diff --git a/include/linux/mm.h b/include/linux/mm.h
index 00abd4d250a9..d28ba827f1d5 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -3413,6 +3413,8 @@ struct zap_details {
 #define  ZAP_FLAG_DROP_MARKER        ((__force zap_flags_t) BIT(0))
 /* Set in unmap_vmas() to indicate a final unmap call.  Only used by hugetlb */
 #define  ZAP_FLAG_UNMAP              ((__force zap_flags_t) BIT(1))
+/* MADV_DONTNEED: zero part of a PMD-mapped THP in place instead of splitting */
+#define  ZAP_FLAG_ZERO_PARTIAL_THP   ((__force zap_flags_t) BIT(2))
 
 #ifdef CONFIG_MMU
 extern bool can_do_mlock(void);
diff --git a/mm/huge_memory.c b/mm/huge_memory.c
index 4fc888ddfb69..121da9397194 100644
--- a/mm/huge_memory.c
+++ b/mm/huge_memory.c
@@ -2623,6 +2623,75 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
 	return true;
 }
 
+/*
+ * MADV_DONTNEED on [addr, end), part of a PMD-mapped THP: zero it in place
+ * instead of splitting the PMD, and queue the THP for the deferred split
+ * shrinker, which frees the zeroed pages once the THP is underused. Return
+ * false if the caller must split the PMD and zap the range instead.
+ */
+bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
+			 unsigned long addr, unsigned long end)
+{
+	unsigned long haddr = addr & HPAGE_PMD_MASK;
+	struct folio *folio;
+	spinlock_t *ptl;
+	pmd_t orig_pmd;
+	bool ret;
+
+	/* With max_ptes_none at 511, no THP is ever underused. */
+	if (!READ_ONCE(split_underused_thp) ||
+	    khugepaged_max_ptes_none == HPAGE_PMD_NR - 1)
+		return false;
+
+	if ((vma->vm_flags & VM_MTE) || userfaultfd_armed(vma) ||
+	    mm_forbids_zeropage(vma->vm_mm))
+		return false;
+
+	ptl = pmd_trans_huge_lock(pmd, vma);
+	if (!ptl)
+		return false;
+	orig_pmd = pmdp_get(pmd);
+	if (is_huge_zero_pmd(orig_pmd)) {
+		spin_unlock(ptl);
+		return true;
+	}
+
+	folio = pmd_present(orig_pmd) ?
+		vm_normal_folio_pmd(vma, haddr, orig_pmd) : NULL;
+	if (!folio || !folio_test_anon(folio) ||
+	    !PageAnonExclusive(&folio->page) || folio_test_mlocked(folio) ||
+	    folio_contain_hwpoisoned_page(folio) ||
+	    folio_ref_count(folio) != folio_expected_ref_count(folio) ||
+	    !folio_trylock(folio)) {
+		spin_unlock(ptl);
+		return false;
+	}
+	folio_get(folio);
+	spin_unlock(ptl);
+
+	flush_cache_range(vma, addr, end);
+	clear_contig_highpages(folio_page(folio, (addr - haddr) >> PAGE_SHIFT),
+			       addr, (end - addr) >> PAGE_SHIFT);
+
+	/*
+	 * Mark the PMD dirty, and soft-dirty, as a write through it would. If
+	 * the PMD was split meanwhile, let the caller zap the range instead.
+	 */
+	ptl = pmd_lock(vma->vm_mm, pmd);
+	orig_pmd = pmdp_get(pmd);
+	ret = pmd_present(orig_pmd) && pmd_trans_huge(orig_pmd) &&
+	      pmd_folio(orig_pmd) == folio;
+	if (ret) {
+		touch_pmd(vma, haddr, pmd, true);
+		deferred_split_folio(folio, false);
+	}
+	spin_unlock(ptl);
+
+	folio_unlock(folio);
+	folio_put(folio);
+	return ret;
+}
+
 #ifndef pmd_move_must_withdraw
 static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
 					 spinlock_t *old_pmd_ptl,
diff --git a/mm/internal.h b/mm/internal.h
index 8942e57744a9..afa301cf8eaf 100644
--- a/mm/internal.h
+++ b/mm/internal.h
@@ -281,6 +281,9 @@ static inline int mmap_file(struct file *file, struct vm_area_struct *vma)
 
 /* unmap_vmas is in mm/memory.c */
 void unmap_vmas(struct mmu_gather *tlb, struct unmap_desc *unmap);
+/* clear_contig_highpages is in mm/memory.c */
+void clear_contig_highpages(struct page *page, unsigned long addr,
+			    unsigned int nr_pages);
 
 #ifdef CONFIG_MMU
 
diff --git a/mm/madvise.c b/mm/madvise.c
index 66600e82605c..35114546008e 100644
--- a/mm/madvise.c
+++ b/mm/madvise.c
@@ -888,7 +888,7 @@ static void zap_range(struct madvise_behavior *madv_behavior,
 static long madvise_dontneed_single_vma(struct madvise_behavior *madv_behavior)
 
 {
-	zap_range(madv_behavior, 0);
+	zap_range(madv_behavior, ZAP_FLAG_ZERO_PARTIAL_THP);
 	return 0;
 }
 
diff --git a/mm/memory.c b/mm/memory.c
index 82e1ec8e44e7..36a43b7ece84 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -2112,9 +2112,15 @@ static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
 	do {
 		next = pmd_addr_end(addr, end);
 		if (pmd_is_huge(*pmd)) {
-			if (next - addr != HPAGE_PMD_SIZE)
+			if (next - addr != HPAGE_PMD_SIZE) {
+				if (details &&
+				    (details->zap_flags & ZAP_FLAG_ZERO_PARTIAL_THP) &&
+				    zero_huge_pmd_range(vma, pmd, addr, next)) {
+					addr = next;
+					continue;
+				}
 				__split_huge_pmd(vma, pmd, addr, false);
-			else if (zap_huge_pmd(tlb, vma, pmd, addr)) {
+			} else if (zap_huge_pmd(tlb, vma, pmd, addr)) {
 				addr = next;
 				continue;
 			}
@@ -7674,8 +7680,8 @@ static inline int process_huge_page(
 	return 0;
 }
 
-static void clear_contig_highpages(struct page *page, unsigned long addr,
-				   unsigned int nr_pages)
+void clear_contig_highpages(struct page *page, unsigned long addr,
+			    unsigned int nr_pages)
 {
 	unsigned int i, count;
 	/*

base-commit: 0bbbdf85abf48b019cb8dd7a6e87f0a8995fdcd2
-- 
2.53.1-Meta



^ permalink raw reply related	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 10:28 [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED Alexandre Ghiti
@ 2026-12-02 11:22 ` Lorenzo Stoakes (ARM)
  2026-12-03 14:10   ` Alexandre Ghiti
  2026-12-02 11:22 ` David Hildenbrand (Arm)
                   ` (3 subsequent siblings)
  4 siblings, 1 reply; 16+ messages in thread
From: Lorenzo Stoakes (ARM) @ 2026-12-02 11:22 UTC (permalink / raw)
  To: Alexandre Ghiti
  Cc: Andrew Morton, David Hildenbrand, Zi Yan, Baolin Wang,
	Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain, Barry Song,
	Lance Yang, Usama Arif, Kiryl Shutsemau, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Suren Baghdasaryan, Shakeel Butt,
	Pedro Falcato, Jann Horn, linux-mm, linux-kernel

On Wed, Dec 02, 2026 at 11:28:10AM +0100, Alexandre Ghiti wrote:
> MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> stays allocated and charged as a whole, now partially mapped, until the
> deferred split shrinker splits it under memory pressure. Until then the
> process has lost the PMD mapping, and the TLB reach that comes with it, for
> no memory benefit.
>
> Besides, a THP is checked for being underused only once: it is queued on
> the deferred split list when it is created, and the shrinker drops it from
> the list for good once it has found it not underused. A long-lived THP
> whose pages are freed later is never looked at again, so its unused memory
> can't be reclaimed.
>
> When the underused THP shrinker can reclaim the range later, zero it in
> place instead: it reads as zeroes, as MADV_DONTNEED requires, and the PMD
> mapping stays. The THP is queued again on the deferred split list, so the
> shrinker looks at it again.
>
> For an exclusive anonymous THP, MADV_DONTNEED on part of it thus no longer
> leaves it partially mapped: the range reads as zeroes at once, and the
> memory is given back when reclaim needs it, once the THP holds more than
> max_ptes_none zeroed pages. Below that, the THP is not split even under
> memory pressure, where the partially mapped THP used to be split: it keeps
> up to max_ptes_none zeroed pages, the waste khugepaged already allows when
> collapsing.
>
> The range is zapped as before when the zeroed pages could not be freed,
> e.g. with max_ptes_none at 511 (the default), or when anyone else may see
> the THP, e.g. after fork or through a GUP pin.
>
> Results on a large production workload (THP=always, max_ptes_none=0,
> allocator purging with MADV_DONTNEED), same allocator configuration before
> and after this patch:

This whole thing reads like AI, too dense, too may words, not to the point,
not for humans.

It needs human rewriting to be succinct and sane.

>
>   THPs and memory                       change
>   ------------------------------------  ------
>   THPs partially mapped                   -97%
>   memory mapped by THPs (AnonHugePages)   +29%
>   underused THP splits                   +145%
>   PMD splits                              +10%
>   workload anonymous memory              +0.2%
>
>   Performance                           change
>   ------------------------------------  ------
>   p50 latency                            -1.7%
>   p99 latency                            -2.3%
>   throughput                      within noise
>   dTLB misses per instruction            -0.4%
>   IPC                                    +0.2%
>
> Signed-off-by: Alexandre Ghiti <alex@ghiti.fr>

OK I see this is an RFC, I will leave it to the THP maintainers for an
architectural review, but the code needs rewriting for it to be
in any way upstreamable.

> ---
> Open questions:
>
> - MADV_DONTNEED now zeroes the range synchronously, up to a whole PMD
>   minus one page (2M on x86, 512M with 64K base pages on arm64). Should
>   zeroing be capped, falling back to the split above some size?
>
> - A pin taken while the range is being zeroed goes unnoticed, as neither
>   GUP-fast nor GUP takes the folio lock: a device write through it (e.g. an
>   O_DIRECT read into the range from another thread) can land after
>   MADV_DONTNEED returns. Only a process doing I/O into memory it is
>   discarding can see it; pins that exist when the THP is checked fall back
>   to the zap. Closing the window would take a PMD invalidation and a TLB
>   flush per call, which this patch avoids, or GUP backing off on a folio
>   being zeroed. Is the race acceptable?
>
> - RSS (and so oom_badness()), /proc/pid/pagemap and mincore() keep showing
>   the range as resident until the THP is split, where the zap made it
>   disappear at once. memcg usage is unchanged: the THP stayed charged until
>   its split before too.
>
> - The cow (THP_RUN_SINGLE_PTE), khugepaged and transhuge-stress selftests
>   use a partial MADV_DONTNEED to split a PMD, which MADV_DONTNEED never
>   guaranteed. khugepaged sets max_ptes_none to 511 first, but cow and
>   transhuge-stress keep the host's value: with a lower max_ptes_none they
>   still pass, while silently testing a PMD-mapped THP. They should pin
>   max_ptes_none or split the PMD explicitly (MADV_NOHUGEPAGE, mprotect() or
>   debugfs).

This reads LLM-generated and packs a ton into each paragraph. Can you write
this for humans please?

>
> PTE-mapped large folios (mTHP) are left for later.

Is that the plan going forward? Weird to have a million words on open
questions above then nothing on this :)

>
>  include/linux/huge_mm.h |  2 ++
>  include/linux/mm.h      |  2 ++
>  mm/huge_memory.c        | 69 +++++++++++++++++++++++++++++++++++++++++
>  mm/internal.h           |  3 ++
>  mm/madvise.c            |  2 +-
>  mm/memory.c             | 14 ++++++---
>  6 files changed, 87 insertions(+), 5 deletions(-)
>
> diff --git a/include/linux/huge_mm.h b/include/linux/huge_mm.h
> index 087920c38163..4ca675435856 100644
> --- a/include/linux/huge_mm.h
> +++ b/include/linux/huge_mm.h
> @@ -28,6 +28,8 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
>  			   pmd_t *pmd, unsigned long addr, unsigned long next);
>  bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, pmd_t *pmd,
>  		  unsigned long addr);
> +bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
> +			 unsigned long addr, unsigned long end);
>  int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud,
>  		 unsigned long addr);
>  bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
> diff --git a/include/linux/mm.h b/include/linux/mm.h
> index 00abd4d250a9..d28ba827f1d5 100644
> --- a/include/linux/mm.h
> +++ b/include/linux/mm.h
> @@ -3413,6 +3413,8 @@ struct zap_details {
>  #define  ZAP_FLAG_DROP_MARKER        ((__force zap_flags_t) BIT(0))
>  /* Set in unmap_vmas() to indicate a final unmap call.  Only used by hugetlb */
>  #define  ZAP_FLAG_UNMAP              ((__force zap_flags_t) BIT(1))
> +/* MADV_DONTNEED: zero part of a PMD-mapped THP in place instead of splitting */
> +#define  ZAP_FLAG_ZERO_PARTIAL_THP   ((__force zap_flags_t) BIT(2))

Do we really have to expand this horrible interface any further?

>
>  #ifdef CONFIG_MMU
>  extern bool can_do_mlock(void);
> diff --git a/mm/huge_memory.c b/mm/huge_memory.c
> index 4fc888ddfb69..121da9397194 100644
> --- a/mm/huge_memory.c
> +++ b/mm/huge_memory.c
> @@ -2623,6 +2623,75 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
>  	return true;
>  }
>
> +/*
> + * MADV_DONTNEED on [addr, end), part of a PMD-mapped THP: zero it in place
> + * instead of splitting the PMD, and queue the THP for the deferred split
> + * shrinker, which frees the zeroed pages once the THP is underused. Return
> + * false if the caller must split the PMD and zap the range instead.
> + */

This comment is horribly schloppy. The functino name has nothing to do with
it, and this is now a function you're exposing to a header called 'zero
huge PMD range' but the comment talks about a use case?

Horrible sorry.

> +bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
> +			 unsigned long addr, unsigned long end)
> +{
> +	unsigned long haddr = addr & HPAGE_PMD_MASK;
> +	struct folio *folio;
> +	spinlock_t *ptl;
> +	pmd_t orig_pmd;
> +	bool ret;
> +
> +	/* With max_ptes_none at 511, no THP is ever underused. */
> +	if (!READ_ONCE(split_underused_thp) ||
> +	    khugepaged_max_ptes_none == HPAGE_PMD_NR - 1)
> +		return false;

This feels like it should be abstracted.

> +
> +	if ((vma->vm_flags & VM_MTE) || userfaultfd_armed(vma) ||

Why are you using the legacy VMA flag interface in new code? And why
explicitly reference an x86 feature?...

These are all signals that you didn't abstract things correctly.

> +	    mm_forbids_zeropage(vma->vm_mm))
> +		return false;

No (SHORT) comment to explain why these are excluded?

> +
> +	ptl = pmd_trans_huge_lock(pmd, vma);
> +	if (!ptl)
> +		return false;
> +	orig_pmd = pmdp_get(pmd);
> +	if (is_huge_zero_pmd(orig_pmd)) {
> +		spin_unlock(ptl);
> +		return true;
> +	}
> +
> +	folio = pmd_present(orig_pmd) ?
> +		vm_normal_folio_pmd(vma, haddr, orig_pmd) : NULL;

Err what? You just use vm_normal_folio_pmd() no?

> +	if (!folio || !folio_test_anon(folio) ||
> +	    !PageAnonExclusive(&folio->page) || folio_test_mlocked(folio) ||
> +	    folio_contain_hwpoisoned_page(folio) ||
> +	    folio_ref_count(folio) != folio_expected_ref_count(folio) ||
> +	    !folio_trylock(folio)) {

This is DISGUSTING :) I'm sorry. 7 conditions all in one continued line of
varying types.

You need to abstract the code in such a way as to avoid something like
this, it's totally un-upstreamable and isn't what kernel code looks like.

THP code is horrible enough let's not make it worse.

> +		spin_unlock(ptl);
> +		return false;
> +	}
> +	folio_get(folio);
> +	spin_unlock(ptl);
> +
> +	flush_cache_range(vma, addr, end);
> +	clear_contig_highpages(folio_page(folio, (addr - haddr) >> PAGE_SHIFT),
> +			       addr, (end - addr) >> PAGE_SHIFT);

Why is this function now exposed? Also _horribly_ open-coded shifted
values.

> +
> +	/*
> +	 * Mark the PMD dirty, and soft-dirty, as a write through it would. If
> +	 * the PMD was split meanwhile, let the caller zap the range instead.
> +	 */

Where are you marking it dirty? Also please don't mention soft-dirty it's a
distraction and no need to point a niche thing out (begs question as to why
you didn't mention anything else niche).

I find the comment actually quite confusing here in general. Needs to be cleareer.

> +	ptl = pmd_lock(vma->vm_mm, pmd);
> +	orig_pmd = pmdp_get(pmd);
> +	ret = pmd_present(orig_pmd) && pmd_trans_huge(orig_pmd) &&
> +	      pmd_folio(orig_pmd) == folio;
> +	if (ret) {
> +		touch_pmd(vma, haddr, pmd, true);
> +		deferred_split_folio(folio, false);
> +	}

Again this code is just utterly horrible. Also you already checked for
pmd_present(orig_pmd) above...

THP code is horrible enough without just piling on more horrors.

> +	spin_unlock(ptl);
> +
> +	folio_unlock(folio);
> +	folio_put(folio);
> +	return ret;
> +}
> +
>  #ifndef pmd_move_must_withdraw
>  static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
>  					 spinlock_t *old_pmd_ptl,
> diff --git a/mm/internal.h b/mm/internal.h
> index 8942e57744a9..afa301cf8eaf 100644
> --- a/mm/internal.h
> +++ b/mm/internal.h
> @@ -281,6 +281,9 @@ static inline int mmap_file(struct file *file, struct vm_area_struct *vma)
>
>  /* unmap_vmas is in mm/memory.c */
>  void unmap_vmas(struct mmu_gather *tlb, struct unmap_desc *unmap);
> +/* clear_contig_highpages is in mm/memory.c */
> +void clear_contig_highpages(struct page *page, unsigned long addr,
> +			    unsigned int nr_pages);
>
>  #ifdef CONFIG_MMU
>
> diff --git a/mm/madvise.c b/mm/madvise.c
> index 66600e82605c..35114546008e 100644
> --- a/mm/madvise.c
> +++ b/mm/madvise.c
> @@ -888,7 +888,7 @@ static void zap_range(struct madvise_behavior *madv_behavior,
>  static long madvise_dontneed_single_vma(struct madvise_behavior *madv_behavior)
>
>  {
> -	zap_range(madv_behavior, 0);
> +	zap_range(madv_behavior, ZAP_FLAG_ZERO_PARTIAL_THP);

No explanation? So somebody reading this 'just has to know'?

>  	return 0;
>  }
>
> diff --git a/mm/memory.c b/mm/memory.c
> index 82e1ec8e44e7..36a43b7ece84 100644
> --- a/mm/memory.c
> +++ b/mm/memory.c
> @@ -2112,9 +2112,15 @@ static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
>  	do {
>  		next = pmd_addr_end(addr, end);
>  		if (pmd_is_huge(*pmd)) {
> -			if (next - addr != HPAGE_PMD_SIZE)
> +			if (next - addr != HPAGE_PMD_SIZE) {
> +				if (details &&
> +				    (details->zap_flags & ZAP_FLAG_ZERO_PARTIAL_THP) &&
> +				    zero_huge_pmd_range(vma, pmd, addr, next)) {
> +					addr = next;
> +					continue;
> +				}

This is also UTTERLY disgusting lord above. And no comment, obviously...!

Don't indent like this, don't put so many conditions on one line, _refactor
code_ to accommodate your change sensibly, don't just add technical debt
into open-coded bits.


>  				__split_huge_pmd(vma, pmd, addr, false);
> -			else if (zap_huge_pmd(tlb, vma, pmd, addr)) {
> +			} else if (zap_huge_pmd(tlb, vma, pmd, addr)) {
>  				addr = next;
>  				continue;
>  			}
> @@ -7674,8 +7680,8 @@ static inline int process_huge_page(
>  	return 0;
>  }
>
> -static void clear_contig_highpages(struct page *page, unsigned long addr,
> -				   unsigned int nr_pages)
> +void clear_contig_highpages(struct page *page, unsigned long addr,
> +			    unsigned int nr_pages)

Why are you exposing this?

>  {
>  	unsigned int i, count;
>  	/*
>
> base-commit: 0bbbdf85abf48b019cb8dd7a6e87f0a8995fdcd2
> --
> 2.53.1-Meta
>

--
Cheers, Lorenzo


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 10:28 [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED Alexandre Ghiti
  2026-12-02 11:22 ` Lorenzo Stoakes (ARM)
@ 2026-12-02 11:22 ` David Hildenbrand (Arm)
  2026-12-02 14:26   ` Alexandre Ghiti
  2026-12-02 16:37 ` Zi Yan
                   ` (2 subsequent siblings)
  4 siblings, 1 reply; 16+ messages in thread
From: David Hildenbrand (Arm) @ 2026-12-02 11:22 UTC (permalink / raw)
  To: Alexandre Ghiti, Andrew Morton, Zi Yan
  Cc: Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain,
	Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Shakeel Butt, Pedro Falcato, Jann Horn,
	linux-mm, linux-kernel

On 12/2/26 11:28, Alexandre Ghiti wrote:

Hi,

> MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> stays allocated and charged as a whole, now partially mapped, until the
> deferred split shrinker splits it under memory pressure. Until then the
> process has lost the PMD mapping, and the TLB reach that comes with it, for
> no memory benefit.

Right. User space should avoid doing stupid things.

> 
> Besides, a THP is checked for being underused only once: it is queued on
> the deferred split list when it is created, and the shrinker drops it from
> the list for good once it has found it not underused. A long-lived THP
> whose pages are freed later is never looked at again, so its unused memory
> can't be reclaimed.

The job of the underused shrinking is to detect over-allocation. Not "user space
used it and then partially freed it".

> 
> When the underused THP shrinker can reclaim the range later, zero it in
> place instead: it reads as zeroes, as MADV_DONTNEED requires, and the PMD
> mapping stays. The THP is queued again on the deferred split list, so the
> shrinker looks at it again.
> 
> For an exclusive anonymous THP, MADV_DONTNEED on part of it thus no longer
> leaves it partially mapped: the range reads as zeroes at once, and the
> memory is given back when reclaim needs it, once the THP holds more than
> max_ptes_none zeroed pages. Below that, the THP is not split even under
> memory pressure, where the partially mapped THP used to be split: it keeps
> up to max_ptes_none zeroed pages, the waste khugepaged already allows when
> collapsing.
> 
> The range is zapped as before when the zeroed pages could not be freed,
> e.g. with max_ptes_none at 511 (the default), or when anyone else may see
> the THP, e.g. after fork or through a GUP pin.
> 
> Results on a large production workload (THP=always, max_ptes_none=0,
> allocator purging with MADV_DONTNEED), same allocator configuration before
> and after this patch:
> 
>   THPs and memory                       change
>   ------------------------------------  ------
>   THPs partially mapped                   -97%
>   memory mapped by THPs (AnonHugePages)   +29%
>   underused THP splits                   +145%
>   PMD splits                              +10%
>   workload anonymous memory              +0.2%
> 
>   Performance                           change
>   ------------------------------------  ------
>   p50 latency                            -1.7%
>   p99 latency                            -2.3%
>   throughput                      within noise
>   dTLB misses per instruction            -0.4%
>   IPC                                    +0.2%
> 
> Signed-off-by: Alexandre Ghiti <alex@ghiti.fr>
> ---
> Open questions:
> 
> - MADV_DONTNEED now zeroes the range synchronously, up to a whole PMD
>   minus one page (2M on x86, 512M with 64K base pages on arm64). Should
>   zeroing be capped, falling back to the split above some size?
> 
> - A pin taken while the range is being zeroed goes unnoticed, as neither
>   GUP-fast nor GUP takes the folio lock: a device write through it (e.g. an
>   O_DIRECT read into the range from another thread) can land after
>   MADV_DONTNEED returns. Only a process doing I/O into memory it is
>   discarding can see it; pins that exist when the THP is checked fall back
>   to the zap. Closing the window would take a PMD invalidation and a TLB
>   flush per call, which this patch avoids, or GUP backing off on a folio
>   being zeroed. Is the race acceptable?
> 
> - RSS (and so oom_badness()), /proc/pid/pagemap and mincore() keep showing
>   the range as resident until the THP is split, where the zap made it
>   disappear at once. memcg usage is unchanged: the THP stayed charged until
>   its split before too.
> 
> - The cow (THP_RUN_SINGLE_PTE), khugepaged and transhuge-stress selftests
>   use a partial MADV_DONTNEED to split a PMD, which MADV_DONTNEED never
>   guaranteed. khugepaged sets max_ptes_none to 511 first, but cow and
>   transhuge-stress keep the host's value: with a lower max_ptes_none they
>   still pass, while silently testing a PMD-mapped THP. They should pin
>   max_ptes_none or split the PMD explicitly (MADV_NOHUGEPAGE, mprotect() or
>   debugfs).
> 
> PTE-mapped large folios (mTHP) are left for later.
> 
>  include/linux/huge_mm.h |  2 ++
>  include/linux/mm.h      |  2 ++
>  mm/huge_memory.c        | 69 +++++++++++++++++++++++++++++++++++++++++
>  mm/internal.h           |  3 ++
>  mm/madvise.c            |  2 +-
>  mm/memory.c             | 14 ++++++---
>  6 files changed, 87 insertions(+), 5 deletions(-)
> 
> diff --git a/include/linux/huge_mm.h b/include/linux/huge_mm.h
> index 087920c38163..4ca675435856 100644
> --- a/include/linux/huge_mm.h
> +++ b/include/linux/huge_mm.h
> @@ -28,6 +28,8 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
>  			   pmd_t *pmd, unsigned long addr, unsigned long next);
>  bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, pmd_t *pmd,
>  		  unsigned long addr);
> +bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
> +			 unsigned long addr, unsigned long end);
>  int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud,
>  		 unsigned long addr);
>  bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
> diff --git a/include/linux/mm.h b/include/linux/mm.h
> index 00abd4d250a9..d28ba827f1d5 100644
> --- a/include/linux/mm.h
> +++ b/include/linux/mm.h
> @@ -3413,6 +3413,8 @@ struct zap_details {
>  #define  ZAP_FLAG_DROP_MARKER        ((__force zap_flags_t) BIT(0))
>  /* Set in unmap_vmas() to indicate a final unmap call.  Only used by hugetlb */
>  #define  ZAP_FLAG_UNMAP              ((__force zap_flags_t) BIT(1))
> +/* MADV_DONTNEED: zero part of a PMD-mapped THP in place instead of splitting */
> +#define  ZAP_FLAG_ZERO_PARTIAL_THP   ((__force zap_flags_t) BIT(2))
>  
>  #ifdef CONFIG_MMU
>  extern bool can_do_mlock(void);
> diff --git a/mm/huge_memory.c b/mm/huge_memory.c
> index 4fc888ddfb69..121da9397194 100644
> --- a/mm/huge_memory.c
> +++ b/mm/huge_memory.c
> @@ -2623,6 +2623,75 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
>  	return true;
>  }
>  
> +/*
> + * MADV_DONTNEED on [addr, end), part of a PMD-mapped THP: zero it in place
> + * instead of splitting the PMD, and queue the THP for the deferred split
> + * shrinker, which frees the zeroed pages once the THP is underused. Return
> + * false if the caller must split the PMD and zap the range instead.
> + */
> +bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
> +			 unsigned long addr, unsigned long end)
> +{
> +	unsigned long haddr = addr & HPAGE_PMD_MASK;
> +	struct folio *folio;
> +	spinlock_t *ptl;
> +	pmd_t orig_pmd;
> +	bool ret;
> +
> +	/* With max_ptes_none at 511, no THP is ever underused. */
> +	if (!READ_ONCE(split_underused_thp) ||
> +	    khugepaged_max_ptes_none == HPAGE_PMD_NR - 1)
> +		return false;
> +
> +	if ((vma->vm_flags & VM_MTE) || userfaultfd_armed(vma) ||
> +	    mm_forbids_zeropage(vma->vm_mm))
> +		return false;
> +
> +	ptl = pmd_trans_huge_lock(pmd, vma);
> +	if (!ptl)
> +		return false;
> +	orig_pmd = pmdp_get(pmd);
> +	if (is_huge_zero_pmd(orig_pmd)) {
> +		spin_unlock(ptl);
> +		return true;
> +	}
> +
> +	folio = pmd_present(orig_pmd) ?
> +		vm_normal_folio_pmd(vma, haddr, orig_pmd) : NULL;
> +	if (!folio || !folio_test_anon(folio) ||
> +	    !PageAnonExclusive(&folio->page) || folio_test_mlocked(folio) ||
> +	    folio_contain_hwpoisoned_page(folio) ||
> +	    folio_ref_count(folio) != folio_expected_ref_count(folio) ||
> +	    !folio_trylock(folio)) {
> +		spin_unlock(ptl);
> +		return false;
> +	}
> +	folio_get(folio);
> +	spin_unlock(ptl);
> +
> +	flush_cache_range(vma, addr, end);
> +	clear_contig_highpages(folio_page(folio, (addr - haddr) >> PAGE_SHIFT),
> +			       addr, (end - addr) >> PAGE_SHIFT);
> +
> +	/*
> +	 * Mark the PMD dirty, and soft-dirty, as a write through it would. If
> +	 * the PMD was split meanwhile, let the caller zap the range instead.
> +	 */
> +	ptl = pmd_lock(vma->vm_mm, pmd);
> +	orig_pmd = pmdp_get(pmd);
> +	ret = pmd_present(orig_pmd) && pmd_trans_huge(orig_pmd) &&
> +	      pmd_folio(orig_pmd) == folio;
> +	if (ret) {
> +		touch_pmd(vma, haddr, pmd, true);
> +		deferred_split_folio(folio, false);
> +	}
> +	spin_unlock(ptl);
> +
> +	folio_unlock(folio);
> +	folio_put(folio);
> +	return ret;
> +}

There is not a lot I like about this code :)

Why can't user space just do reasonable things instead?

-- 
Cheers,

David


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 11:22 ` David Hildenbrand (Arm)
@ 2026-12-02 14:26   ` Alexandre Ghiti
  2026-12-03 12:32     ` David Hildenbrand (Arm)
  0 siblings, 1 reply; 16+ messages in thread
From: Alexandre Ghiti @ 2026-12-02 14:26 UTC (permalink / raw)
  To: David Hildenbrand (Arm)
  Cc: Alexandre Ghiti, Andrew Morton, Zi Yan, Baolin Wang,
	Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain, Barry Song,
	Lance Yang, Usama Arif, Kiryl Shutsemau, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lorenzo Stoakes, Suren Baghdasaryan,
	Shakeel Butt, Pedro Falcato, Jann Horn, linux-mm, linux-kernel

Hi David,

On Wed, Dec 2, 2026 at 12:22 PM David Hildenbrand (Arm)
<david@kernel.org> wrote:
>
> >
> On 12/2/26 11:28, Alexandre Ghiti wrote:
>
> Hi,
>
> > MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> > the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> > stays allocated and charged as a whole, now partially mapped, until the
> > deferred split shrinker splits it under memory pressure. Until then the
> > process has lost the PMD mapping, and the TLB reach that comes with it, for
> > no memory benefit.
>
> Right. User space should avoid doing stupid things.

I think it's hard for userspace when a hugepage becomes partly used,
it can either keep it whole and waste its free memory, or give the
free pages back with MADV_DONTNEED and lose the PMD. I see
MADV_DONTNEED as an honest hint from userspace: "I have used this THP
for a while, but I'm not sure I'll need all of it in the near future,
but I'd like to keep the TLB benefits as long as possible. But under
memory pressure, the kernel can take it."

>
> >
> > Besides, a THP is checked for being underused only once: it is queued on
> > the deferred split list when it is created, and the shrinker drops it from
> > the list for good once it has found it not underused. A long-lived THP
> > whose pages are freed later is never looked at again, so its unused memory
> > can't be reclaimed.
>
> The job of the underused shrinking is to detect over-allocation. Not "user space
> used it and then partially freed it".

I thought the goal of the underused shrinker was broader than just
over-allocation, which raises these questions:

- do we need to detect *underused* THPs? I think we do, to reduce
internal fragmentation over time.
- for now, zero pages are the only way to detect them, so should the
kernel clear the freed pages or should userspace? Userspace already
uses MADV_DONTNEED to tell the kernel that the THP is sparse and can
be reclaimed.

>
> >
> > When the underused THP shrinker can reclaim the range later, zero it in
> > place instead: it reads as zeroes, as MADV_DONTNEED requires, and the PMD
> > mapping stays. The THP is queued again on the deferred split list, so the
> > shrinker looks at it again.
> >
> > For an exclusive anonymous THP, MADV_DONTNEED on part of it thus no longer
> > leaves it partially mapped: the range reads as zeroes at once, and the
> > memory is given back when reclaim needs it, once the THP holds more than
> > max_ptes_none zeroed pages. Below that, the THP is not split even under
> > memory pressure, where the partially mapped THP used to be split: it keeps
> > up to max_ptes_none zeroed pages, the waste khugepaged already allows when
> > collapsing.
> >
> > The range is zapped as before when the zeroed pages could not be freed,
> > e.g. with max_ptes_none at 511 (the default), or when anyone else may see
> > the THP, e.g. after fork or through a GUP pin.
> >
> > Results on a large production workload (THP=always, max_ptes_none=0,
> > allocator purging with MADV_DONTNEED), same allocator configuration before
> > and after this patch:
> >
> >   THPs and memory                       change
> >   ------------------------------------  ------
> >   THPs partially mapped                   -97%
> >   memory mapped by THPs (AnonHugePages)   +29%
> >   underused THP splits                   +145%
> >   PMD splits                              +10%
> >   workload anonymous memory              +0.2%
> >
> >   Performance                           change
> >   ------------------------------------  ------
> >   p50 latency                            -1.7%
> >   p99 latency                            -2.3%
> >   throughput                      within noise
> >   dTLB misses per instruction            -0.4%
> >   IPC                                    +0.2%
> >
> > Signed-off-by: Alexandre Ghiti <alex@ghiti.fr>
> > ---
> > Open questions:
> >
> > - MADV_DONTNEED now zeroes the range synchronously, up to a whole PMD
> >   minus one page (2M on x86, 512M with 64K base pages on arm64). Should
> >   zeroing be capped, falling back to the split above some size?
> >
> > - A pin taken while the range is being zeroed goes unnoticed, as neither
> >   GUP-fast nor GUP takes the folio lock: a device write through it (e.g. an
> >   O_DIRECT read into the range from another thread) can land after
> >   MADV_DONTNEED returns. Only a process doing I/O into memory it is
> >   discarding can see it; pins that exist when the THP is checked fall back
> >   to the zap. Closing the window would take a PMD invalidation and a TLB
> >   flush per call, which this patch avoids, or GUP backing off on a folio
> >   being zeroed. Is the race acceptable?
> >
> > - RSS (and so oom_badness()), /proc/pid/pagemap and mincore() keep showing
> >   the range as resident until the THP is split, where the zap made it
> >   disappear at once. memcg usage is unchanged: the THP stayed charged until
> >   its split before too.
> >
> > - The cow (THP_RUN_SINGLE_PTE), khugepaged and transhuge-stress selftests
> >   use a partial MADV_DONTNEED to split a PMD, which MADV_DONTNEED never
> >   guaranteed. khugepaged sets max_ptes_none to 511 first, but cow and
> >   transhuge-stress keep the host's value: with a lower max_ptes_none they
> >   still pass, while silently testing a PMD-mapped THP. They should pin
> >   max_ptes_none or split the PMD explicitly (MADV_NOHUGEPAGE, mprotect() or
> >   debugfs).
> >
> > PTE-mapped large folios (mTHP) are left for later.
> >
> >  include/linux/huge_mm.h |  2 ++
> >  include/linux/mm.h      |  2 ++
> >  mm/huge_memory.c        | 69 +++++++++++++++++++++++++++++++++++++++++
> >  mm/internal.h           |  3 ++
> >  mm/madvise.c            |  2 +-
> >  mm/memory.c             | 14 ++++++---
> >  6 files changed, 87 insertions(+), 5 deletions(-)
> >
> > diff --git a/include/linux/huge_mm.h b/include/linux/huge_mm.h
> > index 087920c38163..4ca675435856 100644
> > --- a/include/linux/huge_mm.h
> > +++ b/include/linux/huge_mm.h
> > @@ -28,6 +28,8 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
> >                          pmd_t *pmd, unsigned long addr, unsigned long next);
> >  bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, pmd_t *pmd,
> >                 unsigned long addr);
> > +bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
> > +                      unsigned long addr, unsigned long end);
> >  int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud,
> >                unsigned long addr);
> >  bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
> > diff --git a/include/linux/mm.h b/include/linux/mm.h
> > index 00abd4d250a9..d28ba827f1d5 100644
> > --- a/include/linux/mm.h
> > +++ b/include/linux/mm.h
> > @@ -3413,6 +3413,8 @@ struct zap_details {
> >  #define  ZAP_FLAG_DROP_MARKER        ((__force zap_flags_t) BIT(0))
> >  /* Set in unmap_vmas() to indicate a final unmap call.  Only used by hugetlb */
> >  #define  ZAP_FLAG_UNMAP              ((__force zap_flags_t) BIT(1))
> > +/* MADV_DONTNEED: zero part of a PMD-mapped THP in place instead of splitting */
> > +#define  ZAP_FLAG_ZERO_PARTIAL_THP   ((__force zap_flags_t) BIT(2))
> >
> >  #ifdef CONFIG_MMU
> >  extern bool can_do_mlock(void);
> > diff --git a/mm/huge_memory.c b/mm/huge_memory.c
> > index 4fc888ddfb69..121da9397194 100644
> > --- a/mm/huge_memory.c
> > +++ b/mm/huge_memory.c
> > @@ -2623,6 +2623,75 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
> >       return true;
> >  }
> >
> > +/*
> > + * MADV_DONTNEED on [addr, end), part of a PMD-mapped THP: zero it in place
> > + * instead of splitting the PMD, and queue the THP for the deferred split
> > + * shrinker, which frees the zeroed pages once the THP is underused. Return
> > + * false if the caller must split the PMD and zap the range instead.
> > + */
> > +bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
> > +                      unsigned long addr, unsigned long end)
> > +{
> > +     unsigned long haddr = addr & HPAGE_PMD_MASK;
> > +     struct folio *folio;
> > +     spinlock_t *ptl;
> > +     pmd_t orig_pmd;
> > +     bool ret;
> > +
> > +     /* With max_ptes_none at 511, no THP is ever underused. */
> > +     if (!READ_ONCE(split_underused_thp) ||
> > +         khugepaged_max_ptes_none == HPAGE_PMD_NR - 1)
> > +             return false;
> > +
> > +     if ((vma->vm_flags & VM_MTE) || userfaultfd_armed(vma) ||
> > +         mm_forbids_zeropage(vma->vm_mm))
> > +             return false;
> > +
> > +     ptl = pmd_trans_huge_lock(pmd, vma);
> > +     if (!ptl)
> > +             return false;
> > +     orig_pmd = pmdp_get(pmd);
> > +     if (is_huge_zero_pmd(orig_pmd)) {
> > +             spin_unlock(ptl);
> > +             return true;
> > +     }
> > +
> > +     folio = pmd_present(orig_pmd) ?
> > +             vm_normal_folio_pmd(vma, haddr, orig_pmd) : NULL;
> > +     if (!folio || !folio_test_anon(folio) ||
> > +         !PageAnonExclusive(&folio->page) || folio_test_mlocked(folio) ||
> > +         folio_contain_hwpoisoned_page(folio) ||
> > +         folio_ref_count(folio) != folio_expected_ref_count(folio) ||
> > +         !folio_trylock(folio)) {
> > +             spin_unlock(ptl);
> > +             return false;
> > +     }
> > +     folio_get(folio);
> > +     spin_unlock(ptl);
> > +
> > +     flush_cache_range(vma, addr, end);
> > +     clear_contig_highpages(folio_page(folio, (addr - haddr) >> PAGE_SHIFT),
> > +                            addr, (end - addr) >> PAGE_SHIFT);
> > +
> > +     /*
> > +      * Mark the PMD dirty, and soft-dirty, as a write through it would. If
> > +      * the PMD was split meanwhile, let the caller zap the range instead.
> > +      */
> > +     ptl = pmd_lock(vma->vm_mm, pmd);
> > +     orig_pmd = pmdp_get(pmd);
> > +     ret = pmd_present(orig_pmd) && pmd_trans_huge(orig_pmd) &&
> > +           pmd_folio(orig_pmd) == folio;
> > +     if (ret) {
> > +             touch_pmd(vma, haddr, pmd, true);
> > +             deferred_split_folio(folio, false);
> > +     }
> > +     spin_unlock(ptl);
> > +
> > +     folio_unlock(folio);
> > +     folio_put(folio);
> > +     return ret;
> > +}
>
> There is not a lot I like about this code :)
>
> Why can't user space just do reasonable things instead?
>
> --
> Cheers,
>
> David
>

Thanks for the quick review!

Alex


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 10:28 [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED Alexandre Ghiti
  2026-12-02 11:22 ` Lorenzo Stoakes (ARM)
  2026-12-02 11:22 ` David Hildenbrand (Arm)
@ 2026-12-02 16:37 ` Zi Yan
  2026-12-02 17:39   ` Alexandre Ghiti
  2026-12-02 20:28   ` David Hildenbrand (Arm)
  2026-12-02 18:04 ` Shakeel Butt
  2026-12-03 10:28 ` sashiko-bot
  4 siblings, 2 replies; 16+ messages in thread
From: Zi Yan @ 2026-12-02 16:37 UTC (permalink / raw)
  To: Alexandre Ghiti, Andrew Morton, David Hildenbrand
  Cc: Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain,
	Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Shakeel Butt, Pedro Falcato, Jann Horn,
	linux-mm, linux-kernel

On Wed Dec 2, 2026 at 5:28 AM EST, Alexandre Ghiti wrote:
> MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> stays allocated and charged as a whole, now partially mapped, until the
> deferred split shrinker splits it under memory pressure. Until then the
> process has lost the PMD mapping, and the TLB reach that comes with it, for
> no memory benefit.

Why would you expect the PMD mapping still exists after DONTNEED marks
part of a PMD THP? I do not think it is reasonable. Could someone abuse
it by always allocating PMD THPs and DONTNEED part of it just to get PMD
mappings?

>
> Besides, a THP is checked for being underused only once: it is queued on
> the deferred split list when it is created, and the shrinker drops it from
> the list for good once it has found it not underused. A long-lived THP
> whose pages are freed later is never looked at again, so its unused memory
> can't be reclaimed.
>
> When the underused THP shrinker can reclaim the range later, zero it in
> place instead: it reads as zeroes, as MADV_DONTNEED requires, and the PMD
> mapping stays. The THP is queued again on the deferred split list, so the
> shrinker looks at it again.
>
> For an exclusive anonymous THP, MADV_DONTNEED on part of it thus no longer
> leaves it partially mapped: the range reads as zeroes at once, and the
> memory is given back when reclaim needs it, once the THP holds more than
> max_ptes_none zeroed pages. Below that, the THP is not split even under
> memory pressure, where the partially mapped THP used to be split: it keeps
> up to max_ptes_none zeroed pages, the waste khugepaged already allows when
> collapsing.
>
> The range is zapped as before when the zeroed pages could not be freed,
> e.g. with max_ptes_none at 511 (the default), or when anyone else may see
> the THP, e.g. after fork or through a GUP pin.
>
> Results on a large production workload (THP=always, max_ptes_none=0,
> allocator purging with MADV_DONTNEED), same allocator configuration before
> and after this patch:

Since MADV_DONTNEED is slower, why is the perf not affected by it? The
purge is done in the background?


>
>   THPs and memory                       change
>   ------------------------------------  ------
>   THPs partially mapped                   -97%
>   memory mapped by THPs (AnonHugePages)   +29%
>   underused THP splits                   +145%
>   PMD splits                              +10%
>   workload anonymous memory              +0.2%
>
>   Performance                           change
>   ------------------------------------  ------
>   p50 latency                            -1.7%
>   p99 latency                            -2.3%
>   throughput                      within noise
>   dTLB misses per instruction            -0.4%
>   IPC                                    +0.2%
>
> Signed-off-by: Alexandre Ghiti <alex@ghiti.fr>
> ---
> Open questions:
>
> - MADV_DONTNEED now zeroes the range synchronously, up to a whole PMD
>   minus one page (2M on x86, 512M with 64K base pages on arm64). Should
>   zeroing be capped, falling back to the split above some size?
>
> - A pin taken while the range is being zeroed goes unnoticed, as neither
>   GUP-fast nor GUP takes the folio lock: a device write through it (e.g. an
>   O_DIRECT read into the range from another thread) can land after
>   MADV_DONTNEED returns. Only a process doing I/O into memory it is
>   discarding can see it; pins that exist when the THP is checked fall back
>   to the zap. Closing the window would take a PMD invalidation and a TLB
>   flush per call, which this patch avoids, or GUP backing off on a folio
>   being zeroed. Is the race acceptable?
>
> - RSS (and so oom_badness()), /proc/pid/pagemap and mincore() keep showing
>   the range as resident until the THP is split, where the zap made it
>   disappear at once. memcg usage is unchanged: the THP stayed charged until
>   its split before too.

It affects userspace apps checking RSS stats. What is the impact?

>
> - The cow (THP_RUN_SINGLE_PTE), khugepaged and transhuge-stress selftests
>   use a partial MADV_DONTNEED to split a PMD, which MADV_DONTNEED never
>   guaranteed. khugepaged sets max_ptes_none to 511 first, but cow and
>   transhuge-stress keep the host's value: with a lower max_ptes_none they
>   still pass, while silently testing a PMD-mapped THP. They should pin
>   max_ptes_none or split the PMD explicitly (MADV_NOHUGEPAGE, mprotect() or
>   debugfs).
>
> PTE-mapped large folios (mTHP) are left for later.
>
>  include/linux/huge_mm.h |  2 ++
>  include/linux/mm.h      |  2 ++
>  mm/huge_memory.c        | 69 +++++++++++++++++++++++++++++++++++++++++
>  mm/internal.h           |  3 ++
>  mm/madvise.c            |  2 +-
>  mm/memory.c             | 14 ++++++---
>  6 files changed, 87 insertions(+), 5 deletions(-)
>


-- 
Best Regards,
Yan, Zi



^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 16:37 ` Zi Yan
@ 2026-12-02 17:39   ` Alexandre Ghiti
  2026-12-02 20:28   ` David Hildenbrand (Arm)
  1 sibling, 0 replies; 16+ messages in thread
From: Alexandre Ghiti @ 2026-12-02 17:39 UTC (permalink / raw)
  To: Zi Yan
  Cc: Alexandre Ghiti, Andrew Morton, David Hildenbrand, Baolin Wang,
	Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain, Barry Song,
	Lance Yang, Usama Arif, Kiryl Shutsemau, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lorenzo Stoakes, Suren Baghdasaryan,
	Shakeel Butt, Pedro Falcato, Jann Horn, linux-mm, linux-kernel

Hi Zi,

On Wed, Dec 2, 2026 at 5:37 PM Zi Yan <ziy@nvidia.com> wrote:
>
> >
> On Wed Dec 2, 2026 at 5:28 AM EST, Alexandre Ghiti wrote:
> > MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> > the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> > stays allocated and charged as a whole, now partially mapped, until the
> > deferred split shrinker splits it under memory pressure. Until then the
> > process has lost the PMD mapping, and the TLB reach that comes with it, for
> > no memory benefit.
>
> Why would you expect the PMD mapping still exists after DONTNEED marks
> part of a PMD THP? I do not think it is reasonable.

Because the folio is not split yet and is still fully charged to the
cgroup, so let's keep the tlb benefits too?

> Could someone abuse
> it by always allocating PMD THPs and DONTNEED part of it just to get PMD
> mappings?

I'm probably missing your point but I don't see the benefit of doing
that, the thp would still be charged and RSS would not decrease.

>
> >
> > Besides, a THP is checked for being underused only once: it is queued on
> > the deferred split list when it is created, and the shrinker drops it from
> > the list for good once it has found it not underused. A long-lived THP
> > whose pages are freed later is never looked at again, so its unused memory
> > can't be reclaimed.
> >
> > When the underused THP shrinker can reclaim the range later, zero it in
> > place instead: it reads as zeroes, as MADV_DONTNEED requires, and the PMD
> > mapping stays. The THP is queued again on the deferred split list, so the
> > shrinker looks at it again.
> >
> > For an exclusive anonymous THP, MADV_DONTNEED on part of it thus no longer
> > leaves it partially mapped: the range reads as zeroes at once, and the
> > memory is given back when reclaim needs it, once the THP holds more than
> > max_ptes_none zeroed pages. Below that, the THP is not split even under
> > memory pressure, where the partially mapped THP used to be split: it keeps
> > up to max_ptes_none zeroed pages, the waste khugepaged already allows when
> > collapsing.
> >
> > The range is zapped as before when the zeroed pages could not be freed,
> > e.g. with max_ptes_none at 511 (the default), or when anyone else may see
> > the THP, e.g. after fork or through a GUP pin.
> >
> > Results on a large production workload (THP=always, max_ptes_none=0,
> > allocator purging with MADV_DONTNEED), same allocator configuration before
> > and after this patch:
>
> Since MADV_DONTNEED is slower, why is the perf not affected by it? The
> purge is done in the background?

No, the purge is done inline. But I measured roughly that the split of
a PMD costs at least as much as zeroing ~128 pages, so we can come up
with a "good" threshold: this patch does not make MADV_DONTNEED more
costly.

>
>
> >
> >   THPs and memory                       change
> >   ------------------------------------  ------
> >   THPs partially mapped                   -97%
> >   memory mapped by THPs (AnonHugePages)   +29%
> >   underused THP splits                   +145%
> >   PMD splits                              +10%
> >   workload anonymous memory              +0.2%
> >
> >   Performance                           change
> >   ------------------------------------  ------
> >   p50 latency                            -1.7%
> >   p99 latency                            -2.3%
> >   throughput                      within noise
> >   dTLB misses per instruction            -0.4%
> >   IPC                                    +0.2%
> >
> > Signed-off-by: Alexandre Ghiti <alex@ghiti.fr>
> > ---
> > Open questions:
> >
> > - MADV_DONTNEED now zeroes the range synchronously, up to a whole PMD
> >   minus one page (2M on x86, 512M with 64K base pages on arm64). Should
> >   zeroing be capped, falling back to the split above some size?
> >
> > - A pin taken while the range is being zeroed goes unnoticed, as neither
> >   GUP-fast nor GUP takes the folio lock: a device write through it (e.g. an
> >   O_DIRECT read into the range from another thread) can land after
> >   MADV_DONTNEED returns. Only a process doing I/O into memory it is
> >   discarding can see it; pins that exist when the THP is checked fall back
> >   to the zap. Closing the window would take a PMD invalidation and a TLB
> >   flush per call, which this patch avoids, or GUP backing off on a folio
> >   being zeroed. Is the race acceptable?
> >
> > - RSS (and so oom_badness()), /proc/pid/pagemap and mincore() keep showing
> >   the range as resident until the THP is split, where the zap made it
> >   disappear at once. memcg usage is unchanged: the THP stayed charged until
> >   its split before too.
>
> It affects userspace apps checking RSS stats. What is the impact?

It's hard to know how userspace uses RSS, OOM victim selection uses
RSS (according to my AI) so this might make a process more likely to
be OOMed under pressure?

But note that the production workload I'm mentioning is a huge
partially-mapped consumer and you can see that it only increased RSS
by 0.2%.

Thanks for your feedback!

Alex

>
> >
> > - The cow (THP_RUN_SINGLE_PTE), khugepaged and transhuge-stress selftests
> >   use a partial MADV_DONTNEED to split a PMD, which MADV_DONTNEED never
> >   guaranteed. khugepaged sets max_ptes_none to 511 first, but cow and
> >   transhuge-stress keep the host's value: with a lower max_ptes_none they
> >   still pass, while silently testing a PMD-mapped THP. They should pin
> >   max_ptes_none or split the PMD explicitly (MADV_NOHUGEPAGE, mprotect() or
> >   debugfs).
> >
> > PTE-mapped large folios (mTHP) are left for later.
> >
> >  include/linux/huge_mm.h |  2 ++
> >  include/linux/mm.h      |  2 ++
> >  mm/huge_memory.c        | 69 +++++++++++++++++++++++++++++++++++++++++
> >  mm/internal.h           |  3 ++
> >  mm/madvise.c            |  2 +-
> >  mm/memory.c             | 14 ++++++---
> >  6 files changed, 87 insertions(+), 5 deletions(-)
> >
>
>
> --
> Best Regards,
> Yan, Zi
>
>


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 10:28 [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED Alexandre Ghiti
                   ` (2 preceding siblings ...)
  2026-12-02 16:37 ` Zi Yan
@ 2026-12-02 18:04 ` Shakeel Butt
  2026-12-03 14:53   ` Alexandre Ghiti
  2026-12-03 10:28 ` sashiko-bot
  4 siblings, 1 reply; 16+ messages in thread
From: Shakeel Butt @ 2026-12-02 18:04 UTC (permalink / raw)
  To: Alexandre Ghiti
  Cc: Andrew Morton, David Hildenbrand, Zi Yan, Baolin Wang,
	Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain, Barry Song,
	Lance Yang, Usama Arif, Kiryl Shutsemau, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lorenzo Stoakes, Suren Baghdasaryan,
	Pedro Falcato, Jann Horn, linux-mm, linux-kernel

On Wed, Dec 02, 2026 at 11:28:10AM +0100, Alexandre Ghiti wrote:
> MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> stays allocated and charged as a whole, now partially mapped, until the
> deferred split shrinker splits it under memory pressure. Until then the
> process has lost the PMD mapping, and the TLB reach that comes with it, for
> no memory benefit.

Isn't the actual problem higher and unexpected memory usage? Application or the
malloc implementations do madvise(MADV_DONTNEED) to release memory and expect at
least decrease in RSS. Why not fix the cgroup memory usage as well by
synchronously break the THP as well. See
https://lore.kernel.org/all/20211120201230.920082-1-shakeelb@google.com/



^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 16:37 ` Zi Yan
  2026-12-02 17:39   ` Alexandre Ghiti
@ 2026-12-02 20:28   ` David Hildenbrand (Arm)
  1 sibling, 0 replies; 16+ messages in thread
From: David Hildenbrand (Arm) @ 2026-12-02 20:28 UTC (permalink / raw)
  To: Zi Yan, Alexandre Ghiti, Andrew Morton
  Cc: Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain,
	Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Shakeel Butt, Pedro Falcato, Jann Horn,
	linux-mm, linux-kernel

On 12/2/26 17:37, Zi Yan wrote:
> On Wed Dec 2, 2026 at 5:28 AM EST, Alexandre Ghiti wrote:
>> MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
>> the PMD and zaps the PTEs of the range. The THP itself is not freed: it
>> stays allocated and charged as a whole, now partially mapped, until the
>> deferred split shrinker splits it under memory pressure. Until then the
>> process has lost the PMD mapping, and the TLB reach that comes with it, for
>> no memory benefit.
> 
> Why would you expect the PMD mapping still exists after DONTNEED marks
> part of a PMD THP? I do not think it is reasonable. Could someone abuse
> it by always allocating PMD THPs and DONTNEED part of it just to get PMD
> mappings?
> 
>>
>> Besides, a THP is checked for being underused only once: it is queued on
>> the deferred split list when it is created, and the shrinker drops it from
>> the list for good once it has found it not underused. A long-lived THP
>> whose pages are freed later is never looked at again, so its unused memory
>> can't be reclaimed.
>>
>> When the underused THP shrinker can reclaim the range later, zero it in
>> place instead: it reads as zeroes, as MADV_DONTNEED requires, and the PMD
>> mapping stays. The THP is queued again on the deferred split list, so the
>> shrinker looks at it again.
>>
>> For an exclusive anonymous THP, MADV_DONTNEED on part of it thus no longer
>> leaves it partially mapped: the range reads as zeroes at once, and the
>> memory is given back when reclaim needs it, once the THP holds more than
>> max_ptes_none zeroed pages. Below that, the THP is not split even under
>> memory pressure, where the partially mapped THP used to be split: it keeps
>> up to max_ptes_none zeroed pages, the waste khugepaged already allows when
>> collapsing.
>>
>> The range is zapped as before when the zeroed pages could not be freed,
>> e.g. with max_ptes_none at 511 (the default), or when anyone else may see
>> the THP, e.g. after fork or through a GUP pin.
>>
>> Results on a large production workload (THP=always, max_ptes_none=0,
>> allocator purging with MADV_DONTNEED), same allocator configuration before
>> and after this patch:
> 
> Since MADV_DONTNEED is slower, why is the perf not affected by it? The
> purge is done in the background?
> 
> 
>>
>>   THPs and memory                       change
>>   ------------------------------------  ------
>>   THPs partially mapped                   -97%
>>   memory mapped by THPs (AnonHugePages)   +29%
>>   underused THP splits                   +145%
>>   PMD splits                              +10%
>>   workload anonymous memory              +0.2%
>>
>>   Performance                           change
>>   ------------------------------------  ------
>>   p50 latency                            -1.7%
>>   p99 latency                            -2.3%
>>   throughput                      within noise
>>   dTLB misses per instruction            -0.4%
>>   IPC                                    +0.2%
>>
>> Signed-off-by: Alexandre Ghiti <alex@ghiti.fr>
>> ---
>> Open questions:
>>
>> - MADV_DONTNEED now zeroes the range synchronously, up to a whole PMD
>>   minus one page (2M on x86, 512M with 64K base pages on arm64). Should
>>   zeroing be capped, falling back to the split above some size?
>>
>> - A pin taken while the range is being zeroed goes unnoticed, as neither
>>   GUP-fast nor GUP takes the folio lock: a device write through it (e.g. an
>>   O_DIRECT read into the range from another thread) can land after
>>   MADV_DONTNEED returns. Only a process doing I/O into memory it is
>>   discarding can see it; pins that exist when the THP is checked fall back
>>   to the zap. Closing the window would take a PMD invalidation and a TLB
>>   flush per call, which this patch avoids, or GUP backing off on a folio
>>   being zeroed. Is the race acceptable?
>>
>> - RSS (and so oom_badness()), /proc/pid/pagemap and mincore() keep showing
>>   the range as resident until the THP is split, where the zap made it
>>   disappear at once. memcg usage is unchanged: the THP stayed charged until
>>   its split before too.
> 
> It affects userspace apps checking RSS stats. What is the impact?

I think this change can completely break userfaultfd and other code that relies
on MADV_DONTNEED == zap.

So I don't think we want this change.

-- 
Cheers,

David


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 10:28 [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED Alexandre Ghiti
                   ` (3 preceding siblings ...)
  2026-12-02 18:04 ` Shakeel Butt
@ 2026-12-03 10:28 ` sashiko-bot
  4 siblings, 0 replies; 16+ messages in thread
From: sashiko-bot @ 2026-12-03 10:28 UTC (permalink / raw)
  To: Alexandre Ghiti, Andrew Morton, David Hildenbrand, Zi Yan
  Cc: Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain,
	Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Shakeel Butt, Pedro Falcato, Jann Horn,
	linux-mm

Thank you for your contribution! Sashiko AI review found 7 potential
issues to consider:
- [Medium] mm: VM_WARN_ON_FOLIO() in deferred_split_folio() from
  zero_huge_pmd_range()
- [Medium] mm: zero_huge_pmd_range() redirties lazyfree THPs and cancels
  MADV_FREE
- [Medium] mm: touch_pmd() in zero_huge_pmd_range() corrupts x86 shadow
  stack PMDs
- [Medium] mm: race in zero_huge_pmd_range() drops underused THPs from
  split queue
- [Medium] mm: missing cache synchronization after zeroing in
  zero_huge_pmd_range()
- [Medium] mm: zero_huge_pmd_range() fails to queue swapcache THP on
  deferred split list
- [Medium] mm:huge_memory: reclaim and lazyfree regressions in
  zero_huge_pmd_range()
--

commit 68aeca962725b589429831991dcbf23772370b18
Author: Alexandre Ghiti <alex@ghiti.fr>

mm: madvise: don't split a PMD on partial THP MADV_DONTNEED

This commit zeroes partial MADV_DONTNEED ranges of exclusive PMD-mapped
anonymous THPs in place and queues the THP on the deferred split list
instead of splitting the PMD immediately.

> diff --git a/mm/huge_memory.c b/mm/huge_memory.c
> index 4fc888ddfb69f..121da93971941 100644
> --- a/mm/huge_memory.c
> +++ b/mm/huge_memory.c
> @@ -2623,6 +2623,75 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
>  	return true;
>  }
>  
> +/*
> + * MADV_DONTNEED on [addr, end), part of a PMD-mapped THP: zero it in place
> + * instead of splitting the PMD, and queue the THP for the deferred split
> + * shrinker, which frees the zeroed pages once the THP is underused. Return
> + * false if the caller must split the PMD and zap the range instead.
> + */
> +bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
> +			 unsigned long addr, unsigned long end)
> +{
> +	unsigned long haddr = addr & HPAGE_PMD_MASK;
> +	struct folio *folio;
> +	spinlock_t *ptl;
> +	pmd_t orig_pmd;
> +	bool ret;
> +
> +	/* With max_ptes_none at 511, no THP is ever underused. */
> +	if (!READ_ONCE(split_underused_thp) ||
> +	    khugepaged_max_ptes_none == HPAGE_PMD_NR - 1)
> +		return false;
> +
> +	if ((vma->vm_flags & VM_MTE) || userfaultfd_armed(vma) ||
> +	    mm_forbids_zeropage(vma->vm_mm))
> +		return false;
> +
> +	ptl = pmd_trans_huge_lock(pmd, vma);
> +	if (!ptl)
> +		return false;
> +	orig_pmd = pmdp_get(pmd);
> +	if (is_huge_zero_pmd(orig_pmd)) {
> +		spin_unlock(ptl);
> +		return true;
> +	}
> +
> +	folio = pmd_present(orig_pmd) ?
> +		vm_normal_folio_pmd(vma, haddr, orig_pmd) : NULL;
> +	if (!folio || !folio_test_anon(folio) ||
> +	    !PageAnonExclusive(&folio->page) || folio_test_mlocked(folio) ||
> +	    folio_contain_hwpoisoned_page(folio) ||
> +	    folio_ref_count(folio) != folio_expected_ref_count(folio) ||
> +	    !folio_trylock(folio)) {
> +		spin_unlock(ptl);
> +		return false;
> +	}

[Severity: Medium]
Can a swapcache THP pass this check and then fail to be queued by
deferred_split_folio()?

folio_expected_ref_count() includes folio_test_swapcache(folio) << order,
so an exclusive PMD-mapped THP in the swapcache (for instance, after
shrink_folio_list() allocated swap and try_to_unmap_one() stopped on a
concurrent VMA_LOCKONFAULT walk before splitting the PMD) is accepted here
and zeroed in place.  However, deferred_split_folio() returns immediately
when folio_test_swapcache(folio) is true:

mm/huge_memory.c:deferred_split_folio() {
	...
	if (folio_test_swapcache(folio))
		return;
	...
}

Because zero_huge_pmd_range() neither frees the swapcache via
folio_free_swap() nor rejects swapcache folios, it returns true without
queueing the THP on the deferred split list, so the underused THP shrinker
will not reclaim the zeroed pages.

> +	folio_get(folio);
> +	spin_unlock(ptl);
> +
> +	flush_cache_range(vma, addr, end);
> +	clear_contig_highpages(folio_page(folio, (addr - haddr) >> PAGE_SHIFT),
> +			       addr, (end - addr) >> PAGE_SHIFT);

[Severity: Medium]
Does zeroing an already-mapped folio via clear_contig_highpages() without
flush_dcache_folio() leave stale instruction or data cache lines on
architectures with non-coherent I-caches or aliasing D-caches?

clear_contig_highpages() writes zeroes through the kernel linear mapping,
and flush_cache_range() is a no-op on architectures such as arm64 and
riscv that track cache cleanliness via PG_dcache_clean.  Without
flush_dcache_folio(folio) after zeroing, PG_dcache_clean stays set and the
zeroed lines are not cleaned to PoU or invalidated from the I-cache, so an
executable VMA (or a JIT VMA later mprotected back to PROT_EXEC, where
__sync_icache_dcache() skips sync_icache_aliases() when PG_dcache_clean is
set) can execute stale instructions from before MADV_DONTNEED.

> +	/*
> +	 * Mark the PMD dirty, and soft-dirty, as a write through it would. If
> +	 * the PMD was split meanwhile, let the caller zap the range instead.
> +	 */
> +	ptl = pmd_lock(vma->vm_mm, pmd);
> +	orig_pmd = pmdp_get(pmd);
> +	ret = pmd_present(orig_pmd) && pmd_trans_huge(orig_pmd) &&
> +	      pmd_folio(orig_pmd) == folio;
> +	if (ret) {
> +		touch_pmd(vma, haddr, pmd, true);

[Severity: Medium]
Does calling touch_pmd(vma, haddr, pmd, true) on a lazyfree THP redirty
the entire PMD and cancel an earlier MADV_FREE?

When MADV_FREE is called on a PMD-mapped THP, madvise_free_huge_pmd()
clears PG_dirty, marks the PMD old and clean, and clears PG_swapbacked via
folio_mark_lazyfree().  A subsequent partial MADV_DONTNEED now calls
touch_pmd(..., true), setting pmd_mkdirty() and pmd_mkyoung() on the whole
PMD.  When reclaim later inspects or splits the PMD in
__discard_anon_folio_pmd_locked() or __split_huge_pmd_locked() ->
ttu_anon_lazyfree_folio(), pmd_dirty() is transferred to PG_dirty on the
folio, which causes reclaim to restore PG_swapbacked and swap out the
remaining pages instead of discarding them without I/O.

[Severity: Medium]
Can touch_pmd(vma, haddr, pmd, true) corrupt an x86 shadow stack PMD?

On x86, a writable shadow stack PMD in a VM_SHADOW_STACK VMA is encoded
with _PAGE_RW=0 and _PAGE_DIRTY=1.  touch_pmd() calls pmd_mkdirty(entry)
without maybe_pmd_mkwrite(entry, vma):

arch/x86/include/asm/pgtable.h:pmd_mkdirty() {
	pmd = pmd_set_flags(pmd, _PAGE_DIRTY | _PAGE_SOFT_DIRTY);

	return pmd_mksaveddirty(pmd);
}

Because _PAGE_RW is 0, pmd_mksaveddirty() clears _PAGE_DIRTY and sets
_PAGE_SAVED_DIRTY, and pmdp_set_access_flags() writes that entry into
*pmd, turning the shadow stack PMD into a read-only non-shadow-stack PMD.

[Severity: Medium]
Does keeping the THP mapped with partially_mapped=false and marking the
PMD young cause shrink_folio_list() to swap out underused THPs in full
instead of splitting them?

In shrink_folio_list(), queued large folios are only split before
folio_alloc_swap() when folio_test_partially_mapped(folio) is true:

mm/vmscan.c:shrink_folio_list() {
	...
	if (data_race(!list_empty(&folio->_deferred_list) &&
	    folio_test_partially_mapped(folio)) &&
	    split_folio_to_list(folio, folio_list))
		goto activate_locked;
}

Because shrink_lruvec() runs shrink_folio_list() before shrink_slab() (and
MADV_PAGEOUT / DAMON_PAGEOUT do not run shrink_slab() at all), an
underused THP queued with partially_mapped=false is not split before
folio_alloc_swap() and is written to a 2MB swap cluster in full, including
the MADV_DONTNEED-zeroed pages.  In addition, touch_pmd() marks the PMD
young, causing folio_check_references() to treat a cold THP being
partially discarded as recently accessed.

> +		deferred_split_folio(folio, false);
> +	}

[Severity: Medium]
Can deferred_split_folio(folio, false) trigger
VM_WARN_ON_FOLIO(folio_test_partially_mapped(folio), folio) here?

deferred_split_folio() warns whenever partially_mapped is false and
PG_partially_mapped is already set on the folio:

mm/huge_memory.c:deferred_split_folio() {
	...
	if (partially_mapped) {
		...
	} else {
		/* partially mapped folios cannot become non-partially mapped */
		VM_WARN_ON_FOLIO(folio_test_partially_mapped(folio), folio);
	}
	...
}

PG_partially_mapped is sticky until the folio is split or freed.  If a
PMD-mapped THP was shared across fork(), the child split its PMD and
unmapped some PTEs, and try_to_migrate() temporarily converted the
parent's PMD to a migration entry, __folio_remove_rmap() saw the last PMD
unmapped while fewer than HPAGE_PMD_NR PTEs remained in the child and
called deferred_split_folio(folio, true), setting PG_partially_mapped
(which migrate_folio_move() also copies to the destination folio).  Once
the child exits and a write fault in do_huge_pmd_wp_page() restores
PageAnonExclusive on the parent's PMD, a partial MADV_DONTNEED reaches
deferred_split_folio(folio, false) and hits the warning.

> +	spin_unlock(ptl);
> +
> +	folio_unlock(folio);
> +	folio_put(folio);
> +	return ret;
> +}

[Severity: Medium]
Can a concurrent deferred_split_scan() run between folio_unlock() and
folio_put(), fail split_folio() because of the extra reference, and drop
the underused THP from the split queue?

CPU0                                    CPU1
zero_huge_pmd_range()
  folio_get(folio)
  ...
  deferred_split_folio(folio, false)
  spin_unlock(ptl)
  folio_unlock(folio)
                                        deferred_split_scan()
                                          thp_underused(folio) -> true
                                          folio_trylock(folio)
                                          split_folio(folio) -> -EAGAIN
                                          folio_unlock(folio)
                                          /* !partially_mapped: not requeued */
  folio_put(folio)

Because deferred_split_scan() only requeues folios after a failed
split_folio() when folio_test_partially_mapped(folio) is true, the
underused THP is removed from deferred_split_lru and its zeroed pages are
not reclaimed.  Dropping the temporary folio reference before
folio_unlock() (or queueing after dropping the extra reference) would
close this window.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/20261202102818.1317130-1-alex@ghiti.fr?part=1


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 14:26   ` Alexandre Ghiti
@ 2026-12-03 12:32     ` David Hildenbrand (Arm)
  0 siblings, 0 replies; 16+ messages in thread
From: David Hildenbrand (Arm) @ 2026-12-03 12:32 UTC (permalink / raw)
  To: Alexandre Ghiti
  Cc: Alexandre Ghiti, Andrew Morton, Zi Yan, Baolin Wang,
	Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain, Barry Song,
	Lance Yang, Usama Arif, Kiryl Shutsemau, Vlastimil Babka,
	Mike Rapoport, Michal Hocko, Lorenzo Stoakes, Suren Baghdasaryan,
	Shakeel Butt, Pedro Falcato, Jann Horn, linux-mm, linux-kernel

On 12/2/26 15:26, Alexandre Ghiti wrote:
> Hi David,
> 
> On Wed, Dec 2, 2026 at 12:22 PM David Hildenbrand (Arm)
> <david@kernel.org> wrote:
>>
>>>
>> On 12/2/26 11:28, Alexandre Ghiti wrote:
>>
>> Hi,
>>
>>> MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
>>> the PMD and zaps the PTEs of the range. The THP itself is not freed: it
>>> stays allocated and charged as a whole, now partially mapped, until the
>>> deferred split shrinker splits it under memory pressure. Until then the
>>> process has lost the PMD mapping, and the TLB reach that comes with it, for
>>> no memory benefit.
>>
>> Right. User space should avoid doing stupid things.
> 
> I think it's hard for userspace when a hugepage becomes partly used,
> it can either keep it whole and waste its free memory, or give the
> free pages back with MADV_DONTNEED and lose the PMD. I see
> MADV_DONTNEED as an honest hint from userspace: "I have used this THP
> for a while, but I'm not sure I'll need all of it in the near future,
> but I'd like to keep the TLB benefits as long as possible. But under
> memory pressure, the kernel can take it."

MADV_DONTNEED means "zap". We'd have to introduce something new with different
semantics. Which I am not a fan of.

If you care about THP benefits, don't shatter THPs with MADV_DONTNEED.

> 
>>
>>>
>>> Besides, a THP is checked for being underused only once: it is queued on
>>> the deferred split list when it is created, and the shrinker drops it from
>>> the list for good once it has found it not underused. A long-lived THP
>>> whose pages are freed later is never looked at again, so its unused memory
>>> can't be reclaimed.
>>
>> The job of the underused shrinking is to detect over-allocation. Not "user space
>> used it and then partially freed it".
> 
> I thought the goal of the underused shrinker was broader than just
> over-allocation, which raises these questions:

No. It's all about over-allocation right now. That's why we scan exactly once.

-- 
Cheers,

David


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 11:22 ` Lorenzo Stoakes (ARM)
@ 2026-12-03 14:10   ` Alexandre Ghiti
  0 siblings, 0 replies; 16+ messages in thread
From: Alexandre Ghiti @ 2026-12-03 14:10 UTC (permalink / raw)
  To: Lorenzo Stoakes (ARM)
  Cc: Alexandre Ghiti, Andrew Morton, David Hildenbrand, Zi Yan,
	Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain,
	Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Suren Baghdasaryan,
	Shakeel Butt, Pedro Falcato, Jann Horn, linux-mm, linux-kernel

Hi Lorenzo,

On Wed, Dec 2, 2026 at 12:22 PM Lorenzo Stoakes (ARM) <ljs@kernel.org> wrote:
>
> >
> On Wed, Dec 02, 2026 at 11:28:10AM +0100, Alexandre Ghiti wrote:
> > MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> > the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> > stays allocated and charged as a whole, now partially mapped, until the
> > deferred split shrinker splits it under memory pressure. Until then the
> > process has lost the PMD mapping, and the TLB reach that comes with it, for
> > no memory benefit.
> >
> > Besides, a THP is checked for being underused only once: it is queued on
> > the deferred split list when it is created, and the shrinker drops it from
> > the list for good once it has found it not underused. A long-lived THP
> > whose pages are freed later is never looked at again, so its unused memory
> > can't be reclaimed.
> >
> > When the underused THP shrinker can reclaim the range later, zero it in
> > place instead: it reads as zeroes, as MADV_DONTNEED requires, and the PMD
> > mapping stays. The THP is queued again on the deferred split list, so the
> > shrinker looks at it again.
> >
> > For an exclusive anonymous THP, MADV_DONTNEED on part of it thus no longer
> > leaves it partially mapped: the range reads as zeroes at once, and the
> > memory is given back when reclaim needs it, once the THP holds more than
> > max_ptes_none zeroed pages. Below that, the THP is not split even under
> > memory pressure, where the partially mapped THP used to be split: it keeps
> > up to max_ptes_none zeroed pages, the waste khugepaged already allows when
> > collapsing.
> >
> > The range is zapped as before when the zeroed pages could not be freed,
> > e.g. with max_ptes_none at 511 (the default), or when anyone else may see
> > the THP, e.g. after fork or through a GUP pin.
> >
> > Results on a large production workload (THP=always, max_ptes_none=0,
> > allocator purging with MADV_DONTNEED), same allocator configuration before
> > and after this patch:
>
> This whole thing reads like AI, too dense, too may words, not to the point,
> not for humans.
>
> It needs human rewriting to be succinct and sane.
>
> >
> >   THPs and memory                       change
> >   ------------------------------------  ------
> >   THPs partially mapped                   -97%
> >   memory mapped by THPs (AnonHugePages)   +29%
> >   underused THP splits                   +145%
> >   PMD splits                              +10%
> >   workload anonymous memory              +0.2%
> >
> >   Performance                           change
> >   ------------------------------------  ------
> >   p50 latency                            -1.7%
> >   p99 latency                            -2.3%
> >   throughput                      within noise
> >   dTLB misses per instruction            -0.4%
> >   IPC                                    +0.2%
> >
> > Signed-off-by: Alexandre Ghiti <alex@ghiti.fr>
>
> OK I see this is an RFC, I will leave it to the THP maintainers for an
> architectural review, but the code needs rewriting for it to be
> in any way upstreamable.
>
> > ---
> > Open questions:
> >
> > - MADV_DONTNEED now zeroes the range synchronously, up to a whole PMD
> >   minus one page (2M on x86, 512M with 64K base pages on arm64). Should
> >   zeroing be capped, falling back to the split above some size?
> >
> > - A pin taken while the range is being zeroed goes unnoticed, as neither
> >   GUP-fast nor GUP takes the folio lock: a device write through it (e.g. an
> >   O_DIRECT read into the range from another thread) can land after
> >   MADV_DONTNEED returns. Only a process doing I/O into memory it is
> >   discarding can see it; pins that exist when the THP is checked fall back
> >   to the zap. Closing the window would take a PMD invalidation and a TLB
> >   flush per call, which this patch avoids, or GUP backing off on a folio
> >   being zeroed. Is the race acceptable?
> >
> > - RSS (and so oom_badness()), /proc/pid/pagemap and mincore() keep showing
> >   the range as resident until the THP is split, where the zap made it
> >   disappear at once. memcg usage is unchanged: the THP stayed charged until
> >   its split before too.
> >
> > - The cow (THP_RUN_SINGLE_PTE), khugepaged and transhuge-stress selftests
> >   use a partial MADV_DONTNEED to split a PMD, which MADV_DONTNEED never
> >   guaranteed. khugepaged sets max_ptes_none to 511 first, but cow and
> >   transhuge-stress keep the host's value: with a lower max_ptes_none they
> >   still pass, while silently testing a PMD-mapped THP. They should pin
> >   max_ptes_none or split the PMD explicitly (MADV_NOHUGEPAGE, mprotect() or
> >   debugfs).
>
> This reads LLM-generated and packs a ton into each paragraph. Can you write
> this for humans please?
>
> >
> > PTE-mapped large folios (mTHP) are left for later.
>
> Is that the plan going forward? Weird to have a million words on open
> questions above then nothing on this :)
>
> >
> >  include/linux/huge_mm.h |  2 ++
> >  include/linux/mm.h      |  2 ++
> >  mm/huge_memory.c        | 69 +++++++++++++++++++++++++++++++++++++++++
> >  mm/internal.h           |  3 ++
> >  mm/madvise.c            |  2 +-
> >  mm/memory.c             | 14 ++++++---
> >  6 files changed, 87 insertions(+), 5 deletions(-)
> >
> > diff --git a/include/linux/huge_mm.h b/include/linux/huge_mm.h
> > index 087920c38163..4ca675435856 100644
> > --- a/include/linux/huge_mm.h
> > +++ b/include/linux/huge_mm.h
> > @@ -28,6 +28,8 @@ bool madvise_free_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
> >                          pmd_t *pmd, unsigned long addr, unsigned long next);
> >  bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma, pmd_t *pmd,
> >                 unsigned long addr);
> > +bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
> > +                      unsigned long addr, unsigned long end);
> >  int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma, pud_t *pud,
> >                unsigned long addr);
> >  bool move_huge_pmd(struct vm_area_struct *vma, unsigned long old_addr,
> > diff --git a/include/linux/mm.h b/include/linux/mm.h
> > index 00abd4d250a9..d28ba827f1d5 100644
> > --- a/include/linux/mm.h
> > +++ b/include/linux/mm.h
> > @@ -3413,6 +3413,8 @@ struct zap_details {
> >  #define  ZAP_FLAG_DROP_MARKER        ((__force zap_flags_t) BIT(0))
> >  /* Set in unmap_vmas() to indicate a final unmap call.  Only used by hugetlb */
> >  #define  ZAP_FLAG_UNMAP              ((__force zap_flags_t) BIT(1))
> > +/* MADV_DONTNEED: zero part of a PMD-mapped THP in place instead of splitting */
> > +#define  ZAP_FLAG_ZERO_PARTIAL_THP   ((__force zap_flags_t) BIT(2))
>
> Do we really have to expand this horrible interface any further?
>
> >
> >  #ifdef CONFIG_MMU
> >  extern bool can_do_mlock(void);
> > diff --git a/mm/huge_memory.c b/mm/huge_memory.c
> > index 4fc888ddfb69..121da9397194 100644
> > --- a/mm/huge_memory.c
> > +++ b/mm/huge_memory.c
> > @@ -2623,6 +2623,75 @@ bool zap_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,
> >       return true;
> >  }
> >
> > +/*
> > + * MADV_DONTNEED on [addr, end), part of a PMD-mapped THP: zero it in place
> > + * instead of splitting the PMD, and queue the THP for the deferred split
> > + * shrinker, which frees the zeroed pages once the THP is underused. Return
> > + * false if the caller must split the PMD and zap the range instead.
> > + */
>
> This comment is horribly schloppy. The functino name has nothing to do with
> it, and this is now a function you're exposing to a header called 'zero
> huge PMD range' but the comment talks about a use case?
>
> Horrible sorry.
>
> > +bool zero_huge_pmd_range(struct vm_area_struct *vma, pmd_t *pmd,
> > +                      unsigned long addr, unsigned long end)
> > +{
> > +     unsigned long haddr = addr & HPAGE_PMD_MASK;
> > +     struct folio *folio;
> > +     spinlock_t *ptl;
> > +     pmd_t orig_pmd;
> > +     bool ret;
> > +
> > +     /* With max_ptes_none at 511, no THP is ever underused. */
> > +     if (!READ_ONCE(split_underused_thp) ||
> > +         khugepaged_max_ptes_none == HPAGE_PMD_NR - 1)
> > +             return false;
>
> This feels like it should be abstracted.
>
> > +
> > +     if ((vma->vm_flags & VM_MTE) || userfaultfd_armed(vma) ||
>
> Why are you using the legacy VMA flag interface in new code? And why
> explicitly reference an x86 feature?...
>
> These are all signals that you didn't abstract things correctly.
>
> > +         mm_forbids_zeropage(vma->vm_mm))
> > +             return false;
>
> No (SHORT) comment to explain why these are excluded?
>
> > +
> > +     ptl = pmd_trans_huge_lock(pmd, vma);
> > +     if (!ptl)
> > +             return false;
> > +     orig_pmd = pmdp_get(pmd);
> > +     if (is_huge_zero_pmd(orig_pmd)) {
> > +             spin_unlock(ptl);
> > +             return true;
> > +     }
> > +
> > +     folio = pmd_present(orig_pmd) ?
> > +             vm_normal_folio_pmd(vma, haddr, orig_pmd) : NULL;
>
> Err what? You just use vm_normal_folio_pmd() no?
>
> > +     if (!folio || !folio_test_anon(folio) ||
> > +         !PageAnonExclusive(&folio->page) || folio_test_mlocked(folio) ||
> > +         folio_contain_hwpoisoned_page(folio) ||
> > +         folio_ref_count(folio) != folio_expected_ref_count(folio) ||
> > +         !folio_trylock(folio)) {
>
> This is DISGUSTING :) I'm sorry. 7 conditions all in one continued line of
> varying types.
>
> You need to abstract the code in such a way as to avoid something like
> this, it's totally un-upstreamable and isn't what kernel code looks like.
>
> THP code is horrible enough let's not make it worse.
>
> > +             spin_unlock(ptl);
> > +             return false;
> > +     }
> > +     folio_get(folio);
> > +     spin_unlock(ptl);
> > +
> > +     flush_cache_range(vma, addr, end);
> > +     clear_contig_highpages(folio_page(folio, (addr - haddr) >> PAGE_SHIFT),
> > +                            addr, (end - addr) >> PAGE_SHIFT);
>
> Why is this function now exposed? Also _horribly_ open-coded shifted
> values.
>
> > +
> > +     /*
> > +      * Mark the PMD dirty, and soft-dirty, as a write through it would. If
> > +      * the PMD was split meanwhile, let the caller zap the range instead.
> > +      */
>
> Where are you marking it dirty? Also please don't mention soft-dirty it's a
> distraction and no need to point a niche thing out (begs question as to why
> you didn't mention anything else niche).
>
> I find the comment actually quite confusing here in general. Needs to be cleareer.
>
> > +     ptl = pmd_lock(vma->vm_mm, pmd);
> > +     orig_pmd = pmdp_get(pmd);
> > +     ret = pmd_present(orig_pmd) && pmd_trans_huge(orig_pmd) &&
> > +           pmd_folio(orig_pmd) == folio;
> > +     if (ret) {
> > +             touch_pmd(vma, haddr, pmd, true);
> > +             deferred_split_folio(folio, false);
> > +     }
>
> Again this code is just utterly horrible. Also you already checked for
> pmd_present(orig_pmd) above...
>
> THP code is horrible enough without just piling on more horrors.
>
> > +     spin_unlock(ptl);
> > +
> > +     folio_unlock(folio);
> > +     folio_put(folio);
> > +     return ret;
> > +}
> > +
> >  #ifndef pmd_move_must_withdraw
> >  static inline int pmd_move_must_withdraw(spinlock_t *new_pmd_ptl,
> >                                        spinlock_t *old_pmd_ptl,
> > diff --git a/mm/internal.h b/mm/internal.h
> > index 8942e57744a9..afa301cf8eaf 100644
> > --- a/mm/internal.h
> > +++ b/mm/internal.h
> > @@ -281,6 +281,9 @@ static inline int mmap_file(struct file *file, struct vm_area_struct *vma)
> >
> >  /* unmap_vmas is in mm/memory.c */
> >  void unmap_vmas(struct mmu_gather *tlb, struct unmap_desc *unmap);
> > +/* clear_contig_highpages is in mm/memory.c */
> > +void clear_contig_highpages(struct page *page, unsigned long addr,
> > +                         unsigned int nr_pages);
> >
> >  #ifdef CONFIG_MMU
> >
> > diff --git a/mm/madvise.c b/mm/madvise.c
> > index 66600e82605c..35114546008e 100644
> > --- a/mm/madvise.c
> > +++ b/mm/madvise.c
> > @@ -888,7 +888,7 @@ static void zap_range(struct madvise_behavior *madv_behavior,
> >  static long madvise_dontneed_single_vma(struct madvise_behavior *madv_behavior)
> >
> >  {
> > -     zap_range(madv_behavior, 0);
> > +     zap_range(madv_behavior, ZAP_FLAG_ZERO_PARTIAL_THP);
>
> No explanation? So somebody reading this 'just has to know'?
>
> >       return 0;
> >  }
> >
> > diff --git a/mm/memory.c b/mm/memory.c
> > index 82e1ec8e44e7..36a43b7ece84 100644
> > --- a/mm/memory.c
> > +++ b/mm/memory.c
> > @@ -2112,9 +2112,15 @@ static inline unsigned long zap_pmd_range(struct mmu_gather *tlb,
> >       do {
> >               next = pmd_addr_end(addr, end);
> >               if (pmd_is_huge(*pmd)) {
> > -                     if (next - addr != HPAGE_PMD_SIZE)
> > +                     if (next - addr != HPAGE_PMD_SIZE) {
> > +                             if (details &&
> > +                                 (details->zap_flags & ZAP_FLAG_ZERO_PARTIAL_THP) &&
> > +                                 zero_huge_pmd_range(vma, pmd, addr, next)) {
> > +                                     addr = next;
> > +                                     continue;
> > +                             }
>
> This is also UTTERLY disgusting lord above. And no comment, obviously...!
>
> Don't indent like this, don't put so many conditions on one line, _refactor
> code_ to accommodate your change sensibly, don't just add technical debt
> into open-coded bits.
>
>
> >                               __split_huge_pmd(vma, pmd, addr, false);
> > -                     else if (zap_huge_pmd(tlb, vma, pmd, addr)) {
> > +                     } else if (zap_huge_pmd(tlb, vma, pmd, addr)) {
> >                               addr = next;
> >                               continue;
> >                       }
> > @@ -7674,8 +7680,8 @@ static inline int process_huge_page(
> >       return 0;
> >  }
> >
> > -static void clear_contig_highpages(struct page *page, unsigned long addr,
> > -                                unsigned int nr_pages)
> > +void clear_contig_highpages(struct page *page, unsigned long addr,
> > +                         unsigned int nr_pages)
>
> Why are you exposing this?
>
> >  {
> >       unsigned int i, count;
> >       /*
> >
> > base-commit: 0bbbdf85abf48b019cb8dd7a6e87f0a8995fdcd2
> > --
> > 2.53.1-Meta
> >
>
> --
> Cheers, Lorenzo
>

This RFC will stay at the RFC-stage I'm afraid.

Thanks for the thorough review, I'll keep all your points in mind for
future patches.

Thanks,

Alex


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-02 18:04 ` Shakeel Butt
@ 2026-12-03 14:53   ` Alexandre Ghiti
  2026-12-03 15:08     ` Pedro Falcato
  2026-12-03 20:06     ` Shakeel Butt
  0 siblings, 2 replies; 16+ messages in thread
From: Alexandre Ghiti @ 2026-12-03 14:53 UTC (permalink / raw)
  To: Shakeel Butt
  Cc: Alexandre Ghiti, Andrew Morton, David Hildenbrand, Zi Yan,
	Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain,
	Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Pedro Falcato, Jann Horn, linux-mm,
	linux-kernel

Hi Shakeel,

On Wed, Dec 2, 2026 at 7:04 PM Shakeel Butt <shakeel.butt@linux.dev> wrote:
>
> >
> On Wed, Dec 02, 2026 at 11:28:10AM +0100, Alexandre Ghiti wrote:
> > MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> > the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> > stays allocated and charged as a whole, now partially mapped, until the
> > deferred split shrinker splits it under memory pressure. Until then the
> > process has lost the PMD mapping, and the TLB reach that comes with it, for
> > no memory benefit.
>
> Isn't the actual problem higher and unexpected memory usage? Application or the
> malloc implementations do madvise(MADV_DONTNEED) to release memory and expect at
> least decrease in RSS. Why not fix the cgroup memory usage as well by
> synchronously break the THP as well. See
> https://lore.kernel.org/all/20211120201230.920082-1-shakeelb@google.com/
>
>

The memcg charge is not the problem I'm facing (though it exists!). My
issue is that the allocator leaves many partially mapped THPs, even
when that memory may be reused soon after (which userspace can't
easily know), and the TLB benefit  goes away.

If the allocator stops purging hugepages that are only partly free,
the THPs stay intact (along with the TLB benefit) but RSS grows
noticeably, which is also unacceptable.

So what I'm looking for is a way for userspace to tell the kernel
which parts of a THP are free, so that the kernel can reclaim that
internal fragmentation when the memory is actually needed.

But since David says MADV_DONTNEED means zap, I'll try something else.

Thanks anyway for the link!

Alex


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-03 14:53   ` Alexandre Ghiti
@ 2026-12-03 15:08     ` Pedro Falcato
  2026-12-03 15:36       ` Alexandre Ghiti
  2026-12-03 20:06     ` Shakeel Butt
  1 sibling, 1 reply; 16+ messages in thread
From: Pedro Falcato @ 2026-12-03 15:08 UTC (permalink / raw)
  To: Alexandre Ghiti
  Cc: Shakeel Butt, Alexandre Ghiti, Andrew Morton, David Hildenbrand,
	Zi Yan, Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts,
	Dev Jain, Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Jann Horn, linux-mm, linux-kernel

On Thu, Dec 03, 2026 at 03:53:08PM +0100, Alexandre Ghiti wrote:
> Hi Shakeel,
> 
> On Wed, Dec 2, 2026 at 7:04 PM Shakeel Butt <shakeel.butt@linux.dev> wrote:
> >
> > >
> > On Wed, Dec 02, 2026 at 11:28:10AM +0100, Alexandre Ghiti wrote:
> > > MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> > > the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> > > stays allocated and charged as a whole, now partially mapped, until the
> > > deferred split shrinker splits it under memory pressure. Until then the
> > > process has lost the PMD mapping, and the TLB reach that comes with it, for
> > > no memory benefit.
> >
> > Isn't the actual problem higher and unexpected memory usage? Application or the
> > malloc implementations do madvise(MADV_DONTNEED) to release memory and expect at
> > least decrease in RSS. Why not fix the cgroup memory usage as well by
> > synchronously break the THP as well. See
> > https://lore.kernel.org/all/20211120201230.920082-1-shakeelb@google.com/
> >
> >
> 
> The memcg charge is not the problem I'm facing (though it exists!). My
> issue is that the allocator leaves many partially mapped THPs, even
> when that memory may be reused soon after (which userspace can't
> easily know), and the TLB benefit  goes away.

I would say doing a madvise() *at all* is silly; at least every time a range
is free.

> 
> If the allocator stops purging hugepages that are only partly free,
> the THPs stay intact (along with the TLB benefit) but RSS grows
> noticeably, which is also unacceptable.
> 
> So what I'm looking for is a way for userspace to tell the kernel
> which parts of a THP are free, so that the kernel can reclaim that
> internal fragmentation when the memory is actually needed.
> 
> But since David says MADV_DONTNEED means zap, I'll try something else.

MADV_NOHUGEPAGE? But that requires a VMA split, which sucks. I had the
idea (from Kiryl IIRC) on my post-LPC list that splitting off these
hints onto a separate tree (freeing us from VMA splitting) could be a
good idea.

Either way, you still pay the system call, which still sucks.

*Something something *transparent* huge pages*
(I didn't have time lately to work on this :/)


-- 
Pedro


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-03 15:08     ` Pedro Falcato
@ 2026-12-03 15:36       ` Alexandre Ghiti
  2026-12-03 20:07         ` Shakeel Butt
  0 siblings, 1 reply; 16+ messages in thread
From: Alexandre Ghiti @ 2026-12-03 15:36 UTC (permalink / raw)
  To: Pedro Falcato
  Cc: Shakeel Butt, Alexandre Ghiti, Andrew Morton, David Hildenbrand,
	Zi Yan, Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts,
	Dev Jain, Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Jann Horn, linux-mm, linux-kernel

Hi Pedro,

On Thu, Dec 3, 2026 at 4:08 PM Pedro Falcato <pfalcato@suse.de> wrote:
>
> >
> On Thu, Dec 03, 2026 at 03:53:08PM +0100, Alexandre Ghiti wrote:
> > Hi Shakeel,
> >
> > On Wed, Dec 2, 2026 at 7:04 PM Shakeel Butt <shakeel.butt@linux.dev> wrote:
> > >
> > > >
> > > On Wed, Dec 02, 2026 at 11:28:10AM +0100, Alexandre Ghiti wrote:
> > > > MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> > > > the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> > > > stays allocated and charged as a whole, now partially mapped, until the
> > > > deferred split shrinker splits it under memory pressure. Until then the
> > > > process has lost the PMD mapping, and the TLB reach that comes with it, for
> > > > no memory benefit.
> > >
> > > Isn't the actual problem higher and unexpected memory usage? Application or the
> > > malloc implementations do madvise(MADV_DONTNEED) to release memory and expect at
> > > least decrease in RSS. Why not fix the cgroup memory usage as well by
> > > synchronously break the THP as well. See
> > > https://lore.kernel.org/all/20211120201230.920082-1-shakeelb@google.com/
> > >
> > >
> >
> > The memcg charge is not the problem I'm facing (though it exists!). My
> > issue is that the allocator leaves many partially mapped THPs, even
> > when that memory may be reused soon after (which userspace can't
> > easily know), and the TLB benefit  goes away.
>
> I would say doing a madvise() *at all* is silly; at least every time a range
> is free.

It doesn't happen every time, it only happens after some threshold
that needs adjustment.

>
> >
> > If the allocator stops purging hugepages that are only partly free,
> > the THPs stay intact (along with the TLB benefit) but RSS grows
> > noticeably, which is also unacceptable.
> >
> > So what I'm looking for is a way for userspace to tell the kernel
> > which parts of a THP are free, so that the kernel can reclaim that
> > internal fragmentation when the memory is actually needed.
> >
> > But since David says MADV_DONTNEED means zap, I'll try something else.
>
> MADV_NOHUGEPAGE? But that requires a VMA split, which sucks. I had the
> idea (from Kiryl IIRC) on my post-LPC list that splitting off these
> hints onto a separate tree (freeing us from VMA splitting) could be a
> good idea.
>

I thought about using MADV_NOHUGEPAGE indeed (and all the other
madvise flags)...The hint tree sounds like a nice idea indeed.

> Either way, you still pay the system call, which still sucks.
>
> *Something something *transparent* huge pages*
> (I didn't have time lately to work on this :/)
>
>
> --
> Pedro

Thanks for your comments!

Alex


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-03 14:53   ` Alexandre Ghiti
  2026-12-03 15:08     ` Pedro Falcato
@ 2026-12-03 20:06     ` Shakeel Butt
  1 sibling, 0 replies; 16+ messages in thread
From: Shakeel Butt @ 2026-12-03 20:06 UTC (permalink / raw)
  To: Alexandre Ghiti
  Cc: Alexandre Ghiti, Andrew Morton, David Hildenbrand, Zi Yan,
	Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts, Dev Jain,
	Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Pedro Falcato, Jann Horn, linux-mm,
	linux-kernel

On Thu, Dec 03, 2026 at 03:53:08PM +0100, Alexandre Ghiti wrote:
> Hi Shakeel,
> 
> On Wed, Dec 2, 2026 at 7:04 PM Shakeel Butt <shakeel.butt@linux.dev> wrote:
> >
> > >
> > On Wed, Dec 02, 2026 at 11:28:10AM +0100, Alexandre Ghiti wrote:
> > > MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> > > the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> > > stays allocated and charged as a whole, now partially mapped, until the
> > > deferred split shrinker splits it under memory pressure. Until then the
> > > process has lost the PMD mapping, and the TLB reach that comes with it, for
> > > no memory benefit.
> >
> > Isn't the actual problem higher and unexpected memory usage? Application or the
> > malloc implementations do madvise(MADV_DONTNEED) to release memory and expect at
> > least decrease in RSS. Why not fix the cgroup memory usage as well by
> > synchronously break the THP as well. See
> > https://lore.kernel.org/all/20211120201230.920082-1-shakeelb@google.com/
> >
> >
> 
> The memcg charge is not the problem I'm facing (though it exists!). My
> issue is that the allocator leaves many partially mapped THPs, even
> when that memory may be reused soon after (which userspace can't
> easily know), and the TLB benefit  goes away.
> 
> If the allocator stops purging hugepages that are only partly free,
> the THPs stay intact (along with the TLB benefit) but RSS grows
> noticeably, which is also unacceptable.
> 
> So what I'm looking for is a way for userspace to tell the kernel
> which parts of a THP are free, so that the kernel can reclaim that
> internal fragmentation when the memory is actually needed.

Oh that is very important information and I think you should start with this
problem as the motivation.

> 
> But since David says MADV_DONTNEED means zap, I'll try something else.

Yes, this is not MADV_DONTNEED. I remember Rik proposed MADV_LAZYFREE for
reducing the tlb flushing. Maybe you can repurpose that idea but focus on how
userspace malloc implementations can share userspace freelist information with
the kernel. It does not have to be madvise() but I think the problem is worth
solving.


^ permalink raw reply	[flat|nested] 16+ messages in thread

* Re: [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED
  2026-12-03 15:36       ` Alexandre Ghiti
@ 2026-12-03 20:07         ` Shakeel Butt
  0 siblings, 0 replies; 16+ messages in thread
From: Shakeel Butt @ 2026-12-03 20:07 UTC (permalink / raw)
  To: Alexandre Ghiti
  Cc: Pedro Falcato, Alexandre Ghiti, Andrew Morton, David Hildenbrand,
	Zi Yan, Baolin Wang, Liam R. Howlett, Nico Pache, Ryan Roberts,
	Dev Jain, Barry Song, Lance Yang, Usama Arif, Kiryl Shutsemau,
	Vlastimil Babka, Mike Rapoport, Michal Hocko, Lorenzo Stoakes,
	Suren Baghdasaryan, Jann Horn, linux-mm, linux-kernel

On Thu, Dec 03, 2026 at 04:36:31PM +0100, Alexandre Ghiti wrote:
> Hi Pedro,
> 
> On Thu, Dec 3, 2026 at 4:08 PM Pedro Falcato <pfalcato@suse.de> wrote:
> >
> > >
> > On Thu, Dec 03, 2026 at 03:53:08PM +0100, Alexandre Ghiti wrote:
> > > Hi Shakeel,
> > >
> > > On Wed, Dec 2, 2026 at 7:04 PM Shakeel Butt <shakeel.butt@linux.dev> wrote:
> > > >
> > > > >
> > > > On Wed, Dec 02, 2026 at 11:28:10AM +0100, Alexandre Ghiti wrote:
> > > > > MADV_DONTNEED on a range that covers only part of a PMD-mapped THP splits
> > > > > the PMD and zaps the PTEs of the range. The THP itself is not freed: it
> > > > > stays allocated and charged as a whole, now partially mapped, until the
> > > > > deferred split shrinker splits it under memory pressure. Until then the
> > > > > process has lost the PMD mapping, and the TLB reach that comes with it, for
> > > > > no memory benefit.
> > > >
> > > > Isn't the actual problem higher and unexpected memory usage? Application or the
> > > > malloc implementations do madvise(MADV_DONTNEED) to release memory and expect at
> > > > least decrease in RSS. Why not fix the cgroup memory usage as well by
> > > > synchronously break the THP as well. See
> > > > https://lore.kernel.org/all/20211120201230.920082-1-shakeelb@google.com/
> > > >
> > > >
> > >
> > > The memcg charge is not the problem I'm facing (though it exists!). My
> > > issue is that the allocator leaves many partially mapped THPs, even
> > > when that memory may be reused soon after (which userspace can't
> > > easily know), and the TLB benefit  goes away.
> >
> > I would say doing a madvise() *at all* is silly; at least every time a range
> > is free.
> 
> It doesn't happen every time, it only happens after some threshold
> that needs adjustment.
> 
> >
> > >
> > > If the allocator stops purging hugepages that are only partly free,
> > > the THPs stay intact (along with the TLB benefit) but RSS grows
> > > noticeably, which is also unacceptable.
> > >
> > > So what I'm looking for is a way for userspace to tell the kernel
> > > which parts of a THP are free, so that the kernel can reclaim that
> > > internal fragmentation when the memory is actually needed.
> > >
> > > But since David says MADV_DONTNEED means zap, I'll try something else.
> >
> > MADV_NOHUGEPAGE? But that requires a VMA split, which sucks. I had the
> > idea (from Kiryl IIRC) on my post-LPC list that splitting off these
> > hints onto a separate tree (freeing us from VMA splitting) could be a
> > good idea.
> >
> 
> I thought about using MADV_NOHUGEPAGE indeed (and all the other
> madvise flags)...The hint tree sounds like a nice idea indeed.
> 

MADV_NOHUGEPAGE takes mmap lock in write mode and malloc implementations are not
keep to do operations that take mmap_lock in write mode.

> > Either way, you still pay the system call, which still sucks.
> >
> > *Something something *transparent* huge pages*
> > (I didn't have time lately to work on this :/)
> >
> >
> > --
> > Pedro
> 
> Thanks for your comments!
> 
> Alex


^ permalink raw reply	[flat|nested] 16+ messages in thread

end of thread, other threads:[~2026-12-03 20:08 UTC | newest]

Thread overview: 16+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-02 10:28 [RFC PATCH] mm: madvise: don't split a PMD on partial THP MADV_DONTNEED Alexandre Ghiti
2026-12-02 11:22 ` Lorenzo Stoakes (ARM)
2026-12-03 14:10   ` Alexandre Ghiti
2026-12-02 11:22 ` David Hildenbrand (Arm)
2026-12-02 14:26   ` Alexandre Ghiti
2026-12-03 12:32     ` David Hildenbrand (Arm)
2026-12-02 16:37 ` Zi Yan
2026-12-02 17:39   ` Alexandre Ghiti
2026-12-02 20:28   ` David Hildenbrand (Arm)
2026-12-02 18:04 ` Shakeel Butt
2026-12-03 14:53   ` Alexandre Ghiti
2026-12-03 15:08     ` Pedro Falcato
2026-12-03 15:36       ` Alexandre Ghiti
2026-12-03 20:07         ` Shakeel Butt
2026-12-03 20:06     ` Shakeel Butt
2026-12-03 10:28 ` sashiko-bot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox