Skip to contentSkip to conversation

mm/hugetlb: various fixes

PATCH Applied David Hildenbrand (Arm) 6 participants 57 messages Nov 16 – Nov 23

Subsystems (11)
lore
Share & tools
lore

David Hildenbrand (Arm)

author maintainer
#0 lore raw

v2 cover mm/hugetlb: various fixes

Hi,

v2 of the hugetlb fixes. There will be more at some point ... let's drag these over the finishing line.

---
Changes in v2:
- Rebased on top of akpm/mm-stable
- Applied tags
- "mm/hugetlb: compare against persistent count when freeing lowmem folios" and "mm/hugetlb: account temporary folios separately"
- Use const struct hstate pointers
- "mm/hugetlb: fix reservation leak on min_size= mounts"
- Clarify that this is only an accounting error in the description
- "mm/hugetlb: account restored reservations before freeing folios"
- Drop RFC
- Don't allocate surplus pages for restored reservations
- Free unused surplus pages directly instead of via free_huge_folio()
- Document available_huge_pages() and assert that hugetlb_lock is held
- "mm/hugetlb: delay anon folio rmap removal until after the TLB flush"
- Drop RFC
- Flush delayed rmaps in hugetlb_unmap_range() (due to rebasing)
- Move hugetlb_folio_restore_rsv_on_unmap() declaration to mm/internal.h
- Link to v1: https://patch.msgid.link/[email protected]

---
Chris Mason (3):
hugetlbfs: do not grow a sealed file in mmap() mm/hugetlb: keep surplus folios that are reserved mm/hugetlb: fix reservation leak on min_size= mounts

David Hildenbrand (Arm) (10):
hugetlbfs: fix integer overflow in fallocate()
mm/hugetlb: compare against persistent count when freeing lowmem folios mm/hugetlb: preserve reservations when shrinking on HIGHMEM mm/hugetlb: account temporary folios separately
mm/hugetlb: fix mremap() racing with page migration mm/hugetlb: serialize page-cache allocations with truncation mm/memfd: recheck the page cache before allocating a hugetlb folio mm/hugetlb: count again if the reserve map shrank mm/hugetlb: account restored reservations before freeing folios mm/hugetlb: delay anon folio rmap removal until after the TLB flush

Josef Bacik (2):
mm/hugetlb: keep surplus folios when the pool shrinks
hugetlbfs: fix unmapping folios from private VMAs

 Documentation/mm/hugetlbfs_reserv.rst |  30 +--
 arch/s390/include/asm/tlb.h           |   5 +-
 fs/hugetlbfs/inode.c                  |  36 ++-
 include/asm-generic/tlb.h             |   5 +-
 include/linux/hugetlb.h               |  17 ++
 mm/hugetlb.c                          | 424 ++++++++++++++++++++++------------
 mm/hugetlb_internal.h                 |  24 ++
 mm/hugetlb_sysfs.c                    |   2 +-
 mm/internal.h                         |   9 +
 mm/memfd.c                            |  17 ++
 mm/mmu_gather.c                       |  16 +-
 11 files changed, 404 insertions(+), 181 deletions(-)

---
base-commit: fa4ad798f6f681031775266044ba1b0cf3c670bd
change-id: 20261027-fixes_hugetlb-2c4f02ff6304

Best regards,

Signature · 1 line
David Hildenbrand (Arm) <[email protected]>
author maintainer
#1 lore raw

PATCH v2 1/15 hugetlbfs: fix integer overflow in fallocate()

hugetlbfs_fallocate() rounds the range end up by adding hpage_size - 1 to offset + len. vfs_fallocate()'s existing overflow check only makes sure that offset + len does not overflow.

Once we overflow for valid endpoints near LLONG_MAX, we can get a negative temporary result that is then converted to a very large huge page index.

A one-byte allocation ending at LLONG_MAX can therefore consume all available huge pages. Pages added beyond LLONG_MAX are skipped during inode eviction, leaking them and triggering the BUG_ON() in clear_inode().

To fix it, calculate the end index in a simpler way that cannot overflow. This also fixes the signed overflow reported by luojiajun in 2019.

Backporting notes: without commit a08c7193e4f18 ("mm/filemap: remove hugetlb special casing in filemap.c"), remove_inode_hugepages() must include the final huge page during truncate and eviction.

---
 fs/hugetlbfs/inode.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
fs/hugetlbfs/inode.c +5 -3
index 02e0a65d596d8..9f502a456cdb0 100644
@@ -722,11 +722,13 @@ static long hugetlbfs_fallocate(struct file *file, int mode, loff_t offset,
 
 	/*
 	 * Default preallocate case.
-	 * For this range, start is rounded down and end is rounded up
-	 * as well as being converted to page offsets.
+	 * vfs_fallocate() guarantees that offset + len is positive and does
+	 * not overflow. Avoid overflows when calculating the end huge page
+	 * index: set it to one past the index of the huge page containing the
+	 * last byte.
 	 */
 	start = offset >> hpage_shift;
-	end = (offset + len + hpage_size - 1) >> hpage_shift;
+	end = ((offset + len - 1) >> hpage_shift) + 1;
 
 	inode_lock(inode);
 
Signature · 1 line
2.56.1
#2 lore raw

Re: [PATCH v2 01/15] hugetlbfs: fix integer overflow in fallocate()

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

hugetlbfs_fallocate() rounds the range end up by adding hpage_size - 1 to offset + len. vfs_fallocate()'s existing overflow check only makes sure that offset + len does not overflow.

Once we overflow for valid endpoints near LLONG_MAX, we can get a negative temporary result that is then converted to a very large huge page index.

A one-byte allocation ending at LLONG_MAX can therefore consume all available huge pages. Pages added beyond LLONG_MAX are skipped during inode eviction, leaking them and triggering the BUG_ON() in clear_inode().

To fix it, calculate the end index in a simpler way that cannot overflow. This also fixes the signed overflow reported by luojiajun in 2019.

Quoted 6 lines

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
maintainer tree notice Applied
#3 lore raw

[merged mm-hotfixes-stable] hugetlbfs-fix-integer-overflow-in-fallocate.patch removed from -mm tree

In reply to David Hildenbrand (Arm)
The quilt patch titled Subject: hugetlbfs: fix integer overflow in fallocate() has been removed from the -mm tree. Its filename was hugetlbfs-fix-integer-overflow-in-fallocate.patch

The quilt patch titled
Subject: hugetlbfs: fix integer overflow in fallocate()
has been removed from the -mm tree. Its filename was
hugetlbfs-fix-integer-overflow-in-fallocate.patch

This patch was dropped because it was merged into the mm-hotfixes-stable branch of git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

------------------------------------------------------
From: "David Hildenbrand (Arm)" <[email protected]>
Subject: hugetlbfs: fix integer overflow in fallocate()
Date: Mon, 16 Nov 2026 19:29:22 +0100

hugetlbfs_fallocate() rounds the range end up by adding hpage_size - 1 to offset + len. vfs_fallocate()'s existing overflow check only makes sure that offset + len does not overflow.

Once we overflow for valid endpoints near LLONG_MAX, we can get a negative temporary result that is then converted to a very large huge page index.

A one-byte allocation ending at LLONG_MAX can therefore consume all available huge pages. Pages added beyond LLONG_MAX are skipped during inode eviction, leaking them and triggering the BUG_ON() in clear_inode().

To fix it, calculate the end index in a simpler way that cannot overflow. This also fixes the signed overflow reported by luojiajun in 2019.

Backporting notes: without commit a08c7193e4f18 ("mm/filemap: remove hugetlb special casing in filemap.c"), remove_inode_hugepages() must include the final huge page during truncate and eviction.

Fixes 70c3547e36f5 ("hugetlbfs: add hugetlbfs_fallocate()")
Cc Naoya Horiguchi <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Andy Whitcroft <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Vivek Kasireddy <[email protected]>
Cc Dave Airlie <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Peter Xu <[email protected]>
Cc Breno Leitao <[email protected]>
Cc Will Deacon <[email protected]>
Cc Aneesh Kumar K.V <[email protected]>
Cc Nicholas Piggin <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Vasily Gorbik <[email protected]>
Cc Alexander Gordeev <[email protected]>
Cc Christian Borntraeger <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Gerd Hoffmann <[email protected]>
Cc Chris Mason <[email protected]>
Cc Daehyeon Ko <[email protected]>
Cc Oscar Salvador <[email protected]>
 fs/hugetlbfs/inode.c |    8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
fs/hugetlbfs/inode.c renamed from fs/hugetlbfs/inode.c~hugetlbfs-fix-integer-overflow-in-fallocate +5 -3
@@ -722,11 +722,13 @@ static long hugetlbfs_fallocate(struct f
 
 	/*
 	 * Default preallocate case.
-	 * For this range, start is rounded down and end is rounded up
-	 * as well as being converted to page offsets.
+	 * vfs_fallocate() guarantees that offset + len is positive and does
+	 * not overflow. Avoid overflows when calculating the end huge page
+	 * index: set it to one past the index of the huge page containing the
+	 * last byte.
 	 */
 	start = offset >> hpage_shift;
-	end = (offset + len + hpage_size - 1) >> hpage_shift;
+	end = ((offset + len - 1) >> hpage_shift) + 1;
 
 	inode_lock(inode);
 

_

Patches currently in -mm which might be from [email protected] are

mm-mprotect-dont-skip-uffd-marker-install-when-racing-with-pte-table-reclaim.patch mm-khugepaged-free-unused-page-table-when-setting-a-huge-pmd-fails.patch mm-userfaultfd-prevent-poison-marker-loss.patch mm-hugetlb-compare-against-persistent-count-when-freeing-lowmem-folios.patch mm-hugetlb-preserve-reservations-when-shrinking-on-highmem.patch mm-hugetlb-account-temporary-folios-separately.patch mm-hugetlb-account-temporary-folios-separately-fix.patch mm-hugetlb-serialize-page-cache-allocations-with-truncation.patch mm-memfd-recheck-the-page-cache-before-allocating-a-hugetlb-folio.patch mm-hugetlb-count-again-if-the-reserve-map-shrank.patch mm-hugetlb-account-restored-reservations-before-freeing-folios.patch mm-hugetlb-delay-anon-folio-rmap-removal-until-after-the-tlb-flush.patch

author maintainer
#4 lore raw

PATCH v2 2/15 mm/hugetlb: compare against persistent count when freeing lowmem folios

In reply to David Hildenbrand (Arm)

try_to_free_low() gets a target number of persistent folios, but compares it with "nr_huge_pages", which includes surplus folios. As a result, it can free lowmem folios below that target.

For example, with two persistent folios and one surplus folio, a target of two can still end up freeing one persistent folio.

Compare against persistent_huge_pages() instead. Convert the macro to a helper function and place it before try_to_free_low().

Fixes 7893d1d505d5 ("hugetlb: Try to grow hugetlb pool for MAP_PRIVATE mappings")
---
 mm/hugetlb.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
mm/hugetlb.c +6 -2
index 630c96cd1e880..349d45b932d9b 100644
@@ -1339,6 +1339,11 @@ static unsigned long available_huge_pages(struct hstate *h)
 	return h->free_huge_pages - h->resv_huge_pages;
 }
 
+static unsigned long persistent_huge_pages(const struct hstate *h)
+{
+	return h->nr_huge_pages - h->surplus_huge_pages;
+}
+
 static struct folio *dequeue_hugetlb_folio(struct hstate *h, gfp_t gfp_mask,
 					   struct mempolicy_interpreted *mpoli)
 {
@@ -3723,7 +3728,7 @@ static void try_to_free_low(struct hstate *h, unsigned long count,
 		struct folio *folio, *next;
 		struct list_head *freel = &h->hugepage_freelists[i];
 		list_for_each_entry_safe(folio, next, freel, lru) {
-			if (count >= h->nr_huge_pages)
+			if (count >= persistent_huge_pages(h))
 				goto out;
 			if (folio_test_highmem(folio))
 				continue;
@@ -3777,7 +3782,6 @@ static int adjust_pool_surplus(struct hstate *h, nodemask_t *nodes_allowed,
 	return 1;
 }
 
-#define persistent_huge_pages(h) (h->nr_huge_pages - h->surplus_huge_pages)
 static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
 			      nodemask_t *nodes_allowed)
 {
Signature · 1 line
2.56.1
#5 lore raw

Re: [PATCH v2 02/15] mm/hugetlb: compare against persistent count when freeing lowmem folios

Sashiko has reviewed this patch and found no issues.
Quoted 7 lines

try_to_free_low() gets a target number of persistent folios, but compares it with "nr_huge_pages", which includes surplus folios. As a result, it can free lowmem folios below that target.

For example, with two persistent folios and one surplus folio, a target of two can still end up freeing one persistent folio.

Quoted 7 lines

Compare against persistent_huge_pages() instead. Convert the macro to a helper function and place it before try_to_free_low().

Fixes 7893d1d505d5 ("hugetlb: Try to grow hugetlb pool for MAP_PRIVATE mappings")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
reviewer Reviewed-by on v2 2/15
#6 lore raw

Re: [PATCH v2 02/15] mm/hugetlb: compare against persistent count when freeing lowmem folios

In reply to David Hildenbrand (Arm)
Quoted 12 lines · David Hildenbrand (Arm)

try_to_free_low() gets a target number of persistent folios, but compares it with "nr_huge_pages", which includes surplus folios. As a result, it can free lowmem folios below that target.

For example, with two persistent folios and one surplus folio, a target
of two can still end up freeing one persistent folio.

Compare against persistent_huge_pages() instead. Convert the macro to a
helper function and place it before try_to_free_low().

Quoted 5 lines
Fixes 7893d1d505d5 ("hugetlb: Try to grow hugetlb pool for

MAP_PRIVATE mappings")

Signature · 1 line
All Rights Reversed.
Acked-by on v2 2/15
#7 lore raw

Re: [PATCH v2 02/15] mm/hugetlb: compare against persistent count when freeing lowmem folios

In reply to David Hildenbrand (Arm)
Quoted 7 lines · David Hildenbrand (Arm)

try_to_free_low() gets a target number of persistent folios, but compares it with "nr_huge_pages", which includes surplus folios. As a result, it can free lowmem folios below that target.

For example, with two persistent folios and one surplus folio, a target of two can still end up freeing one persistent folio.

Quoted 7 lines

Compare against persistent_huge_pages() instead. Convert the macro to a helper function and place it before try_to_free_low().

Fixes 7893d1d505d5 ("hugetlb: Try to grow hugetlb pool for MAP_PRIVATE mappings")
Signature · 2 lines
Oscar Salvador
SUSE Labs
author maintainer
#8 lore raw

PATCH v2 3/15 mm/hugetlb: preserve reservations when shrinking on HIGHMEM

In reply to David Hildenbrand (Arm)

try_to_free_low() drops the hugetlb_lock while freeing lowmem folios. set_max_huge_pages() then resumes freeing folios using the min_count computed before that unlock. Reservations created in between can consequently lose their backing.

Collect lowmem folios on the caller's existing page_list instead. Keep the hugetlb_lock held through both selection passes, and free the combined list at the caller's existing unlock point.

Likely not stable-worthy.

Fixes 1121828a0c21 ("hugetlb: call update_and_free_page without hugetlb_lock")
---
 mm/hugetlb.c | 20 ++++++--------------
 1 file changed, 6 insertions(+), 14 deletions(-)
mm/hugetlb.c +6 -14
index 349d45b932d9b..0b071bef226ac 100644
@@ -3712,39 +3712,31 @@ static void __init report_hugepages(void)
 
 #ifdef CONFIG_HIGHMEM
 static void try_to_free_low(struct hstate *h, unsigned long count,
-						nodemask_t *nodes_allowed)
+		nodemask_t *nodes_allowed, struct list_head *page_list)
 {
 	int i;
-	LIST_HEAD(page_list);
 
 	lockdep_assert_held(&hugetlb_lock);
 	if (hstate_is_gigantic(h))
 		return;
 
-	/*
-	 * Collect pages to be freed on a list, and free after dropping lock
-	 */
+	/* Collect lowmem pages to free after dropping the lock. */
 	for_each_node_mask(i, *nodes_allowed) {
 		struct folio *folio, *next;
 		struct list_head *freel = &h->hugepage_freelists[i];
 		list_for_each_entry_safe(folio, next, freel, lru) {
 			if (count >= persistent_huge_pages(h))
-				goto out;
+				return;
 			if (folio_test_highmem(folio))
 				continue;
 			remove_hugetlb_folio(h, folio, false);
-			list_add(&folio->lru, &page_list);
+			list_add(&folio->lru, page_list);
 		}
 	}
-
-out:
-	spin_unlock_irq(&hugetlb_lock);
-	update_and_free_pages_bulk(h, &page_list);
-	spin_lock_irq(&hugetlb_lock);
 }
 #else
 static inline void try_to_free_low(struct hstate *h, unsigned long count,
-						nodemask_t *nodes_allowed)
+		nodemask_t *nodes_allowed, struct list_head *page_list)
 {
 }
 #endif
@@ -3939,7 +3931,7 @@ static int set_max_huge_pages(struct hstate *h, unsigned long count, int nid,
 	}
 	min_count = h->resv_huge_pages + persistent_huge_pages(h) - persistent_free_count;
 	min_count = max(count, min_count);
-	try_to_free_low(h, min_count, nodes_allowed);
+	try_to_free_low(h, min_count, nodes_allowed, &page_list);
 
 	/*
 	 * Collect pages to be removed on list without dropping lock
Signature · 1 line
2.56.1
#9 lore raw

Re: [PATCH v2 03/15] mm/hugetlb: preserve reservations when shrinking on HIGHMEM

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

try_to_free_low() drops the hugetlb_lock while freeing lowmem folios. set_max_huge_pages() then resumes freeing folios using the min_count computed before that unlock. Reservations created in between can consequently lose their backing.

Collect lowmem folios on the caller's existing page_list instead. Keep the hugetlb_lock held through both selection passes, and free the combined list at the caller's existing unlock point.

Quoted 5 lines

Likely not stable-worthy.

Fixes 1121828a0c21 ("hugetlb: call update_and_free_page without hugetlb_lock")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
reviewer Reviewed-by on v2 3/15
#10 lore raw

Re: [PATCH v2 03/15] mm/hugetlb: preserve reservations when shrinking on HIGHMEM

In reply to David Hildenbrand (Arm)
Quoted 12 lines · David Hildenbrand (Arm)

try_to_free_low() drops the hugetlb_lock while freeing lowmem folios. set_max_huge_pages() then resumes freeing folios using the min_count computed before that unlock. Reservations created in between
can consequently lose their backing.

Collect lowmem folios on the caller's existing page_list instead. Keep
the hugetlb_lock held through both selection passes, and free the combined
list at the caller's existing unlock point.

Quoted 6 lines

Likely not stable-worthy.

Fixes 1121828a0c21 ("hugetlb: call update_and_free_page without

hugetlb_lock")

Signature · 1 line
All Rights Reversed.
Acked-by on v2 3/15
#11 lore raw

Re: [PATCH v2 03/15] mm/hugetlb: preserve reservations when shrinking on HIGHMEM

In reply to David Hildenbrand (Arm)
Quoted 9 lines · David Hildenbrand (Arm)

try_to_free_low() drops the hugetlb_lock while freeing lowmem folios. set_max_huge_pages() then resumes freeing folios using the min_count computed before that unlock. Reservations created in between can consequently lose their backing.

Collect lowmem folios on the caller's existing page_list instead. Keep the hugetlb_lock held through both selection passes, and free the combined list at the caller's existing unlock point.

Quoted 5 lines

Likely not stable-worthy.

Fixes 1121828a0c21 ("hugetlb: call update_and_free_page without hugetlb_lock")
Signature · 2 lines
Oscar Salvador
SUSE Labs
author maintainer
#12 lore raw

PATCH v2 4/15 mm/hugetlb: account temporary folios separately

In reply to David Hildenbrand (Arm)

Hugetlb migration might have to allocate a temporary folio through alloc_migrate_hugetlb_folio(). Such folios are currently accounted in "nr_huge_pages" but not in "surplus_huge_pages". persistent_huge_pages() can mistake them as persistent huge pages, as it merely calculates the difference.

If set_max_huge_pages() shrinks the pool at the wrong time, it will turn hugetlb folios into surplus folios until persistent_huge_pages() returns the desired number.

After the migration (successful or unsuccessful) either the new (temporary) folio or the old folio gets freed: this will reduce "nr_huge_pages" but not "surplus_huge_pages", to undo what was done when allocating a temporary folio.

This can result in having more surplus folios than actually allocated folios:

HugePages_Total: 0
HugePages_Surp: 1

From then on persistent_huge_pages() returns garbage.

To fix it, add internal temporary counters and subtract them when calculating persistent pool sizes. Update persistent_huge_pages() and add persistent_huge_pages_node() to make the code easier to read.

Count migration targets and rejected surplus allocations as temporary. Transfer the per-node temporary count along with the temporary flag on migration, such that folio freeing will always do the right thing.

Take care of calling account_new_hugetlb_folio() only after setting the folios to be temporary.

For now, keep temporary folios in nr_huge_pages, so HugePages_Total and Hugetlb continue to include them and overcommit accounting remains unchanged. The new temporary counters are internal for now and are not exported to userspace.

Fixes ab5ac90aecf5 ("mm, hugetlb: do not rely on overcommit limit during migration")
---
 include/linux/hugetlb.h |  3 +++
 mm/hugetlb.c            | 65 +++++++++++++++++++++++++++++--------------------
 2 files changed, 42 insertions(+), 26 deletions(-)
include/linux/hugetlb.h +3 -0
index 58f755e70e966..80ae65c7849b9 100644
@@ -698,6 +698,8 @@ struct hstate {
 	unsigned long free_huge_pages;
 	unsigned long resv_huge_pages;
 	unsigned long surplus_huge_pages;
+	/* Included in nr_huge_pages; not exported separately to userspace. */
+	unsigned long temporary_huge_pages;
 	unsigned long nr_overcommit_huge_pages;
 	struct list_head hugepage_activelist;
 	struct list_head hugepage_freelists[MAX_NUMNODES];
@@ -705,6 +707,7 @@ struct hstate {
 	unsigned int nr_huge_pages_node[MAX_NUMNODES];
 	unsigned int free_huge_pages_node[MAX_NUMNODES];
 	unsigned int surplus_huge_pages_node[MAX_NUMNODES];
+	unsigned int temporary_huge_pages_node[MAX_NUMNODES];
 	char name[HSTATE_NAME_LEN];
 };
 
mm/hugetlb.c +39 -26

148 lines not on this page · raw message

Signature · 1 line
2.56.1
#13 lore raw

Re: [PATCH v2 04/15] mm/hugetlb: account temporary folios separately

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

Hugetlb migration might have to allocate a temporary folio through alloc_migrate_hugetlb_folio(). Such folios are currently accounted in "nr_huge_pages" but not in "surplus_huge_pages". persistent_huge_pages() can mistake them as persistent huge pages, as it merely calculates the difference.

If set_max_huge_pages() shrinks the pool at the wrong time, it will turn hugetlb folios into surplus folios until persistent_huge_pages() returns the desired number.

After the migration (successful or unsuccessful) either the new (temporary) folio or the old folio gets freed: this will reduce "nr_huge_pages" but not "surplus_huge_pages", to undo what was done when allocating a temporary folio.

Quoted 6 lines
[ ... ]
Fixes ab5ac90aecf5 ("mm, hugetlb: do not rely on overcommit limit during migration")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
Tested-by Reviewed-by on v2 4/15
#14 lore raw

Re: [PATCH v2 04/15] mm/hugetlb: account temporary folios separately

In reply to David Hildenbrand (Arm)
Quoted 39 lines · David Hildenbrand (Arm)

Hugetlb migration might have to allocate a temporary folio through alloc_migrate_hugetlb_folio(). Such folios are currently accounted in "nr_huge_pages" but not in "surplus_huge_pages". persistent_huge_pages() can mistake them as persistent huge pages, as it merely calculates the difference.

If set_max_huge_pages() shrinks the pool at the wrong time, it will turn hugetlb folios into surplus folios until persistent_huge_pages() returns the desired number.

After the migration (successful or unsuccessful) either the new (temporary) folio or the old folio gets freed: this will reduce "nr_huge_pages" but not "surplus_huge_pages", to undo what was done when allocating a temporary folio.

This can result in having more surplus folios than actually allocated folios:

HugePages_Total: 0
HugePages_Surp: 1

From then on persistent_huge_pages() returns garbage.

To fix it, add internal temporary counters and subtract them when calculating persistent pool sizes. Update persistent_huge_pages() and add persistent_huge_pages_node() to make the code easier to read.

Count migration targets and rejected surplus allocations as temporary. Transfer the per-node temporary count along with the temporary flag on migration, such that folio freeing will always do the right thing.

Take care of calling account_new_hugetlb_folio() only after setting the folios to be temporary.

For now, keep temporary folios in nr_huge_pages, so HugePages_Total and Hugetlb continue to include them and overcommit accounting remains unchanged. The new temporary counters are internal for now and are not exported to userspace.

Quoted 5 lines
Fixes ab5ac90aecf5 ("mm, hugetlb: do not rely on overcommit limit during migration")

My only commentary on this set is that "Surplus" is a horribly confusing name :|

I was able to replicate Patch 4 and 5 bugs together pretty trivially with migrations, leaving the surplus counters out of sync.

Nice to see these accounting bugs finally fixed, we've seen them in production for far too long without an obvious resolution.

Signature · 1 line
~Gregory
Acked-by on v2 4/15
#15 lore raw

Re: [PATCH v2 04/15] mm/hugetlb: account temporary folios separately

In reply to David Hildenbrand (Arm)
Quoted 39 lines · David Hildenbrand (Arm)

Hugetlb migration might have to allocate a temporary folio through alloc_migrate_hugetlb_folio(). Such folios are currently accounted in "nr_huge_pages" but not in "surplus_huge_pages". persistent_huge_pages() can mistake them as persistent huge pages, as it merely calculates the difference.

If set_max_huge_pages() shrinks the pool at the wrong time, it will turn hugetlb folios into surplus folios until persistent_huge_pages() returns the desired number.

After the migration (successful or unsuccessful) either the new (temporary) folio or the old folio gets freed: this will reduce "nr_huge_pages" but not "surplus_huge_pages", to undo what was done when allocating a temporary folio.

This can result in having more surplus folios than actually allocated folios:

HugePages_Total: 0
HugePages_Surp: 1

From then on persistent_huge_pages() returns garbage.

To fix it, add internal temporary counters and subtract them when calculating persistent pool sizes. Update persistent_huge_pages() and add persistent_huge_pages_node() to make the code easier to read.

Count migration targets and rejected surplus allocations as temporary. Transfer the per-node temporary count along with the temporary flag on migration, such that folio freeing will always do the right thing.

Take care of calling account_new_hugetlb_folio() only after setting the folios to be temporary.

For now, keep temporary folios in nr_huge_pages, so HugePages_Total and Hugetlb continue to include them and overcommit accounting remains unchanged. The new temporary counters are internal for now and are not exported to userspace.

Quoted 5 lines
Fixes ab5ac90aecf5 ("mm, hugetlb: do not rely on overcommit limit during migration")
Signature · 2 lines
Oscar Salvador
SUSE Labs
author maintainer
#16 lore raw

Re: [PATCH v2 04/15] mm/hugetlb: account temporary folios separately

In reply to David Hildenbrand (Arm)
Quoted 39 lines · David Hildenbrand (Arm)

Hugetlb migration might have to allocate a temporary folio through alloc_migrate_hugetlb_folio(). Such folios are currently accounted in "nr_huge_pages" but not in "surplus_huge_pages". persistent_huge_pages() can mistake them as persistent huge pages, as it merely calculates the difference.

If set_max_huge_pages() shrinks the pool at the wrong time, it will turn hugetlb folios into surplus folios until persistent_huge_pages() returns the desired number.

After the migration (successful or unsuccessful) either the new (temporary) folio or the old folio gets freed: this will reduce "nr_huge_pages" but not "surplus_huge_pages", to undo what was done when allocating a temporary folio.

This can result in having more surplus folios than actually allocated folios:

HugePages_Total: 0
HugePages_Surp: 1

From then on persistent_huge_pages() returns garbage.

To fix it, add internal temporary counters and subtract them when calculating persistent pool sizes. Update persistent_huge_pages() and add persistent_huge_pages_node() to make the code easier to read.

Count migration targets and rejected surplus allocations as temporary. Transfer the per-node temporary count along with the temporary flag on migration, such that folio freeing will always do the right thing.

Take care of calling account_new_hugetlb_folio() only after setting the folios to be temporary.

For now, keep temporary folios in nr_huge_pages, so HugePages_Total and Hugetlb continue to include them and overcommit accounting remains unchanged. The new temporary counters are internal for now and are not exported to userspace.

Quoted 6 lines
Fixes ab5ac90aecf5 ("mm, hugetlb: do not rely on overcommit limit during migration")

---

In combination with

mm/hugetlb: preserve persistent flags when returning folios to the pool

This results in an issue during boot.

I think the following is required:

mm/hugetlb.c +1 -1
index bfc88d42ef0d..aa6ad8d93266 100644
@@ -1804,8 +1804,8 @@ void free_huge_folio(struct folio *folio)
                h->resv_huge_pages++;
 
        if (folio_test_hugetlb_temporary(folio)) {
-               folio_clear_hugetlb_temporary(folio);
                remove_hugetlb_folio(h, folio, false);
+               folio_clear_hugetlb_temporary(folio);
                spin_unlock_irqrestore(&hugetlb_lock, flags);
                update_and_free_hugetlb_folio(h, folio, true);
        } else if (h->surplus_huge_pages_node[nid] &&

I'll test real quick whether that resolves CI issues ...

Signature · 3 lines
Cheers,

David
author maintainer
#17 lore raw

Re: [PATCH v2 04/15] mm/hugetlb: account temporary folios separately

Quoted 70 lines · David Hildenbrand (Arm)
Quoted 39 lines · David Hildenbrand (Arm)

Hugetlb migration might have to allocate a temporary folio through alloc_migrate_hugetlb_folio(). Such folios are currently accounted in "nr_huge_pages" but not in "surplus_huge_pages". persistent_huge_pages() can mistake them as persistent huge pages, as it merely calculates the difference.

If set_max_huge_pages() shrinks the pool at the wrong time, it will turn hugetlb folios into surplus folios until persistent_huge_pages() returns the desired number.

After the migration (successful or unsuccessful) either the new (temporary) folio or the old folio gets freed: this will reduce "nr_huge_pages" but not "surplus_huge_pages", to undo what was done when allocating a temporary folio.

This can result in having more surplus folios than actually allocated folios:

HugePages_Total: 0
HugePages_Surp: 1

From then on persistent_huge_pages() returns garbage.

To fix it, add internal temporary counters and subtract them when calculating persistent pool sizes. Update persistent_huge_pages() and add persistent_huge_pages_node() to make the code easier to read.

Count migration targets and rejected surplus allocations as temporary. Transfer the per-node temporary count along with the temporary flag on migration, such that folio freeing will always do the right thing.

Take care of calling account_new_hugetlb_folio() only after setting the folios to be temporary.

For now, keep temporary folios in nr_huge_pages, so HugePages_Total and Hugetlb continue to include them and overcommit accounting remains unchanged. The new temporary counters are internal for now and are not exported to userspace.

Quoted 6 lines
Fixes ab5ac90aecf5 ("mm, hugetlb: do not rely on overcommit limit during migration")

---

In combination with

mm/hugetlb: preserve persistent flags when returning folios to the pool

This results in an issue during boot.

I think the following is required:

mm/hugetlb.c +1 -1
index bfc88d42ef0d..aa6ad8d93266 100644
@@ -1804,8 +1804,8 @@ void free_huge_folio(struct folio *folio)
                h->resv_huge_pages++;
 
        if (folio_test_hugetlb_temporary(folio)) {
-               folio_clear_hugetlb_temporary(folio);
                remove_hugetlb_folio(h, folio, false);
+               folio_clear_hugetlb_temporary(folio);
                spin_unlock_irqrestore(&hugetlb_lock, flags);
                update_and_free_hugetlb_folio(h, folio, true);
        } else if (h->surplus_huge_pages_node[nid] &&
Quoted 2 lines

I'll test real quick whether that resolves CI issues ...

Yes, that makes it work. @Andrew, can you fix that up?

Signature · 3 lines
Cheers,

David
maintainer
#18 lore raw

Re: [PATCH v2 04/15] mm/hugetlb: account temporary folios separately

Quoted 23 lines · On Sun, 22 Nov 2026 19:44:35 +0100 "David Hildenbrand (Arm)"…
Quoted 23 lines

In combination with

mm/hugetlb: preserve persistent flags when returning folios to the pool

This results in an issue during boot.

I think the following is required:

mm/hugetlb.c +1 -1
index bfc88d42ef0d..aa6ad8d93266 100644
@@ -1804,8 +1804,8 @@ void free_huge_folio(struct folio *folio)
                h->resv_huge_pages++;
 
        if (folio_test_hugetlb_temporary(folio)) {
-               folio_clear_hugetlb_temporary(folio);
                remove_hugetlb_folio(h, folio, false);
+               folio_clear_hugetlb_temporary(folio);
                spin_unlock_irqrestore(&hugetlb_lock, flags);
                update_and_free_hugetlb_folio(h, folio, true);
        } else if (h->surplus_huge_pages_node[nid] &&
Quoted 4 lines
Quoted 2 lines

I'll test real quick whether that resolves CI issues ...

Yes, that makes it work. @Andrew, can you fix that up?

np.

From: "David Hildenbrand (Arm)" <[email protected]>
Subject: mm-hugetlb-account-temporary-folios-separately-fix
Date: Sun, 22 Nov 2026 19:21:43 +0100

In combination with

mm/hugetlb: preserve persistent flags when returning folios to the pool

This results in an issue during boot.

This fix is required.

 mm/hugetlb.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/hugetlb.c renamed from mm/hugetlb.c~mm-hugetlb-account-temporary-folios-separately-fix +1 -1
@@ -1792,8 +1792,8 @@ void free_huge_folio(struct folio *folio
 		h->resv_huge_pages++;
 
 	if (folio_test_hugetlb_temporary(folio)) {
-		folio_clear_hugetlb_temporary(folio);
 		remove_hugetlb_folio(h, folio, false);
+		folio_clear_hugetlb_temporary(folio);
 		spin_unlock_irqrestore(&hugetlb_lock, flags);
 		update_and_free_hugetlb_folio(h, folio, true);
 	} else if (h->surplus_huge_pages_node[nid]) {

_

maintainer tree notice
#19 lore raw

+ mm-hugetlb-account-temporary-folios-separately-fix.patch added to mm-unstable branch

In reply to David Hildenbrand (Arm)
The patch titled Subject: mm-hugetlb-account-temporary-folios-separately-fix has been added to the -mm mm-unstable branch. Its filename is mm-hugetlb-account-temporary-folios-separately-fix.patch

The patch titled
Subject: mm-hugetlb-account-temporary-folios-separately-fix
has been added to the -mm mm-unstable branch. Its filename is
mm-hugetlb-account-temporary-folios-separately-fix.patch

This patch will shortly appear at
https://git.kernel.org/pub/scm/linux/kernel/git/akpm/25-new.git/tree/patches/mm-hugetlb-account-temporary-folios-separately-fix.patch

This patch will later appear in the mm-unstable branch at
git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

Before you just go and hit "reply", please:
a) Consider who else should be cc'ed
b) Prefer to cc a suitable mailing list as well
c) Ideally: find the original patch on the mailing list and do a reply-to-all to that, adding suitable additional cc's

*** Remember to use Documentation/process/submit-checklist.rst when testing your code ***

The -mm tree is included into linux-next via various branches at git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm
and is updated there most days

------------------------------------------------------
From: "David Hildenbrand (Arm)" <[email protected]>
Subject: mm-hugetlb-account-temporary-folios-separately-fix
Date: Sun, 22 Nov 2026 19:21:43 +0100

In combination with

mm/hugetlb: preserve persistent flags when returning folios to the pool

This results in an issue during boot.

This fix is required.

 mm/hugetlb.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/hugetlb.c renamed from mm/hugetlb.c~mm-hugetlb-account-temporary-folios-separately-fix +1 -1
@@ -1792,8 +1792,8 @@ void free_huge_folio(struct folio *folio
 		h->resv_huge_pages++;
 
 	if (folio_test_hugetlb_temporary(folio)) {
-		folio_clear_hugetlb_temporary(folio);
 		remove_hugetlb_folio(h, folio, false);
+		folio_clear_hugetlb_temporary(folio);
 		spin_unlock_irqrestore(&hugetlb_lock, flags);
 		update_and_free_hugetlb_folio(h, folio, true);
 	} else if (h->surplus_huge_pages_node[nid]) {

_

Patches currently in -mm which might be from [email protected] are

maintainers-memory-management-mglru-multi-gen-lru-update.patch maintainers-remove-myself-from-memory-management-reclaim.patch hugetlbfs-fix-integer-overflow-in-fallocate.patch mm-hugetlb-fix-mremap-racing-with-page-migration.patch mm-mprotect-dont-skip-uffd-marker-install-when-racing-with-pte-table-reclaim.patch mm-khugepaged-free-unused-page-table-when-setting-a-huge-pmd-fails.patch mm-userfaultfd-prevent-poison-marker-loss.patch mm-hugetlb-compare-against-persistent-count-when-freeing-lowmem-folios.patch mm-hugetlb-preserve-reservations-when-shrinking-on-highmem.patch mm-hugetlb-account-temporary-folios-separately.patch mm-hugetlb-account-temporary-folios-separately-fix.patch mm-hugetlb-serialize-page-cache-allocations-with-truncation.patch mm-memfd-recheck-the-page-cache-before-allocating-a-hugetlb-folio.patch mm-hugetlb-count-again-if-the-reserve-map-shrank.patch mm-hugetlb-account-restored-reservations-before-freeing-folios.patch mm-hugetlb-delay-anon-folio-rmap-removal-until-after-the-tlb-flush.patch

author maintainer
#20 lore raw

PATCH v2 5/15 mm/hugetlb: keep surplus folios when the pool shrinks

In reply to David Hildenbrand (Arm)

From: Josef Bacik <[email protected]>

Surplus folios are accounted per node. When shrinking the pool, set_max_huge_pages() removes free folios through remove_pool_hugetlb_folio() and accounts them as persistent folios.

It can select a node whose folios are all surplus and leave its surplus count larger than its total count. Free surplus folios can back reservations created by gather_surplus_pages().

For example, with nr_overcommit_hugepages = 8 on two nodes:

(node columns show total/free/surplus)

                                      total free surp   node0   node1
  mmap() of one page, bound to node 0     1    1    1   1 1 1   0 0 0
  node1/nr_hugepages = 7                  8    8    1   1 1 1   7 7 0
  nr_hugepages = 6                        7    7    1   0 0 1   7 7 0
  munmap()                                7    7    1   0 0 1   7 7 0
  nr_hugepages = 0                        1    1    1   0 0 1   1 1 0

After shrinking to six persistent folios, node 0 has no folios but its surplus count is still one. Releasing the reservation cannot clear that count, and shrinking the pool to zero leaves one free page on node 1.

A later write to node0/nr_hugepages underflows the unsigned per-node persistent count: 0 - 1, resulting in allocation of many folios.

Use persistent_huge_pages_node() to skip nodes with no persistent folios, as adjust_pool_surplus() does. This also excludes temporary folios.

Fixes e4e574b767ba ("hugetlb: Try to grow hugetlb pool for MAP_SHARED mappings")
[ david: cleanup code and description ]
---
 mm/hugetlb.c | 22 +++++++++++++++-------
 1 file changed, 15 insertions(+), 7 deletions(-)
mm/hugetlb.c +15 -7
index d7c71025d166b..3ffd87eb9e45f 100644
@@ -1959,17 +1959,25 @@ static struct folio *remove_pool_hugetlb_folio(struct hstate *h,
 
 	lockdep_assert_held(&hugetlb_lock);
 	for_each_node_mask_to_free(h, nr_nodes, node, nodes_allowed) {
+		if (list_empty(&h->hugepage_freelists[node]))
+			continue;
+
 		/*
 		 * If we're returning unused surplus pages, only examine
-		 * nodes with surplus pages.
+		 * nodes with surplus pages. If we're shrinking the pool, only
+		 * examine nodes with persistent folios.
 		 */
-		if ((!acct_surplus || h->surplus_huge_pages_node[node]) &&
-		    !list_empty(&h->hugepage_freelists[node])) {
-			folio = list_entry(h->hugepage_freelists[node].next,
-					  struct folio, lru);
-			remove_hugetlb_folio(h, folio, acct_surplus);
-			break;
+		if (acct_surplus) {
+			if (!h->surplus_huge_pages_node[node])
+				continue;
+		} else if (!persistent_huge_pages_node(h, node)) {
+			continue;
 		}
+
+		folio = list_first_entry(&h->hugepage_freelists[node],
+					 struct folio, lru);
+		remove_hugetlb_folio(h, folio, acct_surplus);
+		break;
 	}
 
 	return folio;
Signature · 1 line
2.56.1
#21 lore raw

Re: [PATCH v2 05/15] mm/hugetlb: keep surplus folios when the pool shrinks

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

From: Josef Bacik <[email protected]>

Surplus folios are accounted per node. When shrinking the pool, set_max_huge_pages() removes free folios through remove_pool_hugetlb_folio() and accounts them as persistent folios.

It can select a node whose folios are all surplus and leave its surplus count larger than its total count. Free surplus folios can back reservations created by gather_surplus_pages().

For example, with nr_overcommit_hugepages = 8 on two nodes:

(node columns show total/free/surplus)

Quoted 7 lines

total free surp node0 node1

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
Acked-by on v2 5/15
#22 lore raw

Re: [PATCH v2 05/15] mm/hugetlb: keep surplus folios when the pool shrinks

In reply to David Hildenbrand (Arm)
Quoted 31 lines · David Hildenbrand (Arm)

From: Josef Bacik <[email protected]>

Surplus folios are accounted per node. When shrinking the pool, set_max_huge_pages() removes free folios through remove_pool_hugetlb_folio() and accounts them as persistent folios.

It can select a node whose folios are all surplus and leave its surplus count larger than its total count. Free surplus folios can back reservations created by gather_surplus_pages().

For example, with nr_overcommit_hugepages = 8 on two nodes:

(node columns show total/free/surplus)

                                      total free surp   node0   node1
  mmap() of one page, bound to node 0     1    1    1   1 1 1   0 0 0
  node1/nr_hugepages = 7                  8    8    1   1 1 1   7 7 0
  nr_hugepages = 6                        7    7    1   0 0 1   7 7 0
  munmap()                                7    7    1   0 0 1   7 7 0
  nr_hugepages = 0                        1    1    1   0 0 1   1 1 0

After shrinking to six persistent folios, node 0 has no folios but its surplus count is still one. Releasing the reservation cannot clear that count, and shrinking the pool to zero leaves one free page on node 1.

A later write to node0/nr_hugepages underflows the unsigned per-node persistent count: 0 - 1, resulting in allocation of many folios.

Use persistent_huge_pages_node() to skip nodes with no persistent folios, as adjust_pool_surplus() does. This also excludes temporary folios.

Quoted 7 lines
Fixes e4e574b767ba ("hugetlb: Try to grow hugetlb pool for MAP_SHARED mappings")
[ david: cleanup code and description ]
Signature · 2 lines
Oscar Salvador
SUSE Labs
author maintainer
#23 lore raw

PATCH v2 6/15 mm/hugetlb: fix mremap() racing with page migration

In reply to David Hildenbrand (Arm)

Migration of anon hugetlb folios walks the anon_vma, so the file's i_mmap_rwsem does not serialize it against move_hugetlb_page_tables().

There are various issues with that. Most importantly, move_huge_pte() releases both page table locks before the TLB is flushed. Migration can then find the destination entry and finish migration, reusing the old folio while the TLB still has entries cached.

Hold the anon_vma write lock across the move and the final TLB flush. This also prevents concurrent rmap walks from missing entries moved during rollback.

When we must allocate a destination page table, flush the TLB before dropping the anon_vma lock, then reacquire it after allocation.

Dropping the lock only works around lockdep: hugetlb folios are not reclaimed or migrated by allocation compaction, but their anon_vmas share the lock class used by ordinary anonymous memory. Having a separate lock class for hugetlb's anon_vma (like already done for i_mmap_rwsem via hugetlbfs_i_mmap_rwsem_key) requires more thought.

There is a concern that this can block page migration of anonymous folios quite a while ... which is not really different to what happens to page-cache folios today. If ever a problem, we can temporarily release the lock.

So let's keep it simple for now.

It is a shame that hugetlb has to implement everything core-mm implements in a different way that just screams for problems.

Fixes 550a7d60bd5e ("mm, hugepages: add mremap() support for hugepage backed vma")
---
 mm/hugetlb.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
mm/hugetlb.c +20 -1
index 3ffd87eb9e45f..4a24819733730 100644
@@ -5214,6 +5214,7 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
 {
 	struct hstate *h = hstate_vma(vma);
 	struct address_space *mapping = vma->vm_file->f_mapping;
+	struct anon_vma *anon_vma = vma->anon_vma;
 	unsigned long sz = huge_page_size(h);
 	struct mm_struct *mm = vma->vm_mm;
 	unsigned long old_end = old_addr + len;
@@ -5237,6 +5238,8 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
 	/* Prevent race with file truncation */
 	hugetlb_vma_lock_write(vma);
 	i_mmap_lock_write(mapping);
+	if (anon_vma)
+		anon_vma_lock_write(anon_vma);
 	for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
 		const unsigned long offset_to_last_entry =
 			(old_addr | last_addr_mask) - old_addr;
@@ -5276,7 +5279,20 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
 			continue;
 		}
 
-		dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
+		dst_pte = hugetlb_walk(new_vma, new_addr, sz);
+		if (!dst_pte) {
+			/*
+			 * We can allocate memory under anon_vma lock with hugetlb,
+			 * but lockdep does not know about that. So for now we simply
+			 * flush the TLB and temporarily drop the lock.
+			 */
+			tlb_flush_mmu_tlbonly(&tlb);
+			if (anon_vma)
+				anon_vma_unlock_write(anon_vma);
+			dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
+			if (anon_vma)
+				anon_vma_lock_write(anon_vma);
+		}
 		if (!dst_pte)
 			break;
 
@@ -5284,7 +5300,10 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
 		tlb_remove_huge_tlb_entry(h, &tlb, src_pte, old_addr);
 	}
 
+	/* Flush pending moves before allowing migration to walk the entries. */
 	tlb_flush_mmu_tlbonly(&tlb);
+	if (anon_vma)
+		anon_vma_unlock_write(anon_vma);
 	huge_pmd_unshare_flush(&tlb, vma);
 
 	mmu_notifier_invalidate_range_end(&range);
Signature · 1 line
2.56.1
#24 lore raw

Re: [PATCH v2 06/15] mm/hugetlb: fix mremap() racing with page migration

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

Migration of anon hugetlb folios walks the anon_vma, so the file's i_mmap_rwsem does not serialize it against move_hugetlb_page_tables().

There are various issues with that. Most importantly, move_huge_pte() releases both page table locks before the TLB is flushed. Migration can then find the destination entry and finish migration, reusing the old folio while the TLB still has entries cached.

Hold the anon_vma write lock across the move and the final TLB flush. This also prevents concurrent rmap walks from missing entries moved during rollback.

When we must allocate a destination page table, flush the TLB before dropping the anon_vma lock, then reacquire it after allocation.

Quoted 6 lines
[ ... ]
Fixes 550a7d60bd5e ("mm, hugepages: add mremap() support for hugepage backed vma")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
Tested-by Reviewed-by on v2 6/15
#25 lore raw

Re: [PATCH v2 06/15] mm/hugetlb: fix mremap() racing with page migration

In reply to David Hildenbrand (Arm)
Quoted 28 lines · David Hildenbrand (Arm)

Migration of anon hugetlb folios walks the anon_vma, so the file's i_mmap_rwsem does not serialize it against move_hugetlb_page_tables().

There are various issues with that. Most importantly, move_huge_pte() releases both page table locks before the TLB is flushed. Migration can then find the destination entry and finish migration, reusing the old folio while the TLB still has entries cached.

Hold the anon_vma write lock across the move and the final TLB flush. This also prevents concurrent rmap walks from missing entries moved during rollback.

When we must allocate a destination page table, flush the TLB before dropping the anon_vma lock, then reacquire it after allocation.

Dropping the lock only works around lockdep: hugetlb folios are not reclaimed or migrated by allocation compaction, but their anon_vmas share the lock class used by ordinary anonymous memory. Having a separate lock class for hugetlb's anon_vma (like already done for i_mmap_rwsem via hugetlbfs_i_mmap_rwsem_key) requires more thought.

There is a concern that this can block page migration of anonymous folios quite a while ... which is not really different to what happens to page-cache folios today. If ever a problem, we can temporarily release the lock.

So let's keep it simple for now.

Quoted 8 lines

It is a shame that hugetlb has to implement everything core-mm implements in a different way that just screams for problems.

Fixes 550a7d60bd5e ("mm, hugepages: add mremap() support for hugepage backed vma")
Signature · 1 line
~Gregory
Acked-by on v2 6/15
#26 lore raw

Re: [PATCH v2 06/15] mm/hugetlb: fix mremap() racing with page migration

In reply to David Hildenbrand (Arm)
Quoted 28 lines · David Hildenbrand (Arm)

Migration of anon hugetlb folios walks the anon_vma, so the file's i_mmap_rwsem does not serialize it against move_hugetlb_page_tables().

There are various issues with that. Most importantly, move_huge_pte() releases both page table locks before the TLB is flushed. Migration can then find the destination entry and finish migration, reusing the old folio while the TLB still has entries cached.

Hold the anon_vma write lock across the move and the final TLB flush. This also prevents concurrent rmap walks from missing entries moved during rollback.

When we must allocate a destination page table, flush the TLB before dropping the anon_vma lock, then reacquire it after allocation.

Dropping the lock only works around lockdep: hugetlb folios are not reclaimed or migrated by allocation compaction, but their anon_vmas share the lock class used by ordinary anonymous memory. Having a separate lock class for hugetlb's anon_vma (like already done for i_mmap_rwsem via hugetlbfs_i_mmap_rwsem_key) requires more thought.

There is a concern that this can block page migration of anonymous folios quite a while ... which is not really different to what happens to page-cache folios today. If ever a problem, we can temporarily release the lock.

So let's keep it simple for now.

Quoted 8 lines

It is a shame that hugetlb has to implement everything core-mm implements in a different way that just screams for problems.

Fixes 550a7d60bd5e ("mm, hugepages: add mremap() support for hugepage backed vma")
Signature · 2 lines
Oscar Salvador
SUSE Labs
maintainer tree notice Applied
#27 lore raw

[merged mm-hotfixes-stable] mm-hugetlb-fix-mremap-racing-with-page-migration.patch removed from -mm tree

In reply to David Hildenbrand (Arm)
The quilt patch titled Subject: mm/hugetlb: fix mremap() racing with page migration has been removed from the -mm tree. Its filename was mm-hugetlb-fix-mremap-racing-with-page-migration.patch

The quilt patch titled
Subject: mm/hugetlb: fix mremap() racing with page migration
has been removed from the -mm tree. Its filename was
mm-hugetlb-fix-mremap-racing-with-page-migration.patch

This patch was dropped because it was merged into the mm-hotfixes-stable branch of git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

------------------------------------------------------
From: "David Hildenbrand (Arm)" <[email protected]>
Subject: mm/hugetlb: fix mremap() racing with page migration
Date: Mon, 16 Nov 2026 19:29:27 +0100

Migration of anon hugetlb folios walks the anon_vma, so the file's i_mmap_rwsem does not serialize it against move_hugetlb_page_tables().

There are various issues with that. Most importantly, move_huge_pte() releases both page table locks before the TLB is flushed. Migration can then find the destination entry and finish migration, reusing the old folio while the TLB still has entries cached.

Hold the anon_vma write lock across the move and the final TLB flush. This also prevents concurrent rmap walks from missing entries moved during rollback.

When we must allocate a destination page table, flush the TLB before dropping the anon_vma lock, then reacquire it after allocation.

Dropping the lock only works around lockdep: hugetlb folios are not reclaimed or migrated by allocation compaction, but their anon_vmas share the lock class used by ordinary anonymous memory. Having a separate lock class for hugetlb's anon_vma (like already done for i_mmap_rwsem via hugetlbfs_i_mmap_rwsem_key) requires more thought.

There is a concern that this can block page migration of anonymous folios quite a while ... which is not really different to what happens to page-cache folios today. If ever a problem, we can temporarily release the lock.

So let's keep it simple for now.

It is a shame that hugetlb has to implement everything core-mm implements in a different way that just screams for problems.

Fixes 550a7d60bd5e ("mm, hugepages: add mremap() support for hugepage backed vma")
Cc Oscar Salvador <[email protected]>
Cc Naoya Horiguchi <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Andy Whitcroft <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Vivek Kasireddy <[email protected]>
Cc Dave Airlie <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Peter Xu <[email protected]>
Cc Breno Leitao <[email protected]>
Cc Will Deacon <[email protected]>
Cc Aneesh Kumar K.V <[email protected]>
Cc Nicholas Piggin <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Vasily Gorbik <[email protected]>
Cc Alexander Gordeev <[email protected]>
Cc Christian Borntraeger <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Gerd Hoffmann <[email protected]>
Cc Josef Bacik <[email protected]>
Cc Daehyeon Ko <[email protected]>
Cc luojiajun <[email protected]>
Cc Ackerley Tng <[email protected]>
 mm/hugetlb.c |   21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
mm/hugetlb.c renamed from mm/hugetlb.c~mm-hugetlb-fix-mremap-racing-with-page-migration +20 -1
@@ -5204,6 +5204,7 @@ unsigned long move_hugetlb_page_tables(s
 {
 	struct hstate *h = hstate_vma(vma);
 	struct address_space *mapping = vma->vm_file->f_mapping;
+	struct anon_vma *anon_vma = vma->anon_vma;
 	unsigned long sz = huge_page_size(h);
 	struct mm_struct *mm = vma->vm_mm;
 	unsigned long old_end = old_addr + len;
@@ -5227,6 +5228,8 @@ unsigned long move_hugetlb_page_tables(s
 	/* Prevent race with file truncation */
 	hugetlb_vma_lock_write(vma);
 	i_mmap_lock_write(mapping);
+	if (anon_vma)
+		anon_vma_lock_write(anon_vma);
 	for (; old_addr < old_end; old_addr += sz, new_addr += sz) {
 		const unsigned long offset_to_last_entry =
 			(old_addr | last_addr_mask) - old_addr;
@@ -5266,7 +5269,20 @@ unsigned long move_hugetlb_page_tables(s
 			continue;
 		}
 
-		dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
+		dst_pte = hugetlb_walk(new_vma, new_addr, sz);
+		if (!dst_pte) {
+			/*
+			 * We can allocate memory under anon_vma lock with hugetlb,
+			 * but lockdep does not know about that. So for now we simply
+			 * flush the TLB and temporarily drop the lock.
+			 */
+			tlb_flush_mmu_tlbonly(&tlb);
+			if (anon_vma)
+				anon_vma_unlock_write(anon_vma);
+			dst_pte = huge_pte_alloc(mm, new_vma, new_addr, sz);
+			if (anon_vma)
+				anon_vma_lock_write(anon_vma);
+		}
 		if (!dst_pte)
 			break;
 
@@ -5274,7 +5290,10 @@ unsigned long move_hugetlb_page_tables(s
 		tlb_remove_huge_tlb_entry(h, &tlb, src_pte, old_addr);
 	}
 
+	/* Flush pending moves before allowing migration to walk the entries. */
 	tlb_flush_mmu_tlbonly(&tlb);
+	if (anon_vma)
+		anon_vma_unlock_write(anon_vma);
 	huge_pmd_unshare_flush(&tlb, vma);
 
 	mmu_notifier_invalidate_range_end(&range);

_

Patches currently in -mm which might be from [email protected] are

mm-mprotect-dont-skip-uffd-marker-install-when-racing-with-pte-table-reclaim.patch mm-khugepaged-free-unused-page-table-when-setting-a-huge-pmd-fails.patch mm-userfaultfd-prevent-poison-marker-loss.patch mm-hugetlb-compare-against-persistent-count-when-freeing-lowmem-folios.patch mm-hugetlb-preserve-reservations-when-shrinking-on-highmem.patch mm-hugetlb-account-temporary-folios-separately.patch mm-hugetlb-account-temporary-folios-separately-fix.patch mm-hugetlb-serialize-page-cache-allocations-with-truncation.patch mm-memfd-recheck-the-page-cache-before-allocating-a-hugetlb-folio.patch mm-hugetlb-count-again-if-the-reserve-map-shrank.patch mm-hugetlb-account-restored-reservations-before-freeing-folios.patch mm-hugetlb-delay-anon-folio-rmap-removal-until-after-the-tlb-flush.patch

author maintainer
#28 lore raw

PATCH v2 7/15 hugetlbfs: fix unmapping folios from private VMAs

In reply to David Hildenbrand (Arm)

From: Josef Bacik <[email protected]>

hugetlb_unmap_file_folio() assumes vm_private_data points to a struct hugetlb_vma_lock when hugetlb_vma_trylock_write() fails. Since hugetlb VMA locking was extended to private VMAs, this can also happen when vm_private_data contains a resv_map pointer; treating it as a hugetlb_vma_lock corrupts memory and can cause crashes or hangs.

Only take the VMA lock when a shareable lock exists, as additional locking is only needed for PMD table sharing. The fault mutex and i_mmap_rwsem already provide the required protection for private VMAs.

Fix generated by an LLM and sent by Josef Bacik in private.

Fixes bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs")
[ david: simplify description and comment ]
---
 fs/hugetlbfs/inode.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
fs/hugetlbfs/inode.c +10 -0
index 9f502a456cdb0..1d0c35e639e80 100644
@@ -401,6 +401,16 @@ static void hugetlb_unmap_file_folio(struct hstate *h,
 		if (!hugetlb_vma_maps_pfn(vma, v_start, pfn))
 			continue;
 
+		/*
+		 * We only need additional VMA locking here for PMD table
+		 * sharing, which synchronizes on the shareable lock.
+		 */
+		if (!__vma_shareable_lock(vma)) {
+			unmap_hugepage_range(vma, v_start, v_end, NULL,
+					     ZAP_FLAG_DROP_MARKER);
+			continue;
+		}
+
 		if (!hugetlb_vma_trylock_write(vma)) {
 			vma_lock = vma->vm_private_data;
 			/*
Signature · 1 line
2.56.1
#29 lore raw

Re: [PATCH v2 07/15] hugetlbfs: fix unmapping folios from private VMAs

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

From: Josef Bacik <[email protected]>

hugetlb_unmap_file_folio() assumes vm_private_data points to a struct hugetlb_vma_lock when hugetlb_vma_trylock_write() fails. Since hugetlb VMA locking was extended to private VMAs, this can also happen when vm_private_data contains a resv_map pointer; treating it as a hugetlb_vma_lock corrupts memory and can cause crashes or hangs.

Only take the VMA lock when a shareable lock exists, as additional locking is only needed for PMD table sharing. The fault mutex and i_mmap_rwsem already provide the required protection for private VMAs.

Fix generated by an LLM and sent by Josef Bacik in private.

Quoted 7 lines
Fixes bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs")
[ david: simplify description and comment ]

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
Tested-by on v2 7/15
#30 lore raw

Re: [PATCH v2 07/15] hugetlbfs: fix unmapping folios from private VMAs

In reply to David Hildenbrand (Arm)
Quoted 14 lines · David Hildenbrand (Arm)

From: Josef Bacik <[email protected]>

hugetlb_unmap_file_folio() assumes vm_private_data points to a struct hugetlb_vma_lock when hugetlb_vma_trylock_write() fails. Since hugetlb VMA locking was extended to private VMAs, this can also happen when vm_private_data contains a resv_map pointer; treating it as a hugetlb_vma_lock corrupts memory and can cause crashes or hangs.

Only take the VMA lock when a shareable lock exists, as additional locking is only needed for PMD table sharing. The fault mutex and i_mmap_rwsem already provide the required protection for private VMAs.

Fix generated by an LLM and sent by Josef Bacik in private.

Quoted 7 lines
Fixes bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs")
[ david: simplify description and comment ]

Was able to reproduce a hang / RCU lockup pretty handily and verified this resolves it. Have not seen the relevant crash.

Regardless:

Signature · 1 line
~Gregory
Acked-by on v2 7/15
#31 lore raw

Re: [PATCH v2 07/15] hugetlbfs: fix unmapping folios from private VMAs

In reply to David Hildenbrand (Arm)
Quoted 14 lines · David Hildenbrand (Arm)

From: Josef Bacik <[email protected]>

hugetlb_unmap_file_folio() assumes vm_private_data points to a struct hugetlb_vma_lock when hugetlb_vma_trylock_write() fails. Since hugetlb VMA locking was extended to private VMAs, this can also happen when vm_private_data contains a resv_map pointer; treating it as a hugetlb_vma_lock corrupts memory and can cause crashes or hangs.

Only take the VMA lock when a shareable lock exists, as additional locking is only needed for PMD table sharing. The fault mutex and i_mmap_rwsem already provide the required protection for private VMAs.

Fix generated by an LLM and sent by Josef Bacik in private.

Quoted 7 lines
Fixes bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs")
[ david: simplify description and comment ]
Signature · 2 lines
Oscar Salvador
SUSE Labs
maintainer tree notice Applied
#32 lore raw

[merged mm-hotfixes-stable] hugetlbfs-fix-unmapping-folios-from-private-vmas.patch removed from -mm tree

In reply to David Hildenbrand (Arm)
The quilt patch titled Subject: hugetlbfs: fix unmapping folios from private VMAs has been removed from the -mm tree. Its filename was hugetlbfs-fix-unmapping-folios-from-private-vmas.patch

The quilt patch titled
Subject: hugetlbfs: fix unmapping folios from private VMAs
has been removed from the -mm tree. Its filename was
hugetlbfs-fix-unmapping-folios-from-private-vmas.patch

This patch was dropped because it was merged into the mm-hotfixes-stable branch of git://git.kernel.org/pub/scm/linux/kernel/git/akpm/mm

------------------------------------------------------
From: Josef Bacik <[email protected]>
Subject: hugetlbfs: fix unmapping folios from private VMAs
Date: Mon, 16 Nov 2026 19:29:28 +0100

hugetlb_unmap_file_folio() assumes vm_private_data points to a struct hugetlb_vma_lock when hugetlb_vma_trylock_write() fails. Since hugetlb VMA locking was extended to private VMAs, this can also happen when vm_private_data contains a resv_map pointer; treating it as a hugetlb_vma_lock corrupts memory and can cause crashes or hangs.

Only take the VMA lock when a shareable lock exists, as additional locking is only needed for PMD table sharing. The fault mutex and i_mmap_rwsem already provide the required protection for private VMAs.

Fix generated by an LLM and sent by Josef Bacik in private.

[[email protected]: simplify description and comment]
Fixes bf4916922c60 ("hugetlbfs: extend hugetlb_vma_lock to private VMAs")
Cc Oscar Salvador <[email protected]>
Cc Naoya Horiguchi <[email protected]>
Cc Mel Gorman <[email protected]>
Cc Andy Whitcroft <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Vivek Kasireddy <[email protected]>
Cc Dave Airlie <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Peter Xu <[email protected]>
Cc Breno Leitao <[email protected]>
Cc Will Deacon <[email protected]>
Cc Aneesh Kumar K.V <[email protected]>
Cc Nicholas Piggin <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Vasily Gorbik <[email protected]>
Cc Alexander Gordeev <[email protected]>
Cc Christian Borntraeger <[email protected]>
Cc Sven Schnelle <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Gerd Hoffmann <[email protected]>
Cc Chris Mason <[email protected]>
Cc luojiajun <[email protected]>
Cc Ackerley Tng <[email protected]>
 fs/hugetlbfs/inode.c |   10 ++++++++++
 1 file changed, 10 insertions(+)
fs/hugetlbfs/inode.c renamed from fs/hugetlbfs/inode.c~hugetlbfs-fix-unmapping-folios-from-private-vmas +10 -0
@@ -401,6 +401,16 @@ retry:
 		if (!hugetlb_vma_maps_pfn(vma, v_start, pfn))
 			continue;
 
+		/*
+		 * We only need additional VMA locking here for PMD table
+		 * sharing, which synchronizes on the shareable lock.
+		 */
+		if (!__vma_shareable_lock(vma)) {
+			unmap_hugepage_range(vma, v_start, v_end, NULL,
+					     ZAP_FLAG_DROP_MARKER);
+			continue;
+		}
+
 		if (!hugetlb_vma_trylock_write(vma)) {
 			vma_lock = vma->vm_private_data;
 			/*

_

Patches currently in -mm which might be from [email protected] are

mm-zswap-drop-the-stale-zswap-entry-of-a-zero-folio.patch mm-swap-account-synchronous-swap-reads-as-memory-stall.patch mm-mremap-fix-hugetlb-reservation-leak-on-partial-move.patch selftests-mm-test-a-partial-mremap-of-hugetlb-memory.patch mm-mremap-reaccount-on-unmap-failure-only-if-accounted.patch mm-mremap-restore-vma_account_bit-if-the-unmap-fails.patch selftests-mm-test-mremap-with-an-old-size-of-0.patch zram-lz4-lz4hc-accept-dictionaries-of-more-than-64-kib.patch mm-hugetlb-keep-surplus-folios-when-the-pool-shrinks.patch

author maintainer
#33 lore raw

PATCH v2 8/15 mm/hugetlb: serialize page-cache allocations with truncation

In reply to David Hildenbrand (Arm)

Truncation can remove an inode reservation while a fault is still allocating its folio. UFFDIO_COPY and memfd pinning can also consume reservations beyond the new i_size. This can underflow resv_huge_pages and leave folios beyond EOF.

The main issue is that truncation takes the fault mutex for folios in the page-cache, but it has no clue about faults that are still being processed concurrently.

Matthew Wilcox raised mapping->invalidate_lock in a different upstream hugetlb locking discussion:

"although I wonder if we still need the fault mutex array, given that we
now have mapping->invalidate_lock?"

While it likely cannot remove the mutex array entirely (concurrent page faults have to sync ... ), we can at least use it to fix this problem.

Hold mapping->invalidate_lock shared across the size check, allocation and page cache insertion or reservation rollback. Truncation takes it exclusively around i_size_write() only for now: it waits for concurrent allocations to finish updating the page-cache or rolling back reservations before changing the size. Subsequent allocations see the updated i_size.

Let truncation release the lock for now before unmapping and removing folios to preserve the existing lock ordering. Cached-folio faults and private allocations do not acquire the new lock.

Use it to synchronize with truncation, keeping the fault mutexes to serialize allocations for the same index.

Locking order is now:

fault mutex -> hugetlb VMA lock (read) -> invalidate lock (read) -> folio lock -> PTE lock

And on truncation:

i_rwsem (write) -> invalidate lock (write)

Add hugetlb_pgoff_valid() to not repeat the same size check multiple times. Memfd needs a bit of care, as it traditionally allowed partial folios to be pinned: the size check in memfd_pin_folios() allows for that.

Fixes 1c9e8def43a3 ("userfaultfd: hugetlbfs: add UFFDIO_COPY support for shared mappings")
Fixes 188a39725ad7 ("hugetlbfs: revert use i_mmap_rwsem to address page fault/truncate race")
Fixes 89c1905d9c14 ("mm/gup: introduce memfd_pin_folios() for pinning memfd folios")
---
 fs/hugetlbfs/inode.c    | 15 +++++++++++----
 include/linux/hugetlb.h | 12 ++++++++++++
 mm/hugetlb.c            | 45 +++++++++++++++++++++++++++++++++------------
 mm/memfd.c              |  8 ++++++++
 4 files changed, 64 insertions(+), 16 deletions(-)
fs/hugetlbfs/inode.c +11 -4
index 1d0c35e639e80..7f64bdc07aa80 100644
@@ -546,10 +546,9 @@ static void remove_inode_single_folio(struct hstate *h, struct inode *inode,
  * truncation is indicated by end of range being LLONG_MAX
  *	In this case, we first scan the range and release found pages.
  *	After releasing pages, hugetlb_unreserve_pages cleans up region/reserve
- *	maps and global counts.  Page faults can race with truncation.
- *	During faults, hugetlb_no_page() checks i_size before page allocation,
- *	and again after obtaining page table lock.  It will 'back out'
- *	allocations in the truncated range.
+ *	maps and global counts.  hugetlb_vmtruncate() updates i_size under
+ *	invalidate_lock to synchronize with new page cache allocations from
+ *	page faults, uffd, etc.
  * hole punch is indicated if end is not LLONG_MAX
  *	In the hole punch case we scan the range and release found pages.
  *	Only when releasing a page is the associated region/reserve map
@@ -623,7 +622,15 @@ static void hugetlb_vmtruncate(struct inode *inode, loff_t offset)
 	BUG_ON(offset & ~huge_page_mask(h));
 	pgoff = offset >> PAGE_SHIFT;
 
+	filemap_invalidate_lock(mapping);
 	i_size_write(inode, offset);
+	/*
+	 * The size check now prevents new page-cache allocations in the
+	 * truncated range. Existing folios and reservations are cleaned up
+	 * below.
+	 */
+	filemap_invalidate_unlock(mapping);
+
 	i_mmap_lock_write(mapping);
 	if (mapping_mapped(mapping))
 		hugetlb_vmdelete_list(mapping, pgoff, 0, ZAP_FLAG_DROP_MARKER);
include/linux/hugetlb.h +12 -0
index 80ae65c7849b9..1d2dd10074d7a 100644
@@ -820,6 +820,18 @@ static inline unsigned huge_page_shift(struct hstate *h)
 	return h->order + PAGE_SHIFT;
 }
 
+static inline bool hugetlb_pgoff_valid(struct address_space *mapping,
+		pgoff_t idx, bool partial)
+{
+	struct hstate *h = hstate_inode(mapping->host);
+	u64 size = i_size_read(mapping->host);
+
+	if (partial)
+		size = round_up(size, huge_page_size(h));
+
+	return idx < (size >> huge_page_shift(h));
+}
+
 /**
  * hugetlb_linear_page_index() - linear_page_index() but in hugetlb
  *				 page size granularity.
mm/hugetlb.c +33 -12

122 lines not on this page · raw message

mm/memfd.c +8 -0
index 0e3ff3eebfa82..f03d12aa71f7a 100644
@@ -96,6 +96,12 @@ struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx)
 		hash = hugetlb_fault_mutex_hash(memfd->f_mapping, idx);
 		mutex_lock(&hugetlb_fault_mutex_table[hash]);
 
+		filemap_invalidate_lock_shared(memfd->f_mapping);
+		if (!hugetlb_pgoff_valid(memfd->f_mapping, idx, /* partial= */ true)) {
+			err = -EINVAL;
+			goto out_unlock;
+		}
+
 		nr_resv = hugetlb_reserve_pages(inode, idx, idx + 1, NULL, EMPTY_VMA_FLAGS);
 		if (nr_resv < 0) {
 			err = nr_resv;
@@ -131,6 +137,7 @@ struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx)
 
 			hugetlb_set_folio_subpool(folio, subpool_inode(inode));
 			folio_unlock(folio);
+			filemap_invalidate_unlock_shared(memfd->f_mapping);
 			mutex_unlock(&hugetlb_fault_mutex_table[hash]);
 			return folio;
 		}
@@ -138,6 +145,7 @@ struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx)
 		if (nr_resv > 0)
 			hugetlb_unreserve_pages(inode, idx, idx + 1, 0);
 out_unlock:
+		filemap_invalidate_unlock_shared(memfd->f_mapping);
 		mutex_unlock(&hugetlb_fault_mutex_table[hash]);
 		return ERR_PTR(err);
 	}
Signature · 1 line
2.56.1
#34 lore raw

Re: [PATCH v2 08/15] mm/hugetlb: serialize page-cache allocations with truncation

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

Truncation can remove an inode reservation while a fault is still allocating its folio. UFFDIO_COPY and memfd pinning can also consume reservations beyond the new i_size. This can underflow resv_huge_pages and leave folios beyond EOF.

The main issue is that truncation takes the fault mutex for folios in the page-cache, but it has no clue about faults that are still being processed concurrently.

Matthew Wilcox raised mapping->invalidate_lock in a different upstream hugetlb locking discussion:

"although I wonder if we still need the fault mutex array, given that we
now have mapping->invalidate_lock?"

Quoted 6 lines
[ ... ]
Fixes 89c1905d9c14 ("mm/gup: introduce memfd_pin_folios() for pinning memfd folios")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
Acked-by on v2 8/15
#35 lore raw

Re: [PATCH v2 08/15] mm/hugetlb: serialize page-cache allocations with truncation

In reply to David Hildenbrand (Arm)
Quoted 45 lines · David Hildenbrand (Arm)

Truncation can remove an inode reservation while a fault is still allocating its folio. UFFDIO_COPY and memfd pinning can also consume reservations beyond the new i_size. This can underflow resv_huge_pages and leave folios beyond EOF.

The main issue is that truncation takes the fault mutex for folios in the page-cache, but it has no clue about faults that are still being processed concurrently.

Matthew Wilcox raised mapping->invalidate_lock in a different upstream hugetlb locking discussion:

"although I wonder if we still need the fault mutex array, given that we
now have mapping->invalidate_lock?"

While it likely cannot remove the mutex array entirely (concurrent page faults have to sync ... ), we can at least use it to fix this problem.

Hold mapping->invalidate_lock shared across the size check, allocation and page cache insertion or reservation rollback. Truncation takes it exclusively around i_size_write() only for now: it waits for concurrent allocations to finish updating the page-cache or rolling back reservations before changing the size. Subsequent allocations see the updated i_size.

Let truncation release the lock for now before unmapping and removing folios to preserve the existing lock ordering. Cached-folio faults and private allocations do not acquire the new lock.

Use it to synchronize with truncation, keeping the fault mutexes to serialize allocations for the same index.

Locking order is now:

fault mutex -> hugetlb VMA lock (read) -> invalidate lock (read) -> folio lock -> PTE lock

And on truncation:

i_rwsem (write) -> invalidate lock (write)

Add hugetlb_pgoff_valid() to not repeat the same size check multiple times. Memfd needs a bit of care, as it traditionally allowed partial folios to be pinned: the size check in memfd_pin_folios() allows for that.

Quoted 7 lines
Fixes 1c9e8def43a3 ("userfaultfd: hugetlbfs: add UFFDIO_COPY support for shared mappings")
Fixes 188a39725ad7 ("hugetlbfs: revert use i_mmap_rwsem to address page fault/truncate race")
Fixes 89c1905d9c14 ("mm/gup: introduce memfd_pin_folios() for pinning memfd folios")

Just one thing:

mm/rmap.c has a description of the lock ordering for hugetlb:

"
* hugetlbfs PageHuge() take locks in this order:
* hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
* vma_lock (hugetlb specific lock for pmd_sharing)
* mapping->i_mmap_rwsem (also used for hugetlb pmd sharing)
* folio_lock
"

We should update it to reflect the updated locking order, right?

Signature · 2 lines
Oscar Salvador
SUSE Labs
author maintainer
#36 lore raw

Re: [PATCH v2 08/15] mm/hugetlb: serialize page-cache allocations with truncation

Quoted 68 lines · Oscar Salvador (SUSE)
Quoted 45 lines · David Hildenbrand (Arm)

Truncation can remove an inode reservation while a fault is still allocating its folio. UFFDIO_COPY and memfd pinning can also consume reservations beyond the new i_size. This can underflow resv_huge_pages and leave folios beyond EOF.

The main issue is that truncation takes the fault mutex for folios in the page-cache, but it has no clue about faults that are still being processed concurrently.

Matthew Wilcox raised mapping->invalidate_lock in a different upstream hugetlb locking discussion:

"although I wonder if we still need the fault mutex array, given that we
now have mapping->invalidate_lock?"

While it likely cannot remove the mutex array entirely (concurrent page faults have to sync ... ), we can at least use it to fix this problem.

Hold mapping->invalidate_lock shared across the size check, allocation and page cache insertion or reservation rollback. Truncation takes it exclusively around i_size_write() only for now: it waits for concurrent allocations to finish updating the page-cache or rolling back reservations before changing the size. Subsequent allocations see the updated i_size.

Let truncation release the lock for now before unmapping and removing folios to preserve the existing lock ordering. Cached-folio faults and private allocations do not acquire the new lock.

Use it to synchronize with truncation, keeping the fault mutexes to serialize allocations for the same index.

Locking order is now:

fault mutex -> hugetlb VMA lock (read) -> invalidate lock (read) -> folio lock -> PTE lock

And on truncation:

i_rwsem (write) -> invalidate lock (write)

Add hugetlb_pgoff_valid() to not repeat the same size check multiple times. Memfd needs a bit of care, as it traditionally allowed partial folios to be pinned: the size check in memfd_pin_folios() allows for that.

Quoted 7 lines
Fixes 1c9e8def43a3 ("userfaultfd: hugetlbfs: add UFFDIO_COPY support for shared mappings")
Fixes 188a39725ad7 ("hugetlbfs: revert use i_mmap_rwsem to address page fault/truncate race")
Fixes 89c1905d9c14 ("mm/gup: introduce memfd_pin_folios() for pinning memfd folios")

Just one thing:

mm/rmap.c has a description of the lock ordering for hugetlb:

"
* hugetlbfs PageHuge() take locks in this order:
* hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
* vma_lock (hugetlb specific lock for pmd_sharing)
* mapping->i_mmap_rwsem (also used for hugetlb pmd sharing)
* folio_lock
"

Quoted 1 line

We should update it to reflect the updated locking order, right?

Indeed, thanks!

@Andrew, can you fault in the following:

From d050587df932067bcadb618cf8b72604bc9af58e Mon Sep 17 00:00:00 2001
From: "David Hildenbrand (Arm)" <[email protected]>
Date: Thu, 19 Nov 2026 17:57:41 +0100
Subject: [PATCH] fixup: mm/hugetlb: serialize page-cache allocations with
truncation

Update documented locking order in mm/rmap.c.

---
 mm/rmap.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/rmap.c +3 -2
index 0faef46806e5c..a452db02826e8 100644
@@ -48,8 +48,9 @@
  * hugetlbfs PageHuge() take locks in this order:
  *   hugetlb_fault_mutex (hugetlbfs specific page fault mutex)
  *     vma_lock (hugetlb specific lock for pmd_sharing)
- *       mapping->i_mmap_rwsem (also used for hugetlb pmd sharing)
- *         folio_lock
+ *       mapping->invalidate_lock (when allocating page cache folios)
+ *         mapping->i_mmap_rwsem (also used for hugetlb pmd sharing)
+ *           folio_lock
  */
 
 #include <linux/mm.h>
Signature · 7 lines
2.56.1


-- 
Cheers,

David
author maintainer
#37 lore raw

PATCH v2 9/15 mm/memfd: recheck the page cache before allocating a hugetlb folio

In reply to David Hildenbrand (Arm)

A concurrent fault or PIN request can populate the page cache after memfd_pin_folios() misses it in the page cache but before memfd_alloc_folio() takes the fault mutex. The latter still tries to allocate another folio and can return -ENOMEM even though the requested folio is already cached.

In particular, hugetlb_reserve_pages() finds the existing reservation-map entry and reserves nothing. If no global reservations remain, alloc_hugetlb_folio_reserve() fails even when the pool has free pages, effectively failing memfd_pin_folios().

Recheck the page cache before reserving or allocating. If the folio is present, drop the lookup reference and return -EEXIST so memfd_pin_folios() retries its lookup.

This is probably not worth backporting to stable.

Fixes 89c1905d9c14 ("mm/gup: introduce memfd_pin_folios() for pinning memfd folios")
---
 mm/memfd.c | 9 +++++++++
 1 file changed, 9 insertions(+)
mm/memfd.c +9 -0
index f03d12aa71f7a..276f4323b6bda 100644
@@ -102,6 +102,15 @@ struct folio *memfd_alloc_folio(struct file *memfd, pgoff_t idx)
 			goto out_unlock;
 		}
 
+		/* Let the caller retry if we raced with population. */
+		folio = filemap_get_folio(memfd->f_mapping,
+					  idx << huge_page_order(h));
+		if (!IS_ERR(folio)) {
+			folio_put(folio);
+			err = -EEXIST;
+			goto out_unlock;
+		}
+
 		nr_resv = hugetlb_reserve_pages(inode, idx, idx + 1, NULL, EMPTY_VMA_FLAGS);
 		if (nr_resv < 0) {
 			err = nr_resv;
Signature · 1 line
2.56.1
#38 lore raw

Re: [PATCH v2 09/15] mm/memfd: recheck the page cache before allocating a hugetlb folio

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

A concurrent fault or PIN request can populate the page cache after memfd_pin_folios() misses it in the page cache but before memfd_alloc_folio() takes the fault mutex. The latter still tries to allocate another folio and can return -ENOMEM even though the requested folio is already cached.

In particular, hugetlb_reserve_pages() finds the existing reservation-map entry and reserves nothing. If no global reservations remain, alloc_hugetlb_folio_reserve() fails even when the pool has free pages, effectively failing memfd_pin_folios().

Recheck the page cache before reserving or allocating. If the folio is present, drop the lookup reference and return -EEXIST so memfd_pin_folios() retries its lookup.

Quoted 6 lines

This is probably not worth backporting to stable.

Fixes 89c1905d9c14 ("mm/gup: introduce memfd_pin_folios() for pinning memfd folios")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
Tested-by on v2 9/15
#39 lore raw

Re: [PATCH v2 09/15] mm/memfd: recheck the page cache before allocating a hugetlb folio

In reply to David Hildenbrand (Arm)
Quoted 15 lines · David Hildenbrand (Arm)

A concurrent fault or PIN request can populate the page cache after memfd_pin_folios() misses it in the page cache but before memfd_alloc_folio() takes the fault mutex. The latter still tries to allocate another folio and can return -ENOMEM even though the requested folio is already cached.

In particular, hugetlb_reserve_pages() finds the existing reservation-map entry and reserves nothing. If no global reservations remain, alloc_hugetlb_folio_reserve() fails even when the pool has free pages, effectively failing memfd_pin_folios().

Recheck the page cache before reserving or allocating. If the folio is present, drop the lookup reference and return -EEXIST so memfd_pin_folios() retries its lookup.

Quoted 6 lines

This is probably not worth backporting to stable.

Fixes 89c1905d9c14 ("mm/gup: introduce memfd_pin_folios() for pinning memfd folios")

Reproduced using udmabuf to race and generated very consistent failures.

Signature · 1 line
~Gregory
Acked-by on v2 9/15
#40 lore raw

Re: [PATCH v2 09/15] mm/memfd: recheck the page cache before allocating a hugetlb folio

In reply to David Hildenbrand (Arm)
Quoted 15 lines · David Hildenbrand (Arm)

A concurrent fault or PIN request can populate the page cache after memfd_pin_folios() misses it in the page cache but before memfd_alloc_folio() takes the fault mutex. The latter still tries to allocate another folio and can return -ENOMEM even though the requested folio is already cached.

In particular, hugetlb_reserve_pages() finds the existing reservation-map entry and reserves nothing. If no global reservations remain, alloc_hugetlb_folio_reserve() fails even when the pool has free pages, effectively failing memfd_pin_folios().

Recheck the page cache before reserving or allocating. If the folio is present, drop the lookup reference and return -EEXIST so memfd_pin_folios() retries its lookup.

Quoted 6 lines

This is probably not worth backporting to stable.

Fixes 89c1905d9c14 ("mm/gup: introduce memfd_pin_folios() for pinning memfd folios")
Signature · 2 lines
Oscar Salvador
SUSE Labs
author maintainer
#41 lore raw

PATCH v2 10/15 mm/hugetlb: count again if the reserve map shrank

In reply to David Hildenbrand (Arm)

hugetlb_reserve_pages() asks region_chg() how many pages of the range are missing in the reserve map, charges the cgroup, the subpool and the pool for that many, and then lets region_add() fill the gaps.

It copes with region_add() adding less, because a concurrent fault added an entry in the meantime; however, it does not expect it to add more.

Since restore_reserve_on_error() can delete the entry of an allocation that failed later on, entries also disappear without the inode lock that mmap() holds. For a previously unreserved page, UFFDIO_COPY can do this when the source is not resident: it allocates a folio, which adds the entry, fails to copy with page faults disabled, and takes both back. memfd_alloc_folio() does it when it has made a reservation and gets no folio it may pin.

If region_chg() sees such an entry and region_add() does not, an entry is added that nothing was charged for. When we later delete it, we decrement resv_huge_pages and uncharge the cgroup once too often:

  WARNING: mm/page_counter.c:60 at page_counter_uncharge+0xe2/0x160

Similarly, HugePages_Rsvd will underflow.

Tell region_add() how much has been accounted for and let it refuse to add more. Convert it to a region_add_limited() for that purpose. hugetlb_reserve_pages() then undoes what it has done, as for any other failure of region_add(), and starts again.

Note that we move hugetlb_vma_lock_free() so we can retain the allocated VMA lock object as we retry.

Limit retries to 10 to avoid livelock under repeated concurrent rollbacks. Return -ENOMEM if the retries are exhausted.

Fixes 846be08578ed ("mm/hugetlb: expand restore_reserve_on_error functionality")
---
 mm/hugetlb.c | 58 ++++++++++++++++++++++++++++++++++++++++++++--------------
 1 file changed, 44 insertions(+), 14 deletions(-)
mm/hugetlb.c +44 -14
index 3d8eebdca5136..112fa25f36833 100644
@@ -739,26 +739,36 @@ static int allocate_file_region_entries(struct resv_map *resv,
  * region_del.  The extra needed entries will be allocated.
  *
  * regions_needed is the out value provided by a previous call to region_chg.
+ * limit is what the caller has accounted for.  If more huge pages would have
+ * to be added, because somebody has deleted from the range since region_chg,
+ * nothing is added and -EAGAIN is returned.
  *
  * Return the number of new huge pages added to the map.  This number is greater
  * than or equal to zero.  If file_region entries needed to be allocated for
  * this operation and we were not able to allocate, it returns -ENOMEM.
- * region_add of regions of length 1 never allocate file_regions and cannot
- * fail; region_chg will always allocate at least 1 entry and a region_add for
- * 1 page will only require at most 1 entry.
+ * Ranges of length 1 never require allocating file_regions and cannot fail
+ * if limit is at least 1; region_chg will always allocate at least 1 entry
+ * and adding 1 page will only require at most 1 entry.
  */
-static long region_add(struct resv_map *resv, long f, long t,
-		       long in_regions_needed, struct hstate *h,
-		       struct hugetlb_cgroup *h_cg)
+static long region_add_limited(struct resv_map *resv, long f, long t,
+		long in_regions_needed, struct hstate *h,
+		struct hugetlb_cgroup *h_cg, long limit)
 {
 	long add = 0, actual_regions_needed = 0;
 
 	spin_lock(&resv->lock);
 retry:
 
-	/* Count how many regions are actually needed to execute this add. */
-	add_reservation_in_range(resv, f, t, NULL, NULL,
-				 &actual_regions_needed);
+	/*
+	 * Count how many regions are actually needed to execute this add.
+	 * Fail if the number of huge pages to add exceeds limit.
+	 */
+	add = add_reservation_in_range(resv, f, t, NULL, NULL,
+				       &actual_regions_needed);
+	if (add > limit) {
+		spin_unlock(&resv->lock);
+		return -EAGAIN;
+	}
 
 	/*
 	 * Check for sufficient descriptors in the cache to accommodate
@@ -794,6 +804,13 @@ static long region_add(struct resv_map *resv, long f, long t,
 	return add;
 }
 
+static long region_add(struct resv_map *resv, long f, long t,
+		long in_regions_needed, struct hstate *h,
+		struct hugetlb_cgroup *h_cg)
+{
+	return region_add_limited(resv, f, t, in_regions_needed, h, h_cg, t - f);
+}
+
 /*
  * Examine the existing reserve map and determine how many
  * huge pages in the specified range [f, t) are NOT currently
@@ -6847,7 +6864,7 @@ long hugetlb_reserve_pages(struct inode *inode,
 	struct resv_map *resv_map;
 	struct hugetlb_cgroup *h_cg = NULL;
 	long gbl_reserve, regions_needed = 0;
-	int err;
+	int err, retries = 0;
 
 	/* This should never happen */
 	if (from > to) {
@@ -6869,6 +6886,7 @@ long hugetlb_reserve_pages(struct inode *inode,
 	if (vma_flags_test(&vma_flags, VMA_NORESERVE_BIT))
 		return 0;
 
+retry:
 	/*
 	 * Shared mappings base their reservation on the number of pages that
 	 * are already allocated on behalf of the file. Private mappings need
@@ -6947,7 +6965,8 @@ long hugetlb_reserve_pages(struct inode *inode,
 	 * else has to be done for private mappings here
 	 */
 	if (!vma || vma_test(vma, VMA_MAYSHARE_BIT)) {
-		add = region_add(resv_map, from, to, regions_needed, h, h_cg);
+		add = region_add_limited(resv_map, from, to, regions_needed, h,
+					 h_cg, chg);
 
 		if (unlikely(add < 0)) {
 			hugetlb_acct_memory(h, -gbl_reserve);
@@ -7010,17 +7029,28 @@ long hugetlb_reserve_pages(struct inode *inode,
 	hugetlb_cgroup_uncharge_cgroup_rsvd(hstate_index(h),
 					    chg * pages_per_huge_page(h), h_cg);
 out_err:
-	hugetlb_vma_lock_free(vma);
-	if (!vma || vma_test(vma, VMA_MAYSHARE_BIT))
+	if (!vma || vma_test(vma, VMA_MAYSHARE_BIT)) {
 		/* Only call region_abort if the region_chg succeeded but the
 		 * region_add failed or didn't run.
 		 */
 		if (chg >= 0 && add < 0)
 			region_abort(resv_map, from, to, regions_needed);
-	if (vma && is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
+		/*
+		 * A concurrent rollback removed entries after region_chg()
+		 * counted the range, so we charged for too few pages and
+		 * have to recount, recharge, and try again. Limit retries
+		 * to avoid livelock under repeated rollbacks.
+		 */
+		if (err == -EAGAIN) {
+			if (retries++ < 10)
+				goto retry;
+			err = -ENOMEM;
+		}
+	} else if (is_vma_resv_set(vma, HPAGE_RESV_OWNER)) {
 		kref_put(&resv_map->refs, resv_map_release);
 		set_vma_resv_map(vma, NULL);
 	}
+	hugetlb_vma_lock_free(vma);
 	return err;
 }
 
Signature · 1 line
2.56.1
#42 lore raw

Re: [PATCH v2 10/15] mm/hugetlb: count again if the reserve map shrank

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

hugetlb_reserve_pages() asks region_chg() how many pages of the range are missing in the reserve map, charges the cgroup, the subpool and the pool for that many, and then lets region_add() fill the gaps.

It copes with region_add() adding less, because a concurrent fault added an entry in the meantime; however, it does not expect it to add more.

Since restore_reserve_on_error() can delete the entry of an allocation that failed later on, entries also disappear without the inode lock that mmap() holds. For a previously unreserved page, UFFDIO_COPY can do this when the source is not resident: it allocates a folio, which adds the entry, fails to copy with page faults disabled, and takes both back. memfd_alloc_folio() does it when it has made a reservation and gets no folio it may pin.

Quoted 6 lines

[ ... ]

Fixes 846be08578ed ("mm/hugetlb: expand restore_reserve_on_error functionality")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
author maintainer
#43 lore raw

PATCH v2 11/15 hugetlbfs: do not grow a sealed file in mmap()

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

hugetlbfs_file_mmap() grows a file when a writable mapping extends beyond EOF. We are missing seal checks similar to hugetlbfs_setattr() and hugetlbfs_fallocate(), allowing a user to grow a file that has F_SEAL_GROW set.

To fix it, skip the resize when F_SEAL_GROW is set; mmap() still succeeds without growing the file.

We currently also allow CoW mappings to grow a file. Disallowing this, maybe even only for read-only file descriptors, could break existing userspace, so we have to be more careful. QEMU's file backend is an example user that might rely on such things, and would suddenly start getting SIGBUS when faulting in memory outside EOF.

So be careful and focus on F_SEAL_GROW for now.

Fix generated by an LLM and sent by Chris Mason in private.

Fixes ff62a3421044 ("hugetlb: implement memfd sealing")
[ david: drop comment; simplify+extend description ]
---
 fs/hugetlbfs/inode.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/hugetlbfs/inode.c +2 -1
index 7f64bdc07aa80..68761e1ed4d2e 100644
@@ -157,7 +157,8 @@ static int hugetlbfs_file_mmap(struct file *file, struct vm_area_struct *vma)
 		goto out;
 
 	ret = 0;
-	if (vma_test(vma, VMA_WRITE_BIT) && inode->i_size < len)
+	if (vma_test(vma, VMA_WRITE_BIT) && inode->i_size < len &&
+	    !(HUGETLBFS_I(inode)->seals & F_SEAL_GROW))
 		i_size_write(inode, len);
 out:
 	inode_unlock(inode);
Signature · 1 line
2.56.1
#44 lore raw

Re: [PATCH v2 11/15] hugetlbfs: do not grow a sealed file in mmap()

Sashiko has reviewed this patch and found no issues.
Quoted 20 lines

From: Chris Mason <[email protected]>

hugetlbfs_file_mmap() grows a file when a writable mapping extends beyond EOF. We are missing seal checks similar to hugetlbfs_setattr() and hugetlbfs_fallocate(), allowing a user to grow a file that has F_SEAL_GROW set.

To fix it, skip the resize when F_SEAL_GROW is set; mmap() still succeeds without growing the file.

We currently also allow CoW mappings to grow a file. Disallowing this, maybe even only for read-only file descriptors, could break existing userspace, so we have to be more careful. QEMU's file backend is an example user that might rely on such things, and would suddenly start getting SIGBUS when faulting in memory outside EOF.

So be careful and focus on F_SEAL_GROW for now.

Fix generated by an LLM and sent by Chris Mason in private.

Quoted 7 lines
Fixes ff62a3421044 ("hugetlb: implement memfd sealing")
[ david: drop comment; simplify+extend description ]

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
Acked-by on v2 11/15
#45 lore raw

Re: [PATCH v2 11/15] hugetlbfs: do not grow a sealed file in mmap()

In reply to David Hildenbrand (Arm)
Quoted 20 lines · David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

hugetlbfs_file_mmap() grows a file when a writable mapping extends beyond EOF. We are missing seal checks similar to hugetlbfs_setattr() and hugetlbfs_fallocate(), allowing a user to grow a file that has F_SEAL_GROW set.

To fix it, skip the resize when F_SEAL_GROW is set; mmap() still succeeds without growing the file.

We currently also allow CoW mappings to grow a file. Disallowing this, maybe even only for read-only file descriptors, could break existing userspace, so we have to be more careful. QEMU's file backend is an example user that might rely on such things, and would suddenly start getting SIGBUS when faulting in memory outside EOF.

So be careful and focus on F_SEAL_GROW for now.

Fix generated by an LLM and sent by Chris Mason in private.

Quoted 7 lines
Fixes ff62a3421044 ("hugetlb: implement memfd sealing")
[ david: drop comment; simplify+extend description ]
Quoted 22 lines
---
 fs/hugetlbfs/inode.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/hugetlbfs/inode.c +2 -1
index 7f64bdc07aa80..68761e1ed4d2e 100644
@@ -157,7 +157,8 @@ static int hugetlbfs_file_mmap(struct file *file, struct vm_area_struct *vma)
 		goto out;
 
 	ret = 0;
-	if (vma_test(vma, VMA_WRITE_BIT) && inode->i_size < len)
+	if (vma_test(vma, VMA_WRITE_BIT) && inode->i_size < len &&
+	    !(HUGETLBFS_I(inode)->seals & F_SEAL_GROW))
 		i_size_write(inode, len);
 out:
 	inode_unlock(inode);
Signature · 2 lines
-- 
2.56.1
Signature · 2 lines
Oscar Salvador
SUSE Labs
author maintainer
#46 lore raw

PATCH v2 12/15 mm/hugetlb: keep surplus folios that are reserved

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

free_huge_folio() may restore a reservation, but still returns the folio to the page allocator if its node has surplus huge pages.

For example, start with no hugetlb folios and allow one surplus 2 MiB folio:

1. Mount hugetlbfs with pagesize=2M,min_size=2M. This allocates and reserves one surplus folio: free=1, reserved=1.
2. Create a 2 MiB file and write to a shared mapping of it. The fault consumes the folio and its reservation: free=0, reserved=0.
3. Unmap the file and truncate it to zero. The mount's reservation is restored, but the surplus folio is freed: free=0, reserved=1.

Besides losing a hugetlb folio that is required for a reservation, this can also make available_huge_pages() underflow and cause other issues.

Keep the folio in the pool if it is needed to cover reservations, including any reservation we just restored.

Fix generated by an LLM and sent by Chris Mason in private.

Fixes 07443a85ad90 ("mm, hugetlb: return a reserved page to a reserved pool if failed")
[ david: simplify comment and description ]
---
 mm/hugetlb.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
mm/hugetlb.c +3 -2
index 112fa25f36833..2fd5a5e585ad5 100644
@@ -1778,8 +1778,9 @@ void free_huge_folio(struct folio *folio)
 		remove_hugetlb_folio(h, folio, false);
 		spin_unlock_irqrestore(&hugetlb_lock, flags);
 		update_and_free_hugetlb_folio(h, folio, true);
-	} else if (h->surplus_huge_pages_node[nid]) {
-		/* remove the page from active list */
+	} else if (h->surplus_huge_pages_node[nid] &&
+		   h->free_huge_pages >= h->resv_huge_pages) {
+		/* Free this surplus folio that is not required globally. */
 		remove_hugetlb_folio(h, folio, true);
 		spin_unlock_irqrestore(&hugetlb_lock, flags);
 		update_and_free_hugetlb_folio(h, folio, true);
Signature · 1 line
2.56.1
#47 lore raw

Re: [PATCH v2 12/15] mm/hugetlb: keep surplus folios that are reserved

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

From: Chris Mason <[email protected]>

free_huge_folio() may restore a reservation, but still returns the folio to the page allocator if its node has surplus huge pages.

For example, start with no hugetlb folios and allow one surplus 2 MiB folio:

1. Mount hugetlbfs with pagesize=2M,min_size=2M. This allocates and reserves one surplus folio: free=1, reserved=1.
2. Create a 2 MiB file and write to a shared mapping of it. The fault consumes the folio and its reservation: free=0, reserved=0.
3. Unmap the file and truncate it to zero. The mount's reservation is restored, but the surplus folio is freed: free=0, reserved=1.

Quoted 6 lines

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
Acked-by on v2 12/15
#48 lore raw

Re: [PATCH v2 12/15] mm/hugetlb: keep surplus folios that are reserved

In reply to David Hildenbrand (Arm)
Quoted 23 lines · David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

free_huge_folio() may restore a reservation, but still returns the folio to the page allocator if its node has surplus huge pages.

For example, start with no hugetlb folios and allow one surplus 2 MiB folio:

1. Mount hugetlbfs with pagesize=2M,min_size=2M. This allocates and reserves one surplus folio: free=1, reserved=1.
2. Create a 2 MiB file and write to a shared mapping of it. The fault consumes the folio and its reservation: free=0, reserved=0.
3. Unmap the file and truncate it to zero. The mount's reservation is restored, but the surplus folio is freed: free=0, reserved=1.

Besides losing a hugetlb folio that is required for a reservation, this can also make available_huge_pages() underflow and cause other issues.

Keep the folio in the pool if it is needed to cover reservations, including any reservation we just restored.

Fix generated by an LLM and sent by Chris Mason in private.

Quoted 8 lines
Fixes 07443a85ad90 ("mm, hugetlb: return a reserved page to a reserved pool if failed")
[ david: simplify comment and description ]
Signature · 2 lines
Oscar Salvador
SUSE Labs
author maintainer
#49 lore raw

PATCH v2 13/15 mm/hugetlb: fix reservation leak on min_size= mounts

In reply to David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

Failed allocations for CoW mappings can leak reservations on hugetlbfs mounts with min_size= and no size=. The leaked reservations survive unmount.

Note that this is only an accounting error and not a memory leak.

HPG_restore_reserve makes free_huge_folio() restore the global reservation without returning it to the subpool. This assumes the reserve map holds the reservation. However, a CoW mapping may have no reserve map, or the map may already account for another folio at the same index.

Commit 58db7c5fbe7d ("mm/hugetlb: fix avoid_reserve to allow taking folio from subpool") allowed owner CoW allocations to consume subpool reservations. Commit 51e1de00acdb ("mm/hugetlb: simplify vma_has_reserves()") later extended this to CoW mappings without a reserve map.

For example, with a subpool minimum of one page and a MAP_PRIVATE|MAP_NORESERVE mapping:

subpool global
rsv_hpages resv_huge_pages

  1. Mount                             1             1
  2. Allocate using subpool reserve    0             0
  3. Free on error with flag set       0             1
  4. Allocate without a reservation    0             1
  5. Free and return to subpool        1             2

Call folio_clear_hugetlb_restore_reserve() for CoW mappings when map_chg != MAP_CHG_REUSE, meaning no reserve-map reservation was consumed. This lets free_huge_folio() return subpool reservations to the subpool on error.

Do not set the flag again if region-cache allocation fails during
rollback: that would undo the flag clearing and skip returning the reservation to the subpool. This also fixes the older case where setting the flag invents a reservation for an unreserved allocation for a CoW mapping.

The doc still mentions PagePrivate at various places: future work should clean that up.

Fix generated by an LLM and sent by Chris Mason in private.

Fixes 846be08578ed ("mm/hugetlb: expand restore_reserve_on_error functionality")
Fixes 58db7c5fbe7d ("mm/hugetlb: fix avoid_reserve to allow taking folio from subpool")
[ david: simplify comments and improve description; updated Fixes ]
---
 Documentation/mm/hugetlbfs_reserv.rst | 25 ++++++++++++++-----------
 include/linux/hugetlb.h               |  2 ++
 mm/hugetlb.c                          | 34 +++++++++++++++-------------------
 3 files changed, 31 insertions(+), 30 deletions(-)
Documentation/mm/hugetlbfs_reserv.rst +14 -11
index a49115db18c76..fbca6625ca50d 100644
@@ -201,10 +201,10 @@ The value returned from vma_needs_reservation() is generally
 If a reservation does not exist, and there is a subpool associated with the
 mapping the subpool is consulted to determine if it contains reservations.
 If the subpool contains reservations, one can be used for this allocation.
-However, in every case the avoid_reserve argument overrides the use of
-a reservation for the allocation.  After determining whether a reservation
-exists and can be used for the allocation, the routine dequeue_huge_page_vma()
-is called.  This routine takes two arguments related to reservations:
+However, avoid_reserve only applies to reservations from the reservation map.
+After determining whether a reservation exists and can be used for the
+allocation, the routine dequeue_huge_page_vma() is called.  This routine takes
+two arguments related to reservations:
 
 - avoid_reserve, this is the same value/argument passed to
   alloc_hugetlb_folio().
@@ -256,6 +256,10 @@ compensate.  See the section
 :ref:`Reservation Map Helper Routines <resv_map_helpers>` for more
 information on these routines.
 
+For CoW mappings, alloc_hugetlb_folio() calls
+folio_clear_hugetlb_restore_reserve() if the reservation came from the subpool.
+This makes free_huge_folio() return the reservation to the subpool on error.
+
 
 Instantiate Huge Pages
 ======================
@@ -284,14 +288,13 @@ be adjusted (see the section
 :ref:`Consuming Reservations/Allocating a Huge Page <consume_resv>`
 for information on how these are set).
 
-The routine first calls hugepage_subpool_put_pages() for the page.  If this
-routine returns a value of 0 (which does not equal the value passed 1) it
-indicates reserves are associated with the subpool, and this newly free page
-must be used to keep the number of subpool reserves above the minimum size.
-Therefore, the global resv_huge_pages counter is incremented in this case.
+If folio_test_hugetlb_restore_reserve() is false, hugepage_subpool_put_pages()
+returns the page to the subpool.  A return value of 0 means the page must restore
+a subpool reservation, so the global resv_huge_pages counter is incremented.
 
-If the PagePrivate flag was set in the page, the global resv_huge_pages counter
-will always be incremented.
+Otherwise, resv_huge_pages is incremented without calling
+hugepage_subpool_put_pages(): the restored reservation still counts as used in
+the subpool.
 
 .. _sub_pool_resv:
 
include/linux/hugetlb.h +2 -0
index 1d2dd10074d7a..0d5414392d870 100644
@@ -590,6 +590,8 @@ hugetlb_get_unmapped_area(struct file *file, unsigned long addr,
  * HPG_restore_reserve - Set when a hugetlb page consumes a reservation at
  *	allocation time.  Cleared when page is fully instantiated.  Free
  *	routine checks flag to restore a reservation on error paths.
+ *	Cleared when allocating for a CoW mapping using a subpool
+ *	reservation, which the free routine returns to the subpool.
  *	Synchronization:  Examined or modified by code that knows it has
  *	the only reference to page.  i.e. After allocation but before use
  *	or when the page is being freed.
mm/hugetlb.c +15 -19
index 2fd5a5e585ad5..6e79dedfc0fd6 100644
@@ -2635,7 +2635,7 @@ static long vma_del_reservation(struct hstate *h,
  * 1) A reservation was in place and the folio consumed the reservation.
  *    hugetlb_restore_reserve is set in the folio.
  * 2) No reservation was in place for the page, so hugetlb_restore_reserve is
- *    not set.  However, alloc_hugetlb_folio always updates the reserve map.
+ *    not set.  However, alloc_hugetlb_folio may have updated the reserve map.
  *
  * In case 1, free_huge_folio later in the error path will increment the
  * global reserve count.  But, free_huge_folio does not have enough context
@@ -2645,6 +2645,10 @@ static long vma_del_reservation(struct hstate *h,
  * reserve map indicates there is a reservation present.
  *
  * In case 2, simply undo reserve map modifications done by alloc_hugetlb_folio.
+ *
+ * For CoW mappings, allocations using a subpool reservation leave the
+ * flag clear and the reserve map unchanged.  free_huge_folio returns the
+ * reservation to the subpool.
  */
 void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma,
 			unsigned long address, struct folio *folio)
@@ -2692,25 +2696,9 @@ void restore_reserve_on_error(struct hstate *h, struct vm_area_struct *vma,
 				folio_set_hugetlb_restore_reserve(folio);
 		} else if (rc < 0) {
 			/*
-			 * Rare out of memory condition from
-			 * vma_needs_reservation call.  Memory allocation is
-			 * only attempted if a new entry is needed.  Therefore,
-			 * this implies there is not an entry in the
-			 * reserve map.
-			 *
-			 * For shared mappings, no entry in the map indicates
-			 * no reservation.  We are done.
+			 * Region cache allocation can fail even if an entry exists.
+			 * Leave the flag and reserve map unchanged.
 			 */
-			if (!(vma->vm_flags & VM_MAYSHARE))
-				/*
-				 * For private mappings, no entry indicates
-				 * a reservation is present.  Since we can
-				 * not add an entry, set hugetlb_restore_reserve
-				 * on the folio so reserve count will be
-				 * incremented when freed.  This reserve will
-				 * be consumed on a subsequent allocation.
-				 */
-				folio_set_hugetlb_restore_reserve(folio);
 		} else {
 			/*
 			 * No reservation present, do nothing
@@ -3165,6 +3153,14 @@ struct folio *alloc_hugetlb_folio(struct vm_area_struct *vma,
 		}
 	}
 
+	/*
+	 * Return subpool reservations to the subpool on error. A CoW mapping
+	 * might not have a reserve map, or it might already account for
+	 * another folio at this index.
+	 */
+	if (map_chg != MAP_CHG_REUSE && vma_is_cow_mapping(vma))
+		folio_clear_hugetlb_restore_reserve(folio);
+
 	return folio;
 
 out_subpool_put:
Signature · 1 line
2.56.1
#50 lore raw

Re: [PATCH v2 13/15] mm/hugetlb: fix reservation leak on min_size= mounts

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

From: Chris Mason <[email protected]>

Failed allocations for CoW mappings can leak reservations on hugetlbfs mounts with min_size= and no size=. The leaked reservations survive unmount.

Note that this is only an accounting error and not a memory leak.

HPG_restore_reserve makes free_huge_folio() restore the global reservation without returning it to the subpool. This assumes the reserve map holds the reservation. However, a CoW mapping may have no reserve map, or the map may already account for another folio at the same index.

Quoted 7 lines

Commit 58db7c5fbe7d ("mm/hugetlb: fix avoid_reserve to allow taking

[ ... ]
[ david: simplify comments and improve description; updated Fixes ]

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=13
Acked-by on v2 13/15
#51 lore raw

Re: [PATCH v2 13/15] mm/hugetlb: fix reservation leak on min_size= mounts

In reply to David Hildenbrand (Arm)
Quoted 47 lines · David Hildenbrand (Arm)

From: Chris Mason <[email protected]>

Failed allocations for CoW mappings can leak reservations on hugetlbfs mounts with min_size= and no size=. The leaked reservations survive unmount.

Note that this is only an accounting error and not a memory leak.

HPG_restore_reserve makes free_huge_folio() restore the global reservation without returning it to the subpool. This assumes the reserve map holds the reservation. However, a CoW mapping may have no reserve map, or the map may already account for another folio at the same index.

Commit 58db7c5fbe7d ("mm/hugetlb: fix avoid_reserve to allow taking folio from subpool") allowed owner CoW allocations to consume subpool reservations. Commit 51e1de00acdb ("mm/hugetlb: simplify vma_has_reserves()") later extended this to CoW mappings without a reserve map.

For example, with a subpool minimum of one page and a MAP_PRIVATE|MAP_NORESERVE mapping:

subpool global
rsv_hpages resv_huge_pages

  1. Mount                             1             1
  2. Allocate using subpool reserve    0             0
  3. Free on error with flag set       0             1
  4. Allocate without a reservation    0             1
  5. Free and return to subpool        1             2

Call folio_clear_hugetlb_restore_reserve() for CoW mappings when map_chg != MAP_CHG_REUSE, meaning no reserve-map reservation was consumed. This lets free_huge_folio() return subpool reservations to the subpool on error.

Do not set the flag again if region-cache allocation fails during
rollback: that would undo the flag clearing and skip returning the reservation to the subpool. This also fixes the older case where setting the flag invents a reservation for an unreserved allocation for a CoW mapping.

The doc still mentions PagePrivate at various places: future work should clean that up.

Fix generated by an LLM and sent by Chris Mason in private.

Quoted 8 lines
Fixes 846be08578ed ("mm/hugetlb: expand restore_reserve_on_error functionality")
Fixes 58db7c5fbe7d ("mm/hugetlb: fix avoid_reserve to allow taking folio from subpool")
[ david: simplify comments and improve description; updated Fixes ]
Signature · 2 lines
Oscar Salvador
SUSE Labs
author maintainer
#52 lore raw

PATCH v2 14/15 mm/hugetlb: account restored reservations before freeing folios

In reply to David Hildenbrand (Arm)

Unmapping an anonymous folio restores its private VMA reservation immediately, but the global reservation count is only restored when the folio is freed.

If any folio reference delays freeing, closing the VMA or refaulting can decrement resv_huge_pages before it was incremented. This can underflow the counter or hide another mapping's reservation, allowing an unreserved allocation to consume its backing.

Increment resv_huge_pages when restoring the reserve map instead. Detach the folio from its subpool, since the restored reservation now owns that charge. Leave the restore-reserve flag clear so freeing the folio does not repeat the accounting. The folio only becomes free after its last reference is dropped.

Reservations can now temporarily outnumber free folios. Clamp available pages to zero in that case, including for demotion, and limit releases of pooled surplus pages to that availability so they cannot remove backing for remaining reservations.

Use the same clamped availability when gathering surplus pages for a new reservation. An existing deficit can be backed by unmapped folios that are still referenced, so do not allocate replacement backing for it as part of the new request. Otherwise, the request can allocate unnecessary surplus pages or fail even when the overcommit limit has room for the new reservation.

Free unused or aborted surplus allocations directly instead of passing them to free_huge_folio(), which could retain them to cover the existing deficit. These isolated folios have not backed any committed reservation. Preserve pages promoted to persistent capacity by a concurrent pool resize, and use the bulk freeing path to retain vmemmap restoration error handling.

Restore reservations even when surplus pages exist. free_huge_folio() already retains pages needed to back them. It is unclear why that was really added. The comment about i_mmap_lock_write can go as well, that doesn't really help for anonymous folios.

Two existing problems remain:

1) Anonymous hugetlb migration temporarily drops the mapcount. A concurrent unmap can observe zero and restore a reservation even though migration will reinstall a mapping. i_mmap_lock_write() does not protect anonymous folio mapcounts, so it does not prevent this race. This change fixes the resulting counter underflow, but leaves premature restoration possible, leading to (2). Maybe that anon_vma lock can help?

2) A fault can allocate a replacement folio using the restored reservation before the old folio is freed. Repeated vmsplice(), MADV_DONTNEED and refaults can retain multiple folios for one reservation and consume pages backing other reservations. This was already possible; counter accounting is now fixed, but early reuse remains. Removing the surplus check also allows it after unmaps that previously skipped restoration.

Deferring reservation-map restoration until the final put is tricky:
free_huge_folio() has no VMA context to update the private reserve map, and that VMA may already have been destroyed.

Fixes df7a6d1f6405 ("mm/hugetlb: restore the reservation if needed")
---
 Documentation/mm/hugetlbfs_reserv.rst |   5 +-
 mm/hugetlb.c                          | 125 ++++++++++++++++++----------------
 mm/hugetlb_internal.h                 |  24 +++++++
 mm/hugetlb_sysfs.c                    |   2 +-
 4 files changed, 95 insertions(+), 61 deletions(-)
Documentation/mm/hugetlbfs_reserv.rst +3 -2
index fbca6625ca50d..4711029bd067d 100644
@@ -34,7 +34,8 @@ resv_huge_pages
 	This is a global (per-hstate) count of reserved huge pages.  Reserved
 	huge pages are only available to the task which reserved them.
 	Therefore, the number of huge pages generally available is computed
-	as (``free_huge_pages - resv_huge_pages``).
+	as (``free_huge_pages - resv_huge_pages``), clamped to zero when
+	reservations outnumber free huge pages.
 Reserve Map
 	A reserve map is described by the structure::
 
@@ -155,7 +156,7 @@ are enough free huge pages to accommodate the reservation.  If there are,
 the global reservation count resv_huge_pages is adjusted something like the
 following::
 
-	if (resv_needed <= (free_huge_pages - resv_huge_pages)
+	if (resv_needed <= available_huge_pages(h))
 		resv_huge_pages += resv_needed;
 
 Note that the global lock hugetlb_lock is held when checking and adjusting
mm/hugetlb.c +67 -58

176 lines not on this page · raw message

mm/hugetlb_internal.h +24 -0
index 1d2f870deccfe..201028e08a46a 100644
@@ -10,6 +10,30 @@
 #include <linux/hugetlb.h>
 #include <linux/hugetlb_cgroup.h>
 
+/**
+ * available_huge_pages - number of free huge pages not needed for reservations
+ * @h: huge page size state
+ *
+ * Global number of free huge pages that are not needed for existing
+ * reservations, available for allocations without reservations. Things like
+ * NUMA placement, cpusets, mempolicy and the usability of individual folios can
+ * further restrict allocation.
+ *
+ * Reservations of anon folios may be restored before their backing folios are
+ * actually freed, so the number of reserved pages can be bigger than the
+ * number of free pages. In such a scenario, the result is clamped to 0.
+ *
+ * Return: The number of free huge pages not needed for reservations.
+ */
+static inline unsigned long available_huge_pages(const struct hstate *h)
+{
+	lockdep_assert_held(&hugetlb_lock);
+
+	if (h->resv_huge_pages > h->free_huge_pages)
+		return 0;
+	return h->free_huge_pages - h->resv_huge_pages;
+}
+
 /*
  * Check if the hstate represents gigantic pages but gigantic page
  * runtime support is not available. This is a common condition used to
mm/hugetlb_sysfs.c +1 -1
index c89e4c8475756..9e0c5d3d0fcb6 100644
@@ -211,7 +211,7 @@ static ssize_t demote_store(struct kobject *kobj,
 		 * Check for available pages to demote each time thorough the
 		 * loop as demote_pool_huge_page will drop hugetlb_lock.
 		 */
-		nr_available = h->free_huge_pages - h->resv_huge_pages;
+		nr_available = available_huge_pages(h);
 		if (nid != NUMA_NO_NODE)
 			nr_available = min(nr_available,
 					   h->free_huge_pages_node[nid]);
Signature · 1 line
2.56.1
#53 lore raw

Re: [PATCH v2 14/15] mm/hugetlb: account restored reservations before freeing folios

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

Unmapping an anonymous folio restores its private VMA reservation immediately, but the global reservation count is only restored when the folio is freed.

If any folio reference delays freeing, closing the VMA or refaulting can decrement resv_huge_pages before it was incremented. This can underflow the counter or hide another mapping's reservation, allowing an unreserved allocation to consume its backing.

Increment resv_huge_pages when restoring the reserve map instead. Detach the folio from its subpool, since the restored reservation now owns that charge. Leave the restore-reserve flag clear so freeing the folio does not repeat the accounting. The folio only becomes free after its last reference is dropped.

Quoted 6 lines

[ ... ]

Fixes df7a6d1f6405 ("mm/hugetlb: restore the reservation if needed")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
author maintainer
#54 lore raw

PATCH v2 15/15 mm/hugetlb: delay anon folio rmap removal until after the TLB flush

In reply to David Hildenbrand (Arm)

After fork(), parent and child map anonymous folios read-only shared by CoW. On a write fault, hugetlb_wp() reuses an anonymous page instead of copying it if its mapcount is 1. As documented, switching to the safer refcount would cause more harm than help with these scarce resources.

munmap() and MADV_DONTNEED unmap such folios and decrement the mapcount before the TLB is flushed. Until then, another thread of the process can still read the page through a stale TLB entry:

    child: reader        child: munmap()       parent: writer
    =============        ===============       ==============

reads the page
clears the entry
mapcount drops to 1
store to the page
hugetlb_wp() reuses it
reads the store
/* leak */
flushes the TLB

Similar observations are also known and possible with things like vmsplice().

Extend the mmu_gather delayed-rmap machinery to handle hugetlb folios. Defer anonymous hugetlb rmap removal until after the batched TLB flush.

Flush the TLB and remove pending rmaps when the batch fills and before leaving the VMA, then drain the batch so later rmap flushes cannot process the same entries again. This is very similar to how zap_present_ptes() operates.

Skip deferral at exit. On UP, flush before removing the rmap. With MMU_GATHER_NO_GATHER, clearing the entry already flushes the TLB.

Restore reservations after the actual rmap removal, preserving the existing mapcount check.

This is very likely not stable-worthy, as hugetlb is commonly not used for applications with different parent vs. child trust boundaries.

Fixes 24669e58477e ("hugetlb: use mmu_gather instead of a temporary linked list for accumulating pages")
---
 arch/s390/include/asm/tlb.h |  5 +++--
 include/asm-generic/tlb.h   |  5 +++--
 mm/hugetlb.c                | 39 ++++++++++++++++++++++++++++++++++-----
 mm/internal.h               |  9 +++++++++
 mm/mmu_gather.c             | 16 ++++++++++++----
 5 files changed, 61 insertions(+), 13 deletions(-)
arch/s390/include/asm/tlb.h +3 -2
index 619fd41e710e9..3408ee400d23e 100644
@@ -24,7 +24,7 @@
 
 static inline void tlb_flush(struct mmu_gather *tlb);
 static inline bool __tlb_remove_page_size(struct mmu_gather *tlb,
-		struct page *page, int page_size);
+		struct page *page, int page_size, bool delay_rmap);
 static inline bool __tlb_remove_folio_pages(struct mmu_gather *tlb,
 		struct page *page, unsigned int nr_pages, bool delay_rmap);
 
@@ -45,8 +45,9 @@ static inline bool __tlb_remove_folio_pages(struct mmu_gather *tlb,
  * s390 doesn't delay rmap removal.
  */
 static inline bool __tlb_remove_page_size(struct mmu_gather *tlb,
-		struct page *page, int page_size)
+		struct page *page, int page_size, bool delay_rmap)
 {
+	VM_WARN_ON_ONCE(delay_rmap);
 	free_folio_and_swap_cache(page_folio(page));
 	return false;
 }
include/asm-generic/tlb.h +3 -2
index 3f4a180b48f3c..476fa3495eb29 100644
@@ -245,7 +245,8 @@ struct mmu_gather_batch {
  */
 #define MAX_GATHER_BATCH_COUNT	(10000UL/MAX_GATHER_BATCH)
 
-extern bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, int page_size);
+bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page,
+		int page_size, bool delay_rmap);
 bool __tlb_remove_folio_pages(struct mmu_gather *tlb, struct page *page,
 		unsigned int nr_pages, bool delay_rmap);
 
@@ -464,7 +465,7 @@ static inline void tlb_flush_mmu_tlbonly(struct mmu_gather *tlb)
 static inline void tlb_remove_page_size(struct mmu_gather *tlb,
 					struct page *page, int page_size)
 {
-	if (__tlb_remove_page_size(tlb, page, page_size))
+	if (__tlb_remove_page_size(tlb, page, page_size, false))
 		tlb_flush_mmu(tlb);
 }
 
mm/hugetlb.c +34 -5
index 94de63529cbc5..ec9eaaa13ada3 100644
@@ -5340,7 +5340,7 @@ unsigned long move_hugetlb_page_tables(struct vm_area_struct *vma,
 }
 
 /* Must be called after rmap removal. */
-static void hugetlb_folio_restore_rsv_on_unmap(struct vm_area_struct *vma,
+void hugetlb_folio_restore_rsv_on_unmap(struct vm_area_struct *vma,
 		struct folio *folio)
 {
 	struct hstate *h = hstate_vma(vma);
@@ -5401,6 +5401,8 @@ static void hugetlb_unmap_range(struct mmu_gather *tlb,
 	last_addr_mask = hugetlb_mask_last_page(h);
 	address = start;
 	for (; address < end; address += sz) {
+		bool delay_rmap = false;
+
 		ptep = hugetlb_walk(vma, address, sz);
 		if (!ptep) {
 			address |= last_addr_mask;
@@ -5473,19 +5475,46 @@ static void hugetlb_unmap_range(struct mmu_gather *tlb,
 					make_pte_marker(PTE_MARKER_UFFD_WP),
 					sz);
 		hugetlb_count_sub(pages_per_huge_page(h), mm);
-		hugetlb_remove_rmap(folio);
+		/*
+		 * hugetlb_wp() uses mapcount to decide whether an anonymous
+		 * folio can be reused. Delay rmap removal until stale TLB
+		 * entries are gone, unless the mm has no users left.
+		 */
+		if (folio_test_anon(folio) && !tlb->fullmm) {
+			delay_rmap = tlb_delay_rmap(tlb);
+			/*
+			 * Without delay-rmap support, just flush before
+			 * dropping the PTL. Except with MMU_GATHER_NO_GATHER
+			 * where clearing already flushed the TLB.
+			 */
+			if (!delay_rmap && !IS_ENABLED(CONFIG_MMU_GATHER_NO_GATHER))
+				flush_hugetlb_tlb_range(vma, address, address + sz);
+		}
+		if (!delay_rmap)
+			hugetlb_remove_rmap(folio);
 		spin_unlock(ptl);
 
-		hugetlb_folio_restore_rsv_on_unmap(vma, folio);
+		if (!delay_rmap)
+			hugetlb_folio_restore_rsv_on_unmap(vma, folio);
 
-		tlb_remove_page_size(tlb, folio_page(folio, 0),
-				     folio_size(folio));
+		if (__tlb_remove_page_size(tlb, folio_page(folio, 0), sz,
+					   delay_rmap)) {
+			tlb_flush_mmu_tlbonly(tlb);
+			tlb_flush_rmaps(tlb, vma);
+			tlb_flush_mmu(tlb);
+		}
 		/*
 		 * If we were instructed to unmap a specific folio, we're done.
 		 */
 		if (folio_provided)
 			break;
 	}
+
+	if (tlb->delayed_rmap) {
+		tlb_flush_mmu_tlbonly(tlb);
+		tlb_flush_rmaps(tlb, vma);
+		tlb_flush_mmu(tlb);
+	}
 }
 
 void __unmap_hugepage_range(struct mmu_gather *tlb, struct vm_area_struct *vma,
mm/internal.h +9 -0
index e3f92883bf238..2f1a7b9b2c055 100644
@@ -614,6 +614,15 @@ void zap_vma_range_batched(struct mmu_gather *tlb,
 		struct vm_area_struct *vma, unsigned long addr,
 		unsigned long size, struct zap_details *details);
 int zap_vma_for_reaping(struct vm_area_struct *vma);
+#ifdef CONFIG_HUGETLB_PAGE
+void hugetlb_folio_restore_rsv_on_unmap(struct vm_area_struct *vma,
+		struct folio *folio);
+#else
+static inline void hugetlb_folio_restore_rsv_on_unmap(struct vm_area_struct *vma,
+		struct folio *folio)
+{
+}
+#endif
 int folio_unmap_invalidate(struct address_space *mapping, struct folio *folio,
 			   gfp_t gfp);
 
mm/mmu_gather.c +12 -4
index 9f353f0e2ef4d..8728e1764fc5a 100644
@@ -15,6 +15,8 @@
 
 #include <asm/tlb.h>
 
+#include "internal.h"
+
 #ifndef CONFIG_MMU_GATHER_NO_GATHER
 
 static bool tlb_next_batch(struct mmu_gather *tlb)
@@ -59,14 +61,19 @@ static void tlb_flush_rmap_batch(struct mmu_gather_batch *batch, struct vm_area_
 
 		if (encoded_page_flags(enc) & ENCODED_PAGE_BIT_DELAY_RMAP) {
 			struct page *page = encoded_page_ptr(enc);
+			struct folio *folio = page_folio(page);
 			unsigned int nr_pages = 1;
 
 			if (unlikely(encoded_page_flags(enc) &
 				     ENCODED_PAGE_BIT_NR_PAGES_NEXT))
 				nr_pages = encoded_nr_pages(pages[++i]);
 
-			folio_remove_rmap_ptes(page_folio(page), page, nr_pages,
-					       vma);
+			if (folio_test_hugetlb(folio)) {
+				hugetlb_remove_rmap(folio);
+				hugetlb_folio_restore_rsv_on_unmap(vma, folio);
+			} else {
+				folio_remove_rmap_ptes(folio, page, nr_pages, vma);
+			}
 		}
 	}
 }
@@ -211,9 +218,10 @@ bool __tlb_remove_folio_pages(struct mmu_gather *tlb, struct page *page,
 					     PAGE_SIZE);
 }
 
-bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page, int page_size)
+bool __tlb_remove_page_size(struct mmu_gather *tlb, struct page *page,
+		int page_size, bool delay_rmap)
 {
-	return __tlb_remove_folio_pages_size(tlb, page, 1, false, page_size);
+	return __tlb_remove_folio_pages_size(tlb, page, 1, delay_rmap, page_size);
 }
 
 #endif /* MMU_GATHER_NO_GATHER */
Signature · 1 line
2.56.1
#55 lore raw

Re: [PATCH v2 15/15] mm/hugetlb: delay anon folio rmap removal until after the TLB flush

Sashiko has reviewed this patch and found no issues.
Quoted 18 lines

After fork(), parent and child map anonymous folios read-only shared by CoW. On a write fault, hugetlb_wp() reuses an anonymous page instead of copying it if its mapcount is 1. As documented, switching to the safer refcount would cause more harm than help with these scarce resources.

munmap() and MADV_DONTNEED unmap such folios and decrement the mapcount before the TLB is flushed. Until then, another thread of the process can still read the page through a stale TLB entry:

    child: reader        child: munmap()       parent: writer
    =============        ===============       ==============

reads the page
clears the entry
mapcount drops to 1
store to the page
[ ... ]
for applications with different parent vs. child trust boundaries.

Quoted 3 lines
Fixes 24669e58477e ("hugetlb: use mmu_gather instead of a temporary linked list for accumulating pages")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=15
author maintainer
#56 lore raw
In reply to David Hildenbrand (Arm)
Quoted 5 lines · David Hildenbrand (Arm)

Hi,

v2 of the hugetlb fixes. There will be more at some point ... let's drag these over the finishing line.

As Andrew reports, I accidentally used the wrong CC: stable address. I assume this can get fixed up when applying -- unless I have to resend ;)

Signature · 3 lines
Cheers,

David