All of lore.kernel.org
 help / color / mirror / Atom feed
* [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount"
@ 2026-11-30 13:06 Pedro Falcato
  2026-11-30 13:06 ` [PATCH 6.18.y 1/5] mm: limit pagecache folio refcount when mapping pages Pedro Falcato
                   ` (5 more replies)
  0 siblings, 6 replies; 7+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:06 UTC (permalink / raw)
  To: stable; +Cc: Pedro Falcato, linux-mm

Hi,

here's the backport of the "mm: limit pagecache folio refcount" (or part of
it) to v6.18. This was mostly trivial, all patches Mostly Apply, apart from
a couple of userfaultfd hunks.

Note that these backports, as well as the following ones for 6.12, do
not include the net fixes, which haven't hit mainline yet.

Anyway, please consider for stable.

To: stable@vger.kernel.org
Cc: linux-mm@kvack.org

David Hildenbrand (Arm) (5):
  mm: limit pagecache folio refcount when mapping pages
  mm: limit pagecache folio refcount when splicing into pipes
  mm/mmu_gather: flush pending references early before the folio limit
  iommufd: fix cleanup when adding memfd folio pins fails
  mm/gup: limit pagecache folio refcount when grabbing references

 drivers/iommu/iommufd/pages.c | 15 ++++--
 fs/fuse/dev.c                 |  4 +-
 include/asm-generic/tlb.h     |  4 +-
 include/linux/mm.h            | 89 +++++++++++++++++++++++++++++------
 mm/filemap.c                  | 28 +++++++----
 mm/gup.c                      | 32 ++++++++-----
 mm/huge_memory.c              | 32 ++++++++++++-
 mm/internal.h                 |  4 +-
 mm/memory.c                   | 39 ++++++++++++---
 mm/migrate.c                  | 11 +++++
 mm/mmu_gather.c               | 10 ++--
 mm/shmem.c                    |  7 ++-
 mm/swap.c                     | 26 ++++++++++
 mm/userfaultfd.c              |  4 ++
 14 files changed, 247 insertions(+), 58 deletions(-)

-- 
2.56.0



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

* [PATCH 6.18.y 1/5] mm: limit pagecache folio refcount when mapping pages
  2026-11-30 13:06 [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
@ 2026-11-30 13:06 ` Pedro Falcato
  2026-11-30 13:06 ` [PATCH 6.18.y 2/5] mm: limit pagecache folio refcount when splicing into pipes Pedro Falcato
                   ` (4 subsequent siblings)
  5 siblings, 0 replies; 7+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:06 UTC (permalink / raw)
  To: stable
  Cc: Pedro Falcato, linux-mm, David Hildenbrand (Arm), Chris Mason,
	Jose A. Perez de Azpillaga, Zi Yan

From: "David Hildenbrand (Arm)" <david@kernel.org>

With large file folios, overflowing the folio mapcount and refcount
became possible more easily. For anon folios it is currently not really
an issue: each large anon folio can only be mapped once into a process; on
4k kernels it would be more processes than usually allowed on a system,
and on 16k or 64k kernels the processes alone would consume hundreds of
GiB. Something to be sorted out at some point, but it's not as urgent.

Being able to overflow the refcount is not really big news, but it's about
time that we do something about it because some modern technology might
find ways to abuse it :)

One of the enablers for that was commit ddc58f27f9ee ("mm: drop tail page
refcounting"), however, file thp support was added later.

File folios can be mapped multiple times into the same process, allowing
for processes to hold many references to the same folio.

As a short-term solution, let's introduce two folio refcount limits:
one for ordinary consumers and one for admins. Leave some headroom
before the refcount goes negative, which we really don't want (having
the mapcount go negative is also not expected).

Start reporting SIGBUS and a ratelimited warning if we run into limits.
When restoring mappings from migration entries, instead zap the pte/pmd
entry. We allow for slightly exceeding the limit to keep things simpler.

During fork(), prefer not copying page table entries over failing fork.
For fault-around, check in next_uptodate_folio() before trying to lock
the folio.

Export folio_ref_count_over_limit_slowpath() using EXPORT_SYMBOL_GPL
right away so modules can use it through try_get_page(), where we will
use it next.

Use has_capability_noaudit(current, CAP_SYS_RESOURCE),
so filesystem credential overrides do not affect access to the admin
reserve, and to not generate auditing messages simply because we access
optional reserves.

Don't grant access to the admin reserve from kernel threads, from
interrupt context, where "current" is just the interrupted task, or with
IRQs disabled, as even unaudited capability checks can take locks.

This is far from ideal, but better than all easy alternatives we can
backport comfortably. For now it fixes the big problem: letting
the refcount (+mapcount) go negative and cause trouble.

This is only a temporary fix. Keep the mapping checks explicit and
separate from reference acquisition: most are expected to disappear when
we rework the underlying refcounting.

Check order 0 folios as well for consistency: each
folio_add_file_rmap*() and folio_dup_file_rmap*() needs a prior check.

Adjust the check in folio_get() to just check for invalid refcounts and
drop folio_ref_zero_or_close_to_overflow(): we really don't want
negative refcounts or negative mapcounts. Convert to VM_WARN_ON_FOLIO as
we touch it.

Also, just document -EHWPOISON for copy_present_ptes() while at it.

Note: When zapping file migration entries, uffd-wp is preserved using PTE
markers, but uffd-rwp protection is lost because there is no corresponding
marker. try_to_unmap() already has the same problem when unmapping file
folios, so we'll happily ignore it.

Reported-by: Chris Mason <mason@kernel.org>
Fixes: 800d8c63b2e9 ("shmem: add huge pages support")
Fixes: 99cb0dbd47a1 ("mm,thp: add read-only THP support for (non-shmem) FS")
Fixes: 793917d997df ("mm/readahead: Add large folio readahead")
Cc: stable@vger.kernel.org
Reviewed-by: Jose A. Perez de Azpillaga <azpijr@gmail.com>
Acked-by: Zi Yan <ziy@nvidia.com>
Reviewed-by: Pedro Falcato <pfalcato@suse.de>
Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-1-ad3deef0bd23@kernel.org
Signed-off-by: David Hildenbrand (Arm) <david@kernel.org>
(cherry picked from commit 26b8f029ce5224dd5c5f45a4bc964a209c259914)
[pfalcato: remove uffd rwp reference, use pte_install_uffd_wp_if_needed]
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 include/linux/mm.h | 36 ++++++++++++++++++++++++++++++++----
 mm/filemap.c       |  2 ++
 mm/huge_memory.c   | 32 ++++++++++++++++++++++++++++++--
 mm/memory.c        | 35 +++++++++++++++++++++++++++++++----
 mm/migrate.c       | 11 +++++++++++
 mm/swap.c          | 26 ++++++++++++++++++++++++++
 mm/userfaultfd.c   |  4 ++++
 7 files changed, 136 insertions(+), 10 deletions(-)

diff --git a/include/linux/mm.h b/include/linux/mm.h
index bc5771e26e1d..c81d7df84bef 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -1473,9 +1473,37 @@ vm_fault_t finish_fault(struct vm_fault *vmf);
  *   back into memory.
  */
 
-/* 127: arbitrary random number, small enough to assemble well */
-#define folio_ref_zero_or_close_to_overflow(folio) \
-	((unsigned int) folio_ref_count(folio) + 127u <= 127u)
+/* Leave separate reserves for administrators and concurrent reference gains. */
+#define FOLIO_REF_COUNT_LIMIT		(INT_MAX - (1U << 26))
+#define FOLIO_REF_COUNT_ADMIN_LIMIT	(INT_MAX - (1U << 25))
+
+bool folio_ref_count_over_limit_slowpath(const struct folio *folio,
+		unsigned int ref_count);
+
+/**
+ * folio_ref_count_over_limit - Check whether to refuse more folio references.
+ * @folio: The folio.
+ *
+ * Check before adding page table mappings or other significant refcount users
+ * to pagecache folios (!hugetlb), either before acquiring references or
+ * afterwards with rollback if the operation is refused.
+ *
+ * Checking other folios does no harm.
+ *
+ * This check is an approximation; we leave some headroom such that concurrent
+ * increments, batches, temporary references, or other bounded refcount
+ * consumers are not a problem.
+ *
+ * Return: True if the caller should refuse the operation, false otherwise.
+ */
+static inline bool folio_ref_count_over_limit(const struct folio *folio)
+{
+	const unsigned int ref_count = folio_ref_count(folio);
+
+	if (likely(ref_count < FOLIO_REF_COUNT_LIMIT))
+		return false;
+	return folio_ref_count_over_limit_slowpath(folio, ref_count);
+}
 
 /**
  * folio_get - Increment the reference count on a folio.
@@ -1487,7 +1515,7 @@ vm_fault_t finish_fault(struct vm_fault *vmf);
  */
 static inline void folio_get(struct folio *folio)
 {
-	VM_BUG_ON_FOLIO(folio_ref_zero_or_close_to_overflow(folio), folio);
+	VM_WARN_ON_FOLIO(folio_ref_count(folio) <= 0, folio);
 	folio_ref_inc(folio);
 }
 
diff --git a/mm/filemap.c b/mm/filemap.c
index ee6594e69145..d0392be2691e 100644
--- a/mm/filemap.c
+++ b/mm/filemap.c
@@ -3660,6 +3660,8 @@ static struct folio *next_uptodate_folio(struct xa_state *xas,
 			continue;
 		if (!folio_try_get(folio))
 			continue;
+		if (unlikely(folio_ref_count_over_limit(folio)))
+			goto skip;
 		if (folio_test_locked(folio))
 			goto skip;
 		/* Has the page moved or been split? */
diff --git a/mm/huge_memory.c b/mm/huge_memory.c
index b1a63681412d..52b8c33859ac 100644
--- a/mm/huge_memory.c
+++ b/mm/huge_memory.c
@@ -1525,6 +1525,7 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr,
 {
 	struct mm_struct *mm = vma->vm_mm;
 	pgtable_t pgtable = NULL;
+	vm_fault_t ret = VM_FAULT_NOPAGE;
 	spinlock_t *ptl;
 	pmd_t entry;
 
@@ -1561,6 +1562,10 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr,
 		if (is_huge_zero_folio(fop.folio)) {
 			entry = pmd_mkspecial(entry);
 		} else {
+			if (unlikely(folio_ref_count_over_limit(fop.folio))) {
+				ret = VM_FAULT_SIGBUS;
+				goto out_unlock;
+			}
 			folio_get(fop.folio);
 			folio_add_file_rmap_pmd(fop.folio, &fop.folio->page, vma);
 			add_mm_counter(mm, mm_counter_file(fop.folio), HPAGE_PMD_NR);
@@ -1587,7 +1592,7 @@ static vm_fault_t insert_pmd(struct vm_area_struct *vma, unsigned long addr,
 	spin_unlock(ptl);
 	if (pgtable)
 		pte_free(mm, pgtable);
-	return VM_FAULT_NOPAGE;
+	return ret;
 }
 
 /**
@@ -1655,6 +1660,7 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr,
 		pud_t *pud, struct folio_or_pfn fop, pgprot_t prot, bool write)
 {
 	struct mm_struct *mm = vma->vm_mm;
+	vm_fault_t ret = VM_FAULT_NOPAGE;
 	spinlock_t *ptl;
 	pud_t entry;
 
@@ -1680,6 +1686,10 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr,
 	if (fop.is_folio) {
 		entry = folio_mk_pud(fop.folio, vma->vm_page_prot);
 
+		if (unlikely(folio_ref_count_over_limit(fop.folio))) {
+			ret = VM_FAULT_SIGBUS;
+			goto out_unlock;
+		}
 		folio_get(fop.folio);
 		folio_add_file_rmap_pud(fop.folio, &fop.folio->page, vma);
 		add_mm_counter(mm, mm_counter_file(fop.folio), HPAGE_PUD_NR);
@@ -1695,7 +1705,7 @@ static vm_fault_t insert_pud(struct vm_area_struct *vma, unsigned long addr,
 	update_mmu_cache_pud(vma, addr, pud);
 out_unlock:
 	spin_unlock(ptl);
-	return VM_FAULT_NOPAGE;
+	return ret;
 }
 
 /**
@@ -1934,6 +1944,14 @@ int copy_huge_pud(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma
 	if (page) {
 		struct folio *folio = page_folio(page);
 
+		if (unlikely(folio_ref_count_over_limit(folio))) {
+			/*
+			 * VM_MIXEDMAP may contain driver-inserted pages with no
+			 * fault handler to reconstruct the mapping.
+			 */
+			ret = (dst_vma->vm_flags & VM_MIXEDMAP) ? -ENOMEM : 0;
+			goto out_unlock;
+		}
 		folio_get(folio);
 		/*
 		 * TODO: once we support anonymous pages, use
@@ -4855,6 +4873,16 @@ void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct page *new)
 	if (!(pvmw->pmd && !pvmw->pte))
 		return;
 
+	if (!folio_test_anon(folio) && unlikely(folio_ref_count_over_limit(folio))) {
+		/* Leave the file mapping absent so it can be faulted in. */
+		pmd_clear(pvmw->pmd);
+		if (arch_needs_pgtable_deposit())
+			zap_deposited_table(mm, pvmw->pmd);
+		update_hiwater_rss(mm);
+		add_mm_counter(mm, mm_counter_file(folio), -HPAGE_PMD_NR);
+		return;
+	}
+
 	entry = pmd_to_swp_entry(*pvmw->pmd);
 	folio_get(folio);
 	pmde = folio_mk_pmd(folio, READ_ONCE(vma->vm_page_prot));
diff --git a/mm/memory.c b/mm/memory.c
index 2dc764e898fa..047386270303 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -1122,7 +1122,10 @@ static __always_inline void __copy_present_ptes(struct vm_area_struct *dst_vma,
  * consecutive pages of the same folio by copying them as well.
  *
  * Returns -EAGAIN if one preallocated page is required to copy the next PTE.
- * Otherwise, returns the number of copied PTEs (at least 1).
+ * Returns -ENOMEM if the file folio refcount is too high and the PTE must
+ * be copied.
+ * Returns -EHWPOISON if copying a page fails.
+ * Otherwise, returns the number of processed PTEs (at least 1).
  */
 static inline int
 copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
@@ -1140,6 +1143,18 @@ copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma
 
 	folio = page_folio(page);
 
+	if (!folio_test_anon(folio) && unlikely(folio_ref_count_over_limit(folio))) {
+		/*
+		 * VM_MIXEDMAP may contain pages inserted by a driver at mmap
+		 * time, with no fault handler to restore a missing PTE.
+		 */
+		if (dst_vma->vm_flags & VM_MIXEDMAP)
+			return -ENOMEM;
+		/* Preserve uffd-wp protection when faulting the page back in. */
+		pte_install_uffd_wp_if_needed(dst_vma, addr, dst_pte, pte);
+		return 1;
+	}
+
 	/*
 	 * If we likely have to copy, just don't bother with batching. Make
 	 * sure that the common "small folio" case is as fast as possible
@@ -1321,9 +1336,9 @@ copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
 		/*
 		 * If we need a pre-allocated page for this pte, drop the
 		 * locks, allocate, and try again.
-		 * If copy failed due to hwpoison in source page, break out.
+		 * Other errors abort the copy after releasing the page table locks.
 		 */
-		if (unlikely(ret == -EAGAIN || ret == -EHWPOISON))
+		if (unlikely(ret < 0))
 			break;
 		if (unlikely(prealloc)) {
 			/*
@@ -1353,7 +1368,7 @@ copy_pte_range(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma,
 			goto out;
 		}
 		entry.val = 0;
-	} else if (ret == -EBUSY || unlikely(ret == -EHWPOISON)) {
+	} else if (ret == -EBUSY || ret == -ENOMEM || unlikely(ret == -EHWPOISON)) {
 		goto out;
 	} else if (ret ==  -EAGAIN) {
 		prealloc = folio_prealloc(src_mm, src_vma, addr, false);
@@ -2323,6 +2338,8 @@ static int insert_page_into_pte_locked(struct vm_area_struct *vma, pte_t *pte,
 	if (unlikely(is_zero_folio(folio))) {
 		pteval = pte_mkspecial(pteval);
 	} else {
+		if (unlikely(folio_ref_count_over_limit(folio)))
+			return -EOVERFLOW;
 		folio_get(folio);
 		pteval = mk_pte(page, prot);
 		if (mkwrite) {
@@ -5417,6 +5434,9 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *pa
 	if (unlikely(folio_test_has_hwpoisoned(folio)))
 		return ret;
 
+	if (unlikely(folio_ref_count_over_limit(folio)))
+		return VM_FAULT_SIGBUS;
+
 	/*
 	 * Archs like ppc64 need additional space to store information
 	 * related to pte entry. Use the preallocated table for that.
@@ -5471,6 +5491,9 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *pa
  * @page: The first page to create a PTE for.
  * @nr: The number of PTEs to create.
  * @addr: The first address to create a PTE for.
+ *
+ * For file mappings, the caller must check folio_ref_count_over_limit()
+ * before installing PTEs.
  */
 void set_pte_range(struct vm_fault *vmf, struct folio *folio,
 		struct page *page, unsigned int nr, unsigned long addr)
@@ -5637,6 +5660,10 @@ vm_fault_t finish_fault(struct vm_fault *vmf)
 		goto fallback;
 	}
 
+	if (!is_cow && unlikely(folio_ref_count_over_limit(folio))) {
+		ret = VM_FAULT_SIGBUS;
+		goto unlock;
+	}
 	folio_ref_add(folio, nr_pages - 1);
 	set_pte_range(vmf, folio, page, nr_pages, addr);
 	type = is_cow ? MM_ANONPAGES : mm_counter_file(folio);
diff --git a/mm/migrate.c b/mm/migrate.c
index 98d3c9c789f0..d712f5eaf117 100644
--- a/mm/migrate.c
+++ b/mm/migrate.c
@@ -379,6 +379,17 @@ static bool remove_migration_pte(struct folio *folio,
 		    try_to_map_unused_to_zeropage(&pvmw, folio, old_pte, idx))
 			continue;
 
+		if (!folio_test_anon(folio) && !folio_test_hugetlb(folio) &&
+		    unlikely(folio_ref_count_over_limit(folio))) {
+			/* File contents remain available for a later fault. */
+			pte_clear(vma->vm_mm, pvmw.address, pvmw.pte);
+			pte_install_uffd_wp_if_needed(vma, pvmw.address,
+						pvmw.pte, old_pte);
+			update_hiwater_rss(vma->vm_mm);
+			dec_mm_counter(vma->vm_mm, mm_counter_file(folio));
+			continue;
+		}
+
 		folio_get(folio);
 		pte = mk_pte(new, READ_ONCE(vma->vm_page_prot));
 
diff --git a/mm/swap.c b/mm/swap.c
index 2260dcd2775e..20209e0efc2c 100644
--- a/mm/swap.c
+++ b/mm/swap.c
@@ -113,6 +113,32 @@ void __folio_put(struct folio *folio)
 }
 EXPORT_SYMBOL(__folio_put);
 
+bool folio_ref_count_over_limit_slowpath(const struct folio *folio,
+		unsigned int ref_count)
+{
+	if (ref_count >= FOLIO_REF_COUNT_ADMIN_LIMIT)
+		goto over_limit;
+	/* Background threads must not consume admin reserves. */
+	if (current->flags & PF_KTHREAD)
+		goto over_limit;
+	/* Neither must interrupt contexts on behalf of the interrupted task. */
+	if (!in_task())
+		goto over_limit;
+	/* Capability checks are not safe with IRQs disabled. */
+	if (irqs_disabled())
+		goto over_limit;
+	/* Use the task's credentials, which filesystem overrides cannot change. */
+	if (has_capability_noaudit(current, CAP_SYS_RESOURCE))
+		return false;
+
+over_limit:
+	pr_warn_ratelimited("folio:%p refcount:%d mapcount:%d mapping:%p index:%#lx reached refcount limit\n",
+			    folio, (int)ref_count, folio_mapcount(folio),
+			    folio_mapping(folio), folio->index);
+	return true;
+}
+EXPORT_SYMBOL_GPL(folio_ref_count_over_limit_slowpath);
+
 typedef void (*move_fn_t)(struct lruvec *lruvec, struct folio *folio);
 
 static void lru_add(struct lruvec *lruvec, struct folio *folio)
diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c
index 0b479d09e313..ca39280799e5 100644
--- a/mm/userfaultfd.c
+++ b/mm/userfaultfd.c
@@ -207,6 +207,10 @@ int mfill_atomic_install_pte(pmd_t *dst_pmd,
 		goto out_unlock;
 
 	if (page_in_cache) {
+		if (unlikely(folio_ref_count_over_limit(folio))) {
+			ret = -ENOMEM;
+			goto out_unlock;
+		}
 		/* Usually, cache pages are already added to LRU */
 		if (newly_allocated)
 			folio_add_lru(folio);
-- 
2.56.0



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

* [PATCH 6.18.y 2/5] mm: limit pagecache folio refcount when splicing into pipes
  2026-11-30 13:06 [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
  2026-11-30 13:06 ` [PATCH 6.18.y 1/5] mm: limit pagecache folio refcount when mapping pages Pedro Falcato
@ 2026-11-30 13:06 ` Pedro Falcato
  2026-11-30 13:06 ` [PATCH 6.18.y 3/5] mm/mmu_gather: flush pending references early before the folio limit Pedro Falcato
                   ` (3 subsequent siblings)
  5 siblings, 0 replies; 7+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:06 UTC (permalink / raw)
  To: stable
  Cc: Pedro Falcato, linux-mm, David Hildenbrand (Arm),
	Jose A. Perez de Azpillaga

From: "David Hildenbrand (Arm)" <david@kernel.org>

Similar to mapping pagecache folios into page tables, let's reject
additional references when splicing folios into a pipe if the refcount
is at its limit.

This will prevent more cases of possible folio refcount overflows with
large pagecache folios.

Introduce folio_get_checked() for checked reference acquisition when
the caller already holds a reference. It warns and fails on a non-positive
refcount and rejects additional references at the limit.

Add __folio_ref_count_over_limit() so folio_get_checked() can reuse the
refcount instead of having to read it a second time.

Use folio_get_checked() in splice_folio_into_pipe() and
fuse_ref_folio(), returning -EFAULT on failure, like we already do for
pipe-buffer duplication. Similarly, make try_get_page() use it instead.

Likely try_get_page() should be renamed (or removed) later, as it doesn't
match the folio_try_get() semantics and is confusing.

If we hit the limit after splicing some data, return the number of bytes
already spliced. Teach the callers to handle errors, and stop
filemap_splice_read() if we only spliced part of a folio, so we don't
skip ahead to the next folio: note that we wouldn't run into this
scenario before as we always spliced the requested range.

The check in try_get_page() also covers pipe-buffer duplication by tee()
and partial pipe-to-pipe splicing.

Note that we deliberately will not fall back to the slow path of copying
the folio, particularly as the folio might have an invalid refcount. If
it is ever really required, we can revisit.

Fixes: 800d8c63b2e9 ("shmem: add huge pages support")
Fixes: 99cb0dbd47a1 ("mm,thp: add read-only THP support for (non-shmem) FS")
Fixes: 793917d997df ("mm/readahead: Add large folio readahead")
Cc: stable@vger.kernel.org
Reviewed-by: Jose A. Perez de Azpillaga <azpijr@gmail.com>
Reviewed-by: Pedro Falcato <pfalcato@suse.de>
Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-2-ad3deef0bd23@kernel.org
Signed-off-by: David Hildenbrand (Arm) <david@kernel.org>
(cherry picked from commit c6c9a4c1c9a1669693330205cb9d86fafd3cf235)
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 fs/fuse/dev.c      |  4 +++-
 include/linux/mm.h | 49 ++++++++++++++++++++++++++++++++++++++--------
 mm/filemap.c       | 26 ++++++++++++++----------
 mm/internal.h      |  4 ++--
 mm/shmem.c         |  7 +++++--
 5 files changed, 67 insertions(+), 23 deletions(-)

diff --git a/fs/fuse/dev.c b/fs/fuse/dev.c
index 0f9ef3ca9824..e3ff9a1e9ba4 100644
--- a/fs/fuse/dev.c
+++ b/fs/fuse/dev.c
@@ -1103,7 +1103,9 @@ static int fuse_ref_folio(struct fuse_copy_state *cs, struct folio *folio,
 	if (cs->nr_segs >= cs->pipe->max_usage)
 		return -EIO;
 
-	folio_get(folio);
+	if (!folio_get_checked(folio))
+		return -EFAULT;
+
 	err = unlock_request(cs->req);
 	if (err) {
 		folio_put(folio);
diff --git a/include/linux/mm.h b/include/linux/mm.h
index c81d7df84bef..7b373294359b 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -1481,8 +1481,9 @@ bool folio_ref_count_over_limit_slowpath(const struct folio *folio,
 		unsigned int ref_count);
 
 /**
- * folio_ref_count_over_limit - Check whether to refuse more folio references.
+ * __folio_ref_count_over_limit - Check whether to refuse more folio references.
  * @folio: The folio.
+ * @ref_count: The sampled folio reference count.
  *
  * Check before adding page table mappings or other significant refcount users
  * to pagecache folios (!hugetlb), either before acquiring references or
@@ -1496,15 +1497,27 @@ bool folio_ref_count_over_limit_slowpath(const struct folio *folio,
  *
  * Return: True if the caller should refuse the operation, false otherwise.
  */
-static inline bool folio_ref_count_over_limit(const struct folio *folio)
+static inline bool __folio_ref_count_over_limit(const struct folio *folio,
+		unsigned int ref_count)
 {
-	const unsigned int ref_count = folio_ref_count(folio);
-
 	if (likely(ref_count < FOLIO_REF_COUNT_LIMIT))
 		return false;
 	return folio_ref_count_over_limit_slowpath(folio, ref_count);
 }
 
+/**
+ * folio_ref_count_over_limit - Check whether to refuse more folio references.
+ * @folio: The folio.
+ *
+ * See __folio_ref_count_over_limit().
+ *
+ * Return: True if the caller should refuse the operation, false otherwise.
+ */
+static inline bool folio_ref_count_over_limit(const struct folio *folio)
+{
+	return __folio_ref_count_over_limit(folio, folio_ref_count(folio));
+}
+
 /**
  * folio_get - Increment the reference count on a folio.
  * @folio: The folio.
@@ -1529,15 +1542,35 @@ static inline void get_page(struct page *page)
 	folio_get(folio);
 }
 
-static inline __must_check bool try_get_page(struct page *page)
+/**
+ * folio_get_checked - Try to acquire a reference to a live folio.
+ * @folio: The folio.
+ *
+ * The caller must already hold a reference to @folio. Warn and fail on a
+ * non-positive refcount, and refuse additional references at the limit.
+ *
+ * Use folio_try_get() for speculative reference acquisition where the
+ * refcount can legitimately be zero.
+ *
+ * Return: True if the refcount was incremented, false otherwise.
+ */
+static inline __must_check bool folio_get_checked(struct folio *folio)
 {
-	page = compound_head(page);
-	if (WARN_ON_ONCE(page_ref_count(page) <= 0))
+	const int ref_count = folio_ref_count(folio);
+
+	if (WARN_ON_ONCE(ref_count <= 0))
+		return false;
+	if (unlikely(__folio_ref_count_over_limit(folio, ref_count)))
 		return false;
-	page_ref_inc(page);
+	folio_ref_inc(folio);
 	return true;
 }
 
+static inline __must_check bool try_get_page(struct page *page)
+{
+	return folio_get_checked(page_folio(page));
+}
+
 /**
  * folio_put - Decrement the reference count on a folio.
  * @folio: The folio.
diff --git a/mm/filemap.c b/mm/filemap.c
index d0392be2691e..a6df00536342 100644
--- a/mm/filemap.c
+++ b/mm/filemap.c
@@ -2965,10 +2965,11 @@ generic_file_read_iter(struct kiocb *iocb, struct iov_iter *iter)
 EXPORT_SYMBOL(generic_file_read_iter);
 
 /*
- * Splice subpages from a folio into a pipe.
+ * Splice subpages from a folio into a pipe. Return the number of bytes spliced,
+ * or -EFAULT if we cannot splice from the folio.
  */
-size_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
-			      struct folio *folio, loff_t fpos, size_t size)
+ssize_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
+			       struct folio *folio, loff_t fpos, size_t size)
 {
 	struct page *page;
 	size_t spliced = 0, offset = offset_in_folio(folio, fpos);
@@ -2981,13 +2982,15 @@ size_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
 		struct pipe_buffer *buf = pipe_head_buf(pipe);
 		size_t part = min_t(size_t, PAGE_SIZE - offset, size - spliced);
 
+		if (!folio_get_checked(folio))
+			return spliced ? spliced : -EFAULT;
+
 		*buf = (struct pipe_buffer) {
 			.ops	= &page_cache_pipe_buf_ops,
 			.page	= page,
 			.offset	= offset,
 			.len	= part,
 		};
-		folio_get(folio);
 		pipe->head++;
 		page++;
 		spliced += part;
@@ -3012,9 +3015,10 @@ size_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
  * Return: On success, the number of bytes read will be returned and *@ppos
  * will be updated if appropriate; 0 will be returned if there is no more data
  * to be read; -EAGAIN will be returned if the pipe had no space, and some
- * other negative error code will be returned on error.  A short read may occur
- * if the pipe has insufficient space, we reach the end of the data or we hit a
- * hole.
+ * other negative error code will be returned on error; -EFAULT will be returned
+ * if acquiring a folio reference fails and no data has been spliced.
+ * A short read may occur if the pipe has insufficient space, we reach the
+ * end of the data, hit a hole or hit a folio refcount limit.
  */
 ssize_t filemap_splice_read(struct file *in, loff_t *ppos,
 			    struct pipe_inode_info *pipe,
@@ -3072,7 +3076,7 @@ ssize_t filemap_splice_read(struct file *in, loff_t *ppos,
 
 		for (i = 0; i < folio_batch_count(&fbatch); i++) {
 			struct folio *folio = fbatch.folios[i];
-			size_t n;
+			ssize_t n;
 
 			if (folio_pos(folio) >= end_offset)
 				goto out;
@@ -3088,13 +3092,15 @@ ssize_t filemap_splice_read(struct file *in, loff_t *ppos,
 
 			n = min_t(loff_t, len, isize - *ppos);
 			n = splice_folio_into_pipe(pipe, folio, *ppos, n);
-			if (!n)
+			if (n <= 0) {
+				error = n;
 				goto out;
+			}
 			len -= n;
 			total_spliced += n;
 			*ppos += n;
 			in->f_ra.prev_pos = *ppos;
-			if (pipe_is_full(pipe))
+			if (pipe_is_full(pipe) || *ppos < folio_next_pos(folio))
 				goto out;
 		}
 
diff --git a/mm/internal.h b/mm/internal.h
index 4a27dac7a42a..e2306decc8a1 100644
--- a/mm/internal.h
+++ b/mm/internal.h
@@ -1388,8 +1388,8 @@ struct migration_target_control {
 /*
  * mm/filemap.c
  */
-size_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
-			      struct folio *folio, loff_t fpos, size_t size);
+ssize_t splice_folio_into_pipe(struct pipe_inode_info *pipe,
+			       struct folio *folio, loff_t fpos, size_t size);
 
 /*
  * mm/vmalloc.c
diff --git a/mm/shmem.c b/mm/shmem.c
index 82216c44f67d..f0b892c59918 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -3608,7 +3608,8 @@ static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos,
 	struct inode *inode = file_inode(in);
 	struct address_space *mapping = inode->i_mapping;
 	struct folio *folio = NULL;
-	size_t total_spliced = 0, used, npages, n, part;
+	size_t total_spliced = 0, used, npages, part;
+	ssize_t n;
 	loff_t isize;
 	int error = 0;
 
@@ -3694,8 +3695,10 @@ static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos,
 			n = splice_zeropage_into_pipe(pipe, *ppos, part);
 		}
 
-		if (!n)
+		if (n <= 0) {
+			error = n;
 			break;
+		}
 		len -= n;
 		total_spliced += n;
 		*ppos += n;
-- 
2.56.0



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

* [PATCH 6.18.y 3/5] mm/mmu_gather: flush pending references early before the folio limit
  2026-11-30 13:06 [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
  2026-11-30 13:06 ` [PATCH 6.18.y 1/5] mm: limit pagecache folio refcount when mapping pages Pedro Falcato
  2026-11-30 13:06 ` [PATCH 6.18.y 2/5] mm: limit pagecache folio refcount when splicing into pipes Pedro Falcato
@ 2026-11-30 13:06 ` Pedro Falcato
  2026-11-30 13:06 ` [PATCH 6.18.y 4/5] iommufd: fix cleanup when adding memfd folio pins fails Pedro Falcato
                   ` (2 subsequent siblings)
  5 siblings, 0 replies; 7+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:06 UTC (permalink / raw)
  To: stable
  Cc: Pedro Falcato, linux-mm, David Hildenbrand (Arm), Chris Mason,
	Jose A. Perez de Azpillaga, Lance Yang

From: "David Hildenbrand (Arm)" <david@kernel.org>

When a task zaps mappings (e.g., MADV_DONTNEED), it can drop the PT lock
and defer dropping the folio references. In the meantime, page faults
can refault pagecache folios, creating more references for the same
folios. These deferred references can build up over multiple VMAs.

Let's just request a flush after enqueueing folios whose refcount reached
a certain threshold. Start flushing well before new references are refused,
regardless of the caller's privileges.

When returning "true" from __tlb_remove_folio_pages_size(), PTE zapping
will flush the TLB before dropping the PT lock, but drop the references
afterwards. Refaults can still race with that, but flushing early reduces
the risk of letting others hit the limit.

This is a temporary measure until we have something better.

Reported-by: Chris Mason <mason@kernel.org>
Fixes: 800d8c63b2e9 ("shmem: add huge pages support")
Fixes: 99cb0dbd47a1 ("mm,thp: add read-only THP support for (non-shmem) FS")
Fixes: 793917d997df ("mm/readahead: Add large folio readahead")
Cc: stable@vger.kernel.org
Reviewed-by: Jose A. Perez de Azpillaga <azpijr@gmail.com>
Reviewed-by: Lance Yang <lance.yang@linux.dev>
Reviewed-by: Pedro Falcato <pfalcato@suse.de>
Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-3-ad3deef0bd23@kernel.org
Signed-off-by: David Hildenbrand (Arm) <david@kernel.org>
(cherry picked from commit 317bd7d28b248fd4d4e14614d7c30b17a36ef4d7)
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 include/asm-generic/tlb.h |  4 ++--
 include/linux/mm.h        |  1 +
 mm/memory.c               |  4 ++--
 mm/mmu_gather.c           | 10 ++++++----
 4 files changed, 11 insertions(+), 8 deletions(-)

diff --git a/include/asm-generic/tlb.h b/include/asm-generic/tlb.h
index 16dd46d37655..d8553ef897e0 100644
--- a/include/asm-generic/tlb.h
+++ b/include/asm-generic/tlb.h
@@ -78,8 +78,8 @@
  *  - __tlb_remove_folio_pages_size()
  *
  *    __tlb_remove_folio_pages_size() is the basic primitive that queues pages
- *    for freeing. It will return a boolean indicating if the queue is (now)
- *    full and a call to tlb_flush_mmu() is required.
+ *    for freeing. It returns true when a call to tlb_flush_mmu() is required,
+ *    either because the queue is full or a folio is near its refcount limit.
  *
  *    tlb_remove_page() and tlb_remove_page_size() imply the call to
  *    tlb_flush_mmu() when required and has no return value.
diff --git a/include/linux/mm.h b/include/linux/mm.h
index 7b373294359b..e089fd3875f8 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -1476,6 +1476,7 @@ vm_fault_t finish_fault(struct vm_fault *vmf);
 /* Leave separate reserves for administrators and concurrent reference gains. */
 #define FOLIO_REF_COUNT_LIMIT		(INT_MAX - (1U << 26))
 #define FOLIO_REF_COUNT_ADMIN_LIMIT	(INT_MAX - (1U << 25))
+#define FOLIO_REF_COUNT_FLUSH_LIMIT	(INT_MAX - (1U << 27))
 
 bool folio_ref_count_over_limit_slowpath(const struct folio *folio,
 		unsigned int ref_count);
diff --git a/mm/memory.c b/mm/memory.c
index 047386270303..9bc3162edccf 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -1915,8 +1915,8 @@ static unsigned long zap_pte_range(struct mmu_gather *tlb,
 	pte_unmap_unlock(start_pte, ptl);
 
 	/*
-	 * If we forced a TLB flush (either due to running out of
-	 * batch buffers or because we needed to flush dirty TLB
+	 * If we forced a TLB flush (either to release batched
+	 * references or because we needed to flush dirty TLB
 	 * entries before releasing the ptl), free the batched
 	 * memory too. Come back again if we didn't do everything.
 	 */
diff --git a/mm/mmu_gather.c b/mm/mmu_gather.c
index 5619ee967f3c..b01ba6456dae 100644
--- a/mm/mmu_gather.c
+++ b/mm/mmu_gather.c
@@ -178,10 +178,7 @@ static bool __tlb_remove_folio_pages_size(struct mmu_gather *tlb,
 #endif
 
 	batch = tlb->active;
-	/*
-	 * Add the page and check if we are full. If so
-	 * force a flush.
-	 */
+	/* Add the pages before deciding whether we need to flush. */
 	if (likely(nr_pages == 1)) {
 		batch->encoded_pages[batch->nr++] = encode_page(page, flags);
 	} else {
@@ -189,6 +186,11 @@ static bool __tlb_remove_folio_pages_size(struct mmu_gather *tlb,
 		batch->encoded_pages[batch->nr++] = encode_page(page, flags);
 		batch->encoded_pages[batch->nr++] = encode_nr_pages(nr_pages);
 	}
+	/* Flush pending references well before new references are refused. */
+	if (unlikely((unsigned int)folio_ref_count(page_folio(page)) >=
+		     FOLIO_REF_COUNT_FLUSH_LIMIT))
+		return true;
+
 	/*
 	 * Make sure that we can always add another "page" + "nr_pages",
 	 * requiring two entries instead of only a single one.
-- 
2.56.0



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

* [PATCH 6.18.y 4/5] iommufd: fix cleanup when adding memfd folio pins fails
  2026-11-30 13:06 [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
                   ` (2 preceding siblings ...)
  2026-11-30 13:06 ` [PATCH 6.18.y 3/5] mm/mmu_gather: flush pending references early before the folio limit Pedro Falcato
@ 2026-11-30 13:06 ` Pedro Falcato
  2026-11-30 13:06 ` [PATCH 6.18.y 5/5] mm/gup: limit pagecache folio refcount when grabbing references Pedro Falcato
  2026-12-02 13:48 ` [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Sasha Levin
  5 siblings, 0 replies; 7+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:06 UTC (permalink / raw)
  To: stable
  Cc: Pedro Falcato, linux-mm, David Hildenbrand (Arm), Lance Yang,
	Jason Gunthorpe

From: "David Hildenbrand (Arm)" <david@kernel.org>

folio_add_pins() can fail after memfd_pin_folios() succeeded pinning a
folio. Upcoming folio refcount limit checks will make this easier to
trigger.

Let's fix three problems in the error handling:

1. pfn_reader_release_pins() uses the allocated array size instead of the
   number of folios returned by memfd_pin_folios(). With large folios,
   cleanup can unpin uninitialized entries. Remember the number of returned
   folios and use that during cleanup.

2. pin_memfd_pages() returns on failure without releasing the pins acquired
   by the current call. Release the per-page pins for folios already
   expanded into the page array, and the single pins for the remaining
   folios.

3. pfn_reader_next() returns on failure before updating batch_end_index,
   even if the batch already contains successfully expanded folios. Update
   it before propagating the error so cleanup releases those pins as well.

Fixes: 92687c793644 ("iommufd: pfn_reader for file mappings")
Cc: stable@vger.kernel.org
Reviewed-by: Lance Yang <lance.yang@linux.dev>
Reviewed-by: Jason Gunthorpe <jgg@nvidia.com>
Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-4-ad3deef0bd23@kernel.org
Signed-off-by: David Hildenbrand (Arm) <david@kernel.org>
(cherry picked from commit b8ba6cc9943222676d46ac77d3d3de2685a55bf8)
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 drivers/iommu/iommufd/pages.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)

diff --git a/drivers/iommu/iommufd/pages.c b/drivers/iommu/iommufd/pages.c
index c3433b845561..e639e0690e8f 100644
--- a/drivers/iommu/iommufd/pages.c
+++ b/drivers/iommu/iommufd/pages.c
@@ -758,6 +758,7 @@ struct pfn_reader_user {
 	struct file *file;
 	struct folio **ufolios;
 	size_t ufolios_len;
+	unsigned long ufolios_count;
 	unsigned long ufolios_offset;
 	struct folio **ufolios_next;
 };
@@ -777,6 +778,7 @@ static void pfn_reader_user_init(struct pfn_reader_user *user,
 	user->file = (pages->type == IOPT_ADDRESS_FILE) ? pages->file : NULL;
 	user->ufolios = NULL;
 	user->ufolios_len = 0;
+	user->ufolios_count = 0;
 	user->ufolios_next = NULL;
 	user->ufolios_offset = 0;
 }
@@ -820,6 +822,7 @@ static long pin_memfd_pages(struct pfn_reader_user *user, unsigned long start,
 
 	offset >>= PAGE_SHIFT;
 	user->ufolios_next = user->ufolios;
+	user->ufolios_count = nfolios;
 	user->ufolios_offset = offset;
 
 	for (i = 0; i < nfolios; i++) {
@@ -836,8 +839,12 @@ static long pin_memfd_pages(struct pfn_reader_user *user, unsigned long start,
 			} else {
 				int rc = folio_add_pins(folio, npin - 1);
 
-				if (rc)
+				if (rc) {
+					unpin_user_pages(user->upages,
+							 upages - user->upages);
+					unpin_folios(user->ufolios + i, nfolios - i);
 					return rc;
+				}
 
 				while (npin--)
 					*upages++ = folio_page(folio, offset++);
@@ -1180,14 +1187,14 @@ static int pfn_reader_next(struct pfn_reader *pfns)
 			return -EINVAL;
 
 		rc = pfn_reader_fill_span(pfns);
+		pfns->batch_end_index = pfns->batch_start_index +
+					pfns->batch.total_pfns;
 		if (rc)
 			return rc;
 
 		if (WARN_ON(!pfns->batch.total_pfns))
 			return -EINVAL;
 
-		pfns->batch_end_index =
-			pfns->batch_start_index + pfns->batch.total_pfns;
 		if (pfns->batch_end_index == pfns->span.last_used + 1)
 			interval_tree_double_span_iter_next(&pfns->span);
 
@@ -1242,7 +1249,7 @@ static void pfn_reader_release_pins(struct pfn_reader *pfns)
 		if (!user->file) {
 			unpin_user_pages(user->upages + start_index, npages);
 		} else {
-			long n = user->ufolios_len / sizeof(*user->ufolios);
+			const unsigned long n = user->ufolios_count;
 
 			unpin_folios(user->ufolios_next,
 				     user->ufolios + n - user->ufolios_next);
-- 
2.56.0


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

* [PATCH 6.18.y 5/5] mm/gup: limit pagecache folio refcount when grabbing references
  2026-11-30 13:06 [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
                   ` (3 preceding siblings ...)
  2026-11-30 13:06 ` [PATCH 6.18.y 4/5] iommufd: fix cleanup when adding memfd folio pins fails Pedro Falcato
@ 2026-11-30 13:06 ` Pedro Falcato
  2026-12-02 13:48 ` [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Sasha Levin
  5 siblings, 0 replies; 7+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:06 UTC (permalink / raw)
  To: stable
  Cc: Pedro Falcato, linux-mm, David Hildenbrand (Arm),
	Jose A. Perez de Azpillaga

From: "David Hildenbrand (Arm)" <david@kernel.org>

Let's add __folio_ref_count_over_limit() checks in fast and slow GUP
before acquiring additional references or pins.

Keep it simple and use the check for all folio types.

Also propagate try_grab_folio() errors when grabbing additional
references in __get_user_pages() and in memfd_pin_folios(), so hitting
the limit returns -ENOMEM instead of -EFAULT and -EINVAL, respectively.

Keep the existing invalid-refcount warnings.

Fixes: 800d8c63b2e9 ("shmem: add huge pages support")
Fixes: 99cb0dbd47a1 ("mm,thp: add read-only THP support for (non-shmem) FS")
Fixes: 793917d997df ("mm/readahead: Add large folio readahead")
Cc: stable@vger.kernel.org
Reviewed-by: Jose A. Perez de Azpillaga <azpijr@gmail.com>
Reviewed-by: Pedro Falcato <pfalcato@suse.de>
Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-5-ad3deef0bd23@kernel.org
Signed-off-by: David Hildenbrand (Arm) <david@kernel.org>
(cherry picked from commit 2d9bcd380585abc436f055fbb618b34f98882004)
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 include/linux/mm.h | 11 +++++------
 mm/gup.c           | 32 +++++++++++++++++++++-----------
 2 files changed, 26 insertions(+), 17 deletions(-)

diff --git a/include/linux/mm.h b/include/linux/mm.h
index e089fd3875f8..d69c8e942eab 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -1490,6 +1490,9 @@ bool folio_ref_count_over_limit_slowpath(const struct folio *folio,
  * to pagecache folios (!hugetlb), either before acquiring references or
  * afterwards with rollback if the operation is refused.
  *
+ * Also required when pinning folios without a dedicated pincount that use
+ * GUP_PIN_COUNTING_BIAS.
+ *
  * Checking other folios does no harm.
  *
  * This check is an approximation; we leave some headroom such that concurrent
@@ -2119,12 +2122,8 @@ static inline bool folio_maybe_dma_pinned(struct folio *folio)
 		return atomic_read(&folio->_pincount) > 0;
 
 	/*
-	 * folio_ref_count() is signed. If that refcount overflows, then
-	 * folio_ref_count() returns a negative value, and callers will avoid
-	 * further incrementing the refcount.
-	 *
-	 * Here, for that overflow case, use the sign bit to count a little
-	 * bit higher via unsigned math, and thus still get an accurate result.
+	 * Use unsigned math so even an unexpected negative refcount is
+	 * treated as possibly pinned.
 	 */
 	return ((unsigned int)folio_ref_count(folio)) >=
 		GUP_PIN_COUNTING_BIAS;
diff --git a/mm/gup.c b/mm/gup.c
index f74fe4b17d01..72fc72115f3e 100644
--- a/mm/gup.c
+++ b/mm/gup.c
@@ -74,10 +74,14 @@ static inline void sanity_check_pinned_pages(struct page **pages,
 static inline struct folio *try_get_folio(struct page *page, int refs)
 {
 	struct folio *folio;
+	int ref_count;
 
 retry:
 	folio = page_folio(page);
-	if (WARN_ON_ONCE(folio_ref_count(folio) < 0))
+	ref_count = folio_ref_count(folio);
+	if (WARN_ON_ONCE(ref_count < 0))
+		return NULL;
+	if (unlikely(__folio_ref_count_over_limit(folio, ref_count)))
 		return NULL;
 	if (unlikely(!folio_ref_try_add(folio, refs)))
 		return NULL;
@@ -140,7 +144,13 @@ static void gup_put_folio(struct folio *folio, int refs, unsigned int flags)
 int __must_check try_grab_folio(struct folio *folio, int refs,
 				unsigned int flags)
 {
-	if (WARN_ON_ONCE(folio_ref_count(folio) <= 0))
+	const int ref_count = folio_ref_count(folio);
+
+	if (WARN_ON_ONCE(ref_count <= 0))
+		return -ENOMEM;
+
+	if ((flags & (FOLL_GET | FOLL_PIN)) &&
+	    unlikely(__folio_ref_count_over_limit(folio, ref_count)))
 		return -ENOMEM;
 
 	if (unlikely(!(flags & FOLL_PCI_P2PDMA) && folio_is_pci_p2pdma(folio)))
@@ -1482,17 +1492,17 @@ static long __get_user_pages(struct mm_struct *mm,
 				struct folio *folio = page_folio(page);
 
 				/*
-				 * Since we already hold refcount on the
-				 * large folio, this should never fail.
+				 * Grabbing more references can fail once we
+				 * hit folio refcount limits.
 				 */
-				if (try_grab_folio(folio, page_increm - 1,
-						   gup_flags)) {
+				ret = try_grab_folio(folio, page_increm - 1,
+						     gup_flags);
+				if (ret) {
 					/*
-					 * Release the 1st page ref if the
-					 * folio is problematic, fail hard.
+					 * Release the folio reference we
+					 * already took.
 					 */
 					gup_put_folio(folio, 1, gup_flags);
-					ret = -EFAULT;
 					goto out;
 				}
 			}
@@ -3541,10 +3551,10 @@ long memfd_pin_folios(struct file *memfd, loff_t start, loff_t end,
 					break;
 				}
 
-				if (try_grab_folio(folio, 1, FOLL_PIN)) {
+				ret = try_grab_folio(folio, 1, FOLL_PIN);
+				if (ret) {
 					folio_unlock(folio);
 					folio_batch_release(&fbatch);
-					ret = -EINVAL;
 					goto err;
 				}
 
-- 
2.56.0


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

* Re: [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount"
  2026-11-30 13:06 [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
                   ` (4 preceding siblings ...)
  2026-11-30 13:06 ` [PATCH 6.18.y 5/5] mm/gup: limit pagecache folio refcount when grabbing references Pedro Falcato
@ 2026-12-02 13:48 ` Sasha Levin
  5 siblings, 0 replies; 7+ messages in thread
From: Sasha Levin @ 2026-12-02 13:48 UTC (permalink / raw)
  To: stable; +Cc: Sasha Levin, Pedro Falcato, linux-mm

> here's the backport of the "mm: limit pagecache folio refcount" (or part of
> it) to v6.18.

Queued the series for 6.18, thanks.

-- 
Thanks,
Sasha

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

end of thread, other threads:[~2026-12-02 13:49 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-30 13:06 [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
2026-11-30 13:06 ` [PATCH 6.18.y 1/5] mm: limit pagecache folio refcount when mapping pages Pedro Falcato
2026-11-30 13:06 ` [PATCH 6.18.y 2/5] mm: limit pagecache folio refcount when splicing into pipes Pedro Falcato
2026-11-30 13:06 ` [PATCH 6.18.y 3/5] mm/mmu_gather: flush pending references early before the folio limit Pedro Falcato
2026-11-30 13:06 ` [PATCH 6.18.y 4/5] iommufd: fix cleanup when adding memfd folio pins fails Pedro Falcato
2026-11-30 13:06 ` [PATCH 6.18.y 5/5] mm/gup: limit pagecache folio refcount when grabbing references Pedro Falcato
2026-12-02 13:48 ` [PATCH 6.18.y 0/5] Backport of "mm: limit pagecache folio refcount" Sasha Levin

This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.