Linux kernel -stable discussions
 help / color / mirror / Atom feed
* [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount"
@ 2026-11-30 13:24 Pedro Falcato
  2026-11-30 13:24 ` [PATCH 6.12.y 1/6] mm: constify pagemap related test/getter functions Pedro Falcato
                   ` (6 more replies)
  0 siblings, 7 replies; 9+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:24 UTC (permalink / raw)
  To: stable; +Cc: david, Pedro Falcato

Hi,

here's the backport of the "mm: limit pagecache folio refcount" (or part of
it) to v6.18. This wasn't particularly trivial, all patches Kind Of Apply,
except where they don't.

This includes two patches which are dependencies (not present in the v6.18
series).

Also note that this doesn't include the iommufd patch, as it blamed commit
was only introduced in 6.13.

These backports do not include the net fixes, which haven't hit
mainline yet.

I'm probably stopping here. I tried on our (downstream) 6.4 kernel and
nothing applies. I fully expect it to not apply on 6.6 LTS, and other
vintage kernels.

Anyway, please consider for stable.

To: stable@vger.kernel.org
Cc: linux-mm@kvack.org
Cc: "David Hildenbrand (Arm)" <david@kernel.org>

David Hildenbrand (Arm) (4):
  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
  mm/gup: limit pagecache folio refcount when grabbing references

Matthew Wilcox (Oracle) (1):
  filemap: Add folio_next_pos()

Max Kellermann (1):
  mm: constify pagemap related test/getter functions

 fs/fuse/dev.c             |  5 ++-
 fs/ocfs2/alloc.c          |  2 +-
 include/asm-generic/tlb.h |  6 +--
 include/linux/mm.h        | 89 +++++++++++++++++++++++++++++++++------
 include/linux/pagemap.h   | 66 +++++++++++++++++------------
 mm/filemap.c              | 29 ++++++++-----
 mm/gup.c                  | 32 +++++++++-----
 mm/huge_memory.c          | 10 +++++
 mm/internal.h             |  4 +-
 mm/memory.c               | 39 ++++++++++++++---
 mm/migrate.c              | 11 +++++
 mm/mmu_gather.c           | 10 +++--
 mm/shmem.c                |  7 ++-
 mm/userfaultfd.c          |  4 ++
 mm/util.c                 | 26 ++++++++++++
 15 files changed, 259 insertions(+), 81 deletions(-)

-- 
2.56.0


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

* [PATCH 6.12.y 1/6] mm: constify pagemap related test/getter functions
  2026-11-30 13:24 [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
@ 2026-11-30 13:24 ` Pedro Falcato
  2026-11-30 13:24 ` [PATCH 6.12.y 2/6] filemap: Add folio_next_pos() Pedro Falcato
                   ` (5 subsequent siblings)
  6 siblings, 0 replies; 9+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:24 UTC (permalink / raw)
  To: stable
  Cc: david, Max Kellermann, Vishal Moola (Oracle), Lorenzo Stoakes,
	David Hildenbrand, Vlastimil Babka, Mike Rapoport (Microsoft),
	Shakeel Butt, Andrew Morton, Pedro Falcato

From: Max Kellermann <max.kellermann@ionos.com>

commit 7c3e97ac0d75306d9d03de575c9878f8fd9efe3b upstream.

For improved const-correctness.

We select certain test functions which either invoke each other, functions
that are already const-ified, or no further functions.

It is therefore relatively trivial to const-ify them, which provides a
basis for further const-ification further up the call stack.

Link: https://lkml.kernel.org/r/20250901205021.3573313-3-max.kellermann@ionos.com
Signed-off-by: Max Kellermann <max.kellermann@ionos.com>
Reviewed-by: Vishal Moola (Oracle) <vishal.moola@gmail.com>
Reviewed-by: Lorenzo Stoakes <lorenzo.stoakes@oracle.com>
Acked-by: David Hildenbrand <david@redhat.com>
Acked-by: Vlastimil Babka <vbabka@suse.cz>
Acked-by: Mike Rapoport (Microsoft) <rppt@kernel.org>
Acked-by: Shakeel Butt <shakeel.butt@linux.dev>
Cc: Alexander Gordeev <agordeev@linux.ibm.com>
Cc: Al Viro <viro@zeniv.linux.org.uk>
Cc: Andreas Larsson <andreas@gaisler.com>
Cc: Andy Lutomirski <luto@kernel.org>
Cc: Axel Rasmussen <axelrasmussen@google.com>
Cc: Baolin Wang <baolin.wang@linux.alibaba.com>
Cc: Borislav Betkov <bp@alien8.de>
Cc: Christian Borntraeger <borntraeger@linux.ibm.com>
Cc: Christian Brauner <brauner@kernel.org>
Cc: Christian Zankel <chris@zankel.net>
Cc: David Rientjes <rientjes@google.com>
Cc: David S. Miller <davem@davemloft.net>
Cc: Gerald Schaefer <gerald.schaefer@linux.ibm.com>
Cc: Heiko Carstens <hca@linux.ibm.com>
Cc: Helge Deller <deller@gmx.de>
Cc: "H. Peter Anvin" <hpa@zytor.com>
Cc: Hugh Dickins <hughd@google.com>
Cc: Ingo Molnar <mingo@redhat.com>
Cc: James Bottomley <james.bottomley@HansenPartnership.com>
Cc: Jan Kara <jack@suse.cz>
Cc: Jocelyn Falempe <jfalempe@redhat.com>
Cc: Liam Howlett <liam.howlett@oracle.com>
Cc: Mark Brown <broonie@kernel.org>
Cc: Matthew Wilcox (Oracle) <willy@infradead.org>
Cc: Max Filippov <jcmvbkbc@gmail.com>
Cc: Michael Ellerman <mpe@ellerman.id.au>
Cc: Michal Hocko <mhocko@suse.com>
Cc: "Nysal Jan K.A" <nysal@linux.ibm.com>
Cc: Oscar Salvador <osalvador@suse.de>
Cc: Peter Zijlstra <peterz@infradead.org>
Cc: Russel King <linux@armlinux.org.uk>
Cc: Suren Baghdasaryan <surenb@google.com>
Cc: Sven Schnelle <svens@linux.ibm.com>
Cc: Thomas Gleinxer <tglx@linutronix.de>
Cc: Thomas Huth <thuth@redhat.com>
Cc: Vasily Gorbik <gor@linux.ibm.com>
Cc: Wei Xu <weixugc@google.com>
Cc: Yuanchu Xie <yuanchu@google.com>
Signed-off-by: Andrew Morton <akpm@linux-foundation.org>
Stable-dep-of: 4511fd86db6f ("filemap: Add folio_next_pos()")
[pfalcato: massage this for 6.12]
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 include/linux/pagemap.h | 55 +++++++++++++++++++++--------------------
 1 file changed, 28 insertions(+), 27 deletions(-)

diff --git a/include/linux/pagemap.h b/include/linux/pagemap.h
index 01717aa4a054..97e9690394db 100644
--- a/include/linux/pagemap.h
+++ b/include/linux/pagemap.h
@@ -140,7 +140,7 @@ static inline int inode_drain_writes(struct inode *inode)
 	return filemap_write_and_wait(inode->i_mapping);
 }
 
-static inline bool mapping_empty(struct address_space *mapping)
+static inline bool mapping_empty(const struct address_space *mapping)
 {
 	return xa_empty(&mapping->i_pages);
 }
@@ -166,7 +166,7 @@ static inline bool mapping_empty(struct address_space *mapping)
  * refcount and the referenced bit, which will be elevated or set in
  * the process of adding new cache pages to an inode.
  */
-static inline bool mapping_shrinkable(struct address_space *mapping)
+static inline bool mapping_shrinkable(const struct address_space *mapping)
 {
 	void *head;
 
@@ -264,7 +264,7 @@ static inline void mapping_clear_unevictable(struct address_space *mapping)
 	clear_bit(AS_UNEVICTABLE, &mapping->flags);
 }
 
-static inline bool mapping_unevictable(struct address_space *mapping)
+static inline bool mapping_unevictable(const struct address_space *mapping)
 {
 	return mapping && test_bit(AS_UNEVICTABLE, &mapping->flags);
 }
@@ -274,7 +274,7 @@ static inline void mapping_set_exiting(struct address_space *mapping)
 	set_bit(AS_EXITING, &mapping->flags);
 }
 
-static inline int mapping_exiting(struct address_space *mapping)
+static inline int mapping_exiting(const struct address_space *mapping)
 {
 	return test_bit(AS_EXITING, &mapping->flags);
 }
@@ -284,7 +284,7 @@ static inline void mapping_set_no_writeback_tags(struct address_space *mapping)
 	set_bit(AS_NO_WRITEBACK_TAGS, &mapping->flags);
 }
 
-static inline int mapping_use_writeback_tags(struct address_space *mapping)
+static inline int mapping_use_writeback_tags(const struct address_space *mapping)
 {
 	return !test_bit(AS_NO_WRITEBACK_TAGS, &mapping->flags);
 }
@@ -330,18 +330,18 @@ static inline void mapping_set_inaccessible(struct address_space *mapping)
 	set_bit(AS_INACCESSIBLE, &mapping->flags);
 }
 
-static inline bool mapping_inaccessible(struct address_space *mapping)
+static inline bool mapping_inaccessible(const struct address_space *mapping)
 {
 	return test_bit(AS_INACCESSIBLE, &mapping->flags);
 }
 
-static inline gfp_t mapping_gfp_mask(struct address_space * mapping)
+static inline gfp_t mapping_gfp_mask(const struct address_space * mapping)
 {
 	return mapping->gfp_mask;
 }
 
 /* Restricts the given gfp_mask to what the mapping allows. */
-static inline gfp_t mapping_gfp_constraint(struct address_space *mapping,
+static inline gfp_t mapping_gfp_constraint(const struct address_space *mapping,
 		gfp_t gfp_mask)
 {
 	return mapping_gfp_mask(mapping) & gfp_mask;
@@ -464,7 +464,7 @@ mapping_min_folio_order(const struct address_space *mapping)
 }
 
 static inline unsigned long
-mapping_min_folio_nrpages(struct address_space *mapping)
+mapping_min_folio_nrpages(const struct address_space *mapping)
 {
 	return 1UL << mapping_min_folio_order(mapping);
 }
@@ -478,7 +478,7 @@ mapping_min_folio_nrpages(struct address_space *mapping)
  * new folio to the page cache and need to know what index to give it,
  * call this function.
  */
-static inline pgoff_t mapping_align_index(struct address_space *mapping,
+static inline pgoff_t mapping_align_index(const struct address_space *mapping,
 					  pgoff_t index)
 {
 	return round_down(index, mapping_min_folio_nrpages(mapping));
@@ -488,7 +488,7 @@ static inline pgoff_t mapping_align_index(struct address_space *mapping,
  * Large folio support currently depends on THP.  These dependencies are
  * being worked on but are not yet fixed.
  */
-static inline bool mapping_large_folio_support(struct address_space *mapping)
+static inline bool mapping_large_folio_support(const struct address_space *mapping)
 {
 	/* AS_FOLIO_ORDER is only reasonable for pagecache folios */
 	VM_WARN_ONCE((unsigned long)mapping & PAGE_MAPPING_ANON,
@@ -503,7 +503,7 @@ static inline size_t mapping_max_folio_size(const struct address_space *mapping)
 	return PAGE_SIZE << mapping_max_folio_order(mapping);
 }
 
-static inline int filemap_nr_thps(struct address_space *mapping)
+static inline int filemap_nr_thps(const struct address_space *mapping)
 {
 #ifdef CONFIG_READ_ONLY_THP_FOR_FS
 	return atomic_read(&mapping->nr_thps);
@@ -933,7 +933,7 @@ static inline pgoff_t folio_index(struct folio *folio)
  *
  * Return: The index of the folio which follows this folio in the file.
  */
-static inline pgoff_t folio_next_index(struct folio *folio)
+static inline pgoff_t folio_next_index(const struct folio *folio)
 {
 	return folio->index + folio_nr_pages(folio);
 }
@@ -963,9 +963,9 @@ static inline struct page *folio_file_page(struct folio *folio, pgoff_t index)
  * and changing its index in the middle of the operation.
  * Return: true or false.
  */
-static inline bool folio_contains(struct folio *folio, pgoff_t index)
+static inline bool folio_contains(const struct folio *folio, pgoff_t index)
 {
-	return index - folio_index(folio) < folio_nr_pages(folio);
+	return index - folio_index((struct folio *) folio) < folio_nr_pages(folio);
 }
 
 /*
@@ -1059,13 +1059,13 @@ static inline loff_t folio_pos(struct folio *folio)
 /*
  * Get the offset in PAGE_SIZE (even for hugetlb folios).
  */
-static inline pgoff_t folio_pgoff(struct folio *folio)
+static inline pgoff_t folio_pgoff(const struct folio *folio)
 {
 	return folio->index;
 }
 
-static inline pgoff_t linear_page_index(struct vm_area_struct *vma,
-					unsigned long address)
+static inline pgoff_t linear_page_index(const struct vm_area_struct *vma,
+					const unsigned long address)
 {
 	pgoff_t pgoff;
 	pgoff = (address - vma->vm_start) >> PAGE_SHIFT;
@@ -1526,7 +1526,7 @@ static inline unsigned int __readahead_batch(struct readahead_control *rac,
  * readahead_pos - The byte offset into the file of this readahead request.
  * @rac: The readahead request.
  */
-static inline loff_t readahead_pos(struct readahead_control *rac)
+static inline loff_t readahead_pos(const struct readahead_control *rac)
 {
 	return (loff_t)rac->_index * PAGE_SIZE;
 }
@@ -1535,7 +1535,7 @@ static inline loff_t readahead_pos(struct readahead_control *rac)
  * readahead_length - The number of bytes in this readahead request.
  * @rac: The readahead request.
  */
-static inline size_t readahead_length(struct readahead_control *rac)
+static inline size_t readahead_length(const struct readahead_control *rac)
 {
 	return rac->_nr_pages * PAGE_SIZE;
 }
@@ -1544,7 +1544,7 @@ static inline size_t readahead_length(struct readahead_control *rac)
  * readahead_index - The index of the first page in this readahead request.
  * @rac: The readahead request.
  */
-static inline pgoff_t readahead_index(struct readahead_control *rac)
+static inline pgoff_t readahead_index(const struct readahead_control *rac)
 {
 	return rac->_index;
 }
@@ -1553,7 +1553,7 @@ static inline pgoff_t readahead_index(struct readahead_control *rac)
  * readahead_count - The number of pages in this readahead request.
  * @rac: The readahead request.
  */
-static inline unsigned int readahead_count(struct readahead_control *rac)
+static inline unsigned int readahead_count(const struct readahead_control *rac)
 {
 	return rac->_nr_pages;
 }
@@ -1562,12 +1562,12 @@ static inline unsigned int readahead_count(struct readahead_control *rac)
  * readahead_batch_length - The number of bytes in the current batch.
  * @rac: The readahead request.
  */
-static inline size_t readahead_batch_length(struct readahead_control *rac)
+static inline size_t readahead_batch_length(const struct readahead_control *rac)
 {
 	return rac->_batch_count * PAGE_SIZE;
 }
 
-static inline unsigned long dir_pages(struct inode *inode)
+static inline unsigned long dir_pages(const struct inode *inode)
 {
 	return (unsigned long)(inode->i_size + PAGE_SIZE - 1) >>
 			       PAGE_SHIFT;
@@ -1581,8 +1581,8 @@ static inline unsigned long dir_pages(struct inode *inode)
  * Return: the number of bytes in the folio up to EOF,
  * or -EFAULT if the folio was truncated.
  */
-static inline ssize_t folio_mkwrite_check_truncate(struct folio *folio,
-					      struct inode *inode)
+static inline ssize_t folio_mkwrite_check_truncate(const struct folio *folio,
+						   const struct inode *inode)
 {
 	loff_t size = i_size_read(inode);
 	pgoff_t index = size >> PAGE_SHIFT;
@@ -1641,7 +1641,8 @@ static inline int page_mkwrite_check_truncate(struct page *page,
  * Return: The number of filesystem blocks covered by this folio.
  */
 static inline
-unsigned int i_blocks_per_folio(struct inode *inode, struct folio *folio)
+unsigned int i_blocks_per_folio(const struct inode *inode,
+				const struct folio *folio)
 {
 	return folio_size(folio) >> inode->i_blkbits;
 }
-- 
2.56.0


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

* [PATCH 6.12.y 2/6] filemap: Add folio_next_pos()
  2026-11-30 13:24 [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
  2026-11-30 13:24 ` [PATCH 6.12.y 1/6] mm: constify pagemap related test/getter functions Pedro Falcato
@ 2026-11-30 13:24 ` Pedro Falcato
  2026-11-30 13:24 ` [PATCH 6.12.y 3/6] mm: limit pagecache folio refcount when mapping pages Pedro Falcato
                   ` (4 subsequent siblings)
  6 siblings, 0 replies; 9+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:24 UTC (permalink / raw)
  To: stable
  Cc: david, Matthew Wilcox (Oracle), Joseph Qi, Christoph Hellwig,
	Christian Brauner, Pedro Falcato

From: "Matthew Wilcox (Oracle)" <willy@infradead.org>

commit 4511fd86db6f8f94f8aff01044f5c69aa38f81f4 upstream.

Replace the open-coded implementation in ocfs2 (which loses the top
32 bits on 32-bit architectures) with a helper in pagemap.h.

Fixes: 35edec1d52c0 (ocfs2: update truncate handling of partial clusters)
Signed-off-by: Matthew Wilcox (Oracle) <willy@infradead.org>
Link: https://patch.msgid.link/20251024170822.1427218-2-willy@infradead.org
Reviewed-by: Joseph Qi <joseph.qi@linux.alibaba.com>
Reviewed-by: Christoph Hellwig <hch@lst.de>
Cc: Mark Fasheh <mark@fasheh.com>
Cc: Joel Becker <jlbec@evilplan.org>
Cc: Joseph Qi <joseph.qi@linux.alibaba.com>
Cc: ocfs2-devel@lists.linux.dev
Signed-off-by: Christian Brauner <brauner@kernel.org>
[pfalcato: ocfs2 is page-based in 6.12, use page_offset() there]
Stable-dep-of: c6c9a4c1c9a1 ("mm: limit pagecache folio refcount when splicing into pipes")
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 fs/ocfs2/alloc.c        |  2 +-
 include/linux/pagemap.h | 11 +++++++++++
 2 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/fs/ocfs2/alloc.c b/fs/ocfs2/alloc.c
index f33aa48a3bc5..cb86ba1ecc80 100644
--- a/fs/ocfs2/alloc.c
+++ b/fs/ocfs2/alloc.c
@@ -6885,7 +6885,7 @@ static void ocfs2_zero_cluster_pages(struct inode *inode, loff_t start,
 		ocfs2_map_and_dirty_page(inode, handle, from, to, page, 1,
 					 &phys);
 
-		start = (page->index + 1) << PAGE_SHIFT;
+		start = page_offset(page) + PAGE_SIZE;
 	}
 out:
 	if (pages)
diff --git a/include/linux/pagemap.h b/include/linux/pagemap.h
index 97e9690394db..aabf0de22729 100644
--- a/include/linux/pagemap.h
+++ b/include/linux/pagemap.h
@@ -938,6 +938,17 @@ static inline pgoff_t folio_next_index(const struct folio *folio)
 	return folio->index + folio_nr_pages(folio);
 }
 
+/**
+ * folio_next_pos - Get the file position of the next folio.
+ * @folio: The current folio.
+ *
+ * Return: The position of the folio which follows this folio in the file.
+ */
+static inline loff_t folio_next_pos(const struct folio *folio)
+{
+	return (loff_t)folio_next_index(folio) << PAGE_SHIFT;
+}
+
 /**
  * folio_file_page - The page for a particular index.
  * @folio: The folio which contains this index.
-- 
2.56.0


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

* [PATCH 6.12.y 3/6] mm: limit pagecache folio refcount when mapping pages
  2026-11-30 13:24 [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
  2026-11-30 13:24 ` [PATCH 6.12.y 1/6] mm: constify pagemap related test/getter functions Pedro Falcato
  2026-11-30 13:24 ` [PATCH 6.12.y 2/6] filemap: Add folio_next_pos() Pedro Falcato
@ 2026-11-30 13:24 ` Pedro Falcato
  2026-11-30 13:24 ` [PATCH 6.12.y 4/6] mm: limit pagecache folio refcount when splicing into pipes Pedro Falcato
                   ` (3 subsequent siblings)
  6 siblings, 0 replies; 9+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:24 UTC (permalink / raw)
  To: stable
  Cc: david, Chris Mason, Jose A. Perez de Azpillaga, Zi Yan,
	Pedro Falcato

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

commit 26b8f029ce5224dd5c5f45a4bc964a209c259914 upstream.

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>
[pfalcato: drop most of huge_memory.c changes (DAX pages are not refcounted in 6.12), massage]
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 include/linux/mm.h | 36 ++++++++++++++++++++++++++++++++----
 mm/filemap.c       |  2 ++
 mm/huge_memory.c   | 10 ++++++++++
 mm/memory.c        | 35 +++++++++++++++++++++++++++++++----
 mm/migrate.c       | 11 +++++++++++
 mm/userfaultfd.c   |  4 ++++
 mm/util.c          | 26 ++++++++++++++++++++++++++
 7 files changed, 116 insertions(+), 8 deletions(-)

diff --git a/include/linux/mm.h b/include/linux/mm.h
index a6348b25aee2..a600d6c4c311 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -1457,9 +1457,37 @@ static inline bool put_devmap_managed_folio_refs(struct folio *folio, int refs)
 }
 #endif /* CONFIG_ZONE_DEVICE && CONFIG_FS_DAX */
 
-/* 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.
@@ -1471,7 +1499,7 @@ static inline bool put_devmap_managed_folio_refs(struct folio *folio, int refs)
  */
 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 76efdb1e1b78..dc3267690654 100644
--- a/mm/filemap.c
+++ b/mm/filemap.c
@@ -3506,6 +3506,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;
 		/* Has the page moved or been split? */
 		if (unlikely(folio != xas_reload(xas)))
 			goto skip;
diff --git a/mm/huge_memory.c b/mm/huge_memory.c
index 6cd88cd4b33b..6d5a615107a8 100644
--- a/mm/huge_memory.c
+++ b/mm/huge_memory.c
@@ -4381,6 +4381,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 = mk_huge_pmd(new, READ_ONCE(vma->vm_page_prot));
diff --git a/mm/memory.c b/mm/memory.c
index 37b039cc7ba3..484088946106 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -975,7 +975,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,
@@ -994,6 +997,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
@@ -1170,9 +1185,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)) {
 			/*
@@ -1202,7 +1217,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);
@@ -2052,6 +2067,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);
 		inc_mm_counter(vma->vm_mm, mm_counter_file(folio));
 		folio_add_file_rmap_pte(folio, page, vma);
@@ -4994,6 +5011,9 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
 	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.
@@ -5048,6 +5068,9 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct page *page)
  * @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)
@@ -5218,6 +5241,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 66af1dd6a941..8f57b302f2ad 100644
--- a/mm/migrate.c
+++ b/mm/migrate.c
@@ -322,6 +322,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/userfaultfd.c b/mm/userfaultfd.c
index 6a575335bc6f..f592f92c7407 100644
--- a/mm/userfaultfd.c
+++ b/mm/userfaultfd.c
@@ -211,6 +211,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);
diff --git a/mm/util.c b/mm/util.c
index 8c6d8d4d62c4..af1531a092ce 100644
--- a/mm/util.c
+++ b/mm/util.c
@@ -1248,3 +1248,29 @@ void flush_dcache_folio(struct folio *folio)
 }
 EXPORT_SYMBOL(flush_dcache_folio);
 #endif
+
+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((struct folio *) folio), folio->index);
+	return true;
+}
+EXPORT_SYMBOL_GPL(folio_ref_count_over_limit_slowpath);
-- 
2.56.0


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

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

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

commit c6c9a4c1c9a1669693330205cb9d86fafd3cf235 upstream.

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>
[pfalcato: fixup fuse_ref_page changes for folios, filemap_splice_read pipe_full check]
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 fs/fuse/dev.c      |  5 ++++-
 include/linux/mm.h | 49 ++++++++++++++++++++++++++++++++++++++--------
 mm/filemap.c       | 27 +++++++++++++++----------
 mm/internal.h      |  4 ++--
 mm/shmem.c         |  7 +++++--
 5 files changed, 69 insertions(+), 23 deletions(-)

diff --git a/fs/fuse/dev.c b/fs/fuse/dev.c
index 27ce1f1bcfe1..d0374e2bcb23 100644
--- a/fs/fuse/dev.c
+++ b/fs/fuse/dev.c
@@ -938,13 +938,16 @@ static int fuse_try_move_page(struct fuse_copy_state *cs, struct page **pagep)
 static int fuse_ref_page(struct fuse_copy_state *cs, struct page *page,
 			 unsigned offset, unsigned count)
 {
+	struct folio *folio = page_folio(page);
 	struct pipe_buffer *buf;
 	int err;
 
 	if (cs->nr_segs >= cs->pipe->max_usage)
 		return -EIO;
 
-	get_page(page);
+	if (!folio_get_checked(folio))
+		return -EFAULT;
+
 	err = unlock_request(cs->req);
 	if (err) {
 		put_page(page);
diff --git a/include/linux/mm.h b/include/linux/mm.h
index a600d6c4c311..6341c9433dfb 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -1465,8 +1465,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
@@ -1480,15 +1481,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.
@@ -1508,15 +1521,35 @@ static inline void get_page(struct page *page)
 	folio_get(page_folio(page));
 }
 
-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 dc3267690654..17148fffc124 100644
--- a/mm/filemap.c
+++ b/mm/filemap.c
@@ -2848,10 +2848,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);
@@ -2865,13 +2866,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;
@@ -2896,9 +2899,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,
@@ -2956,7 +2960,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;
@@ -2972,13 +2976,16 @@ 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_full(pipe->head, pipe->tail, pipe->max_usage))
+			if (pipe_full(pipe->head, pipe->tail, pipe->max_usage) ||
+			    *ppos < folio_next_pos(folio))
 				goto out;
 		}
 
diff --git a/mm/internal.h b/mm/internal.h
index ba332da196e4..b259d3afe1f4 100644
--- a/mm/internal.h
+++ b/mm/internal.h
@@ -1279,8 +1279,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 1693aa906227..b40595fda88b 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -3373,7 +3373,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;
 
@@ -3437,8 +3438,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] 9+ messages in thread

* [PATCH 6.12.y 5/6] mm/mmu_gather: flush pending references early before the folio limit
  2026-11-30 13:24 [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
                   ` (3 preceding siblings ...)
  2026-11-30 13:24 ` [PATCH 6.12.y 4/6] mm: limit pagecache folio refcount when splicing into pipes Pedro Falcato
@ 2026-11-30 13:24 ` Pedro Falcato
  2026-11-30 13:24 ` [PATCH 6.12.y 6/6] mm/gup: limit pagecache folio refcount when grabbing references Pedro Falcato
  2026-11-30 13:38 ` [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
  6 siblings, 0 replies; 9+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:24 UTC (permalink / raw)
  To: stable
  Cc: david, Chris Mason, Jose A. Perez de Azpillaga, Lance Yang,
	Pedro Falcato

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

commit 317bd7d28b248fd4d4e14614d7c30b17a36ef4d7 upstream.

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>
[pfalcato: massage comment]
Signed-off-by: Pedro Falcato <pfalcato@suse.de>
---
 include/asm-generic/tlb.h |  6 +++---
 include/linux/mm.h        |  1 +
 mm/memory.c               |  4 ++--
 mm/mmu_gather.c           | 10 ++++++----
 4 files changed, 12 insertions(+), 9 deletions(-)

diff --git a/include/asm-generic/tlb.h b/include/asm-generic/tlb.h
index c046a09b0b48..b4f690a62305 100644
--- a/include/asm-generic/tlb.h
+++ b/include/asm-generic/tlb.h
@@ -73,9 +73,9 @@
  *  - __tlb_remove_folio_pages()
  *
  *    __tlb_remove_page_size() is the basic primitive that queues a page for
- *    freeing. __tlb_remove_page() assumes PAGE_SIZE. Both will return a
- *    boolean indicating if the queue is (now) full and a call to
- *    tlb_flush_mmu() is required.
+ *    freeing. __tlb_remove_page() assumes PAGE_SIZE. They return 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 6341c9433dfb..e8c676fe8451 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -1460,6 +1460,7 @@ static inline bool put_devmap_managed_folio_refs(struct folio *folio, int refs)
 /* 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 484088946106..a6a127c5a825 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -1704,8 +1704,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 04469b481b93..fc705de6a3bb 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] 9+ messages in thread

* [PATCH 6.12.y 6/6] mm/gup: limit pagecache folio refcount when grabbing references
  2026-11-30 13:24 [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
                   ` (4 preceding siblings ...)
  2026-11-30 13:24 ` [PATCH 6.12.y 5/6] mm/mmu_gather: flush pending references early before the folio limit Pedro Falcato
@ 2026-11-30 13:24 ` Pedro Falcato
  2026-11-30 13:38 ` [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
  6 siblings, 0 replies; 9+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:24 UTC (permalink / raw)
  To: stable; +Cc: david, Jose A. Perez de Azpillaga, Pedro Falcato

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

commit 2d9bcd380585abc436f055fbb618b34f98882004 upstream.

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>
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 e8c676fe8451..b46deb18495e 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -1474,6 +1474,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
@@ -2030,12 +2033,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 d9107eb461a0..c6f5c84f4f80 100644
--- a/mm/gup.c
+++ b/mm/gup.c
@@ -78,10 +78,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;
@@ -146,7 +150,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) && is_pci_p2pdma_page(&folio->page)))
@@ -1547,17 +1557,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;
 				}
 			}
@@ -3785,10 +3795,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] 9+ messages in thread

* Re: [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount"
  2026-11-30 13:24 [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
                   ` (5 preceding siblings ...)
  2026-11-30 13:24 ` [PATCH 6.12.y 6/6] mm/gup: limit pagecache folio refcount when grabbing references Pedro Falcato
@ 2026-11-30 13:38 ` Pedro Falcato
  2026-11-30 15:43   ` David Hildenbrand (Arm)
  6 siblings, 1 reply; 9+ messages in thread
From: Pedro Falcato @ 2026-11-30 13:38 UTC (permalink / raw)
  To: stable; +Cc: david, linux-mm

+CC linux-mm

Of course I had to mess up when playing with send-email CC supression :)
Please see https://lore.kernel.org/stable/20261130132456.391567-1-pfalcato@suse.de/
for the full backports.

On Mon, Nov 30, 2026 at 01:24:50PM +0000, Pedro Falcato wrote:
> Hi,
> 
> here's the backport of the "mm: limit pagecache folio refcount" (or part of
> it) to v6.18. This wasn't particularly trivial, all patches Kind Of Apply,
> except where they don't.
> 
> This includes two patches which are dependencies (not present in the v6.18
> series).
> 
> Also note that this doesn't include the iommufd patch, as it blamed commit
> was only introduced in 6.13.
> 
> These backports do not include the net fixes, which haven't hit
> mainline yet.
> 
> I'm probably stopping here. I tried on our (downstream) 6.4 kernel and
> nothing applies. I fully expect it to not apply on 6.6 LTS, and other
> vintage kernels.
> 
> Anyway, please consider for stable.
> 
> To: stable@vger.kernel.org
> Cc: linux-mm@kvack.org
> Cc: "David Hildenbrand (Arm)" <david@kernel.org>
> 
> David Hildenbrand (Arm) (4):
>   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
>   mm/gup: limit pagecache folio refcount when grabbing references
> 
> Matthew Wilcox (Oracle) (1):
>   filemap: Add folio_next_pos()
> 
> Max Kellermann (1):
>   mm: constify pagemap related test/getter functions
> 
>  fs/fuse/dev.c             |  5 ++-
>  fs/ocfs2/alloc.c          |  2 +-
>  include/asm-generic/tlb.h |  6 +--
>  include/linux/mm.h        | 89 +++++++++++++++++++++++++++++++++------
>  include/linux/pagemap.h   | 66 +++++++++++++++++------------
>  mm/filemap.c              | 29 ++++++++-----
>  mm/gup.c                  | 32 +++++++++-----
>  mm/huge_memory.c          | 10 +++++
>  mm/internal.h             |  4 +-
>  mm/memory.c               | 39 ++++++++++++++---
>  mm/migrate.c              | 11 +++++
>  mm/mmu_gather.c           | 10 +++--
>  mm/shmem.c                |  7 ++-
>  mm/userfaultfd.c          |  4 ++
>  mm/util.c                 | 26 ++++++++++++
>  15 files changed, 259 insertions(+), 81 deletions(-)
> 
> -- 
> 2.56.0
> 

-- 
Pedro

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

* Re: [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount"
  2026-11-30 13:38 ` [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
@ 2026-11-30 15:43   ` David Hildenbrand (Arm)
  0 siblings, 0 replies; 9+ messages in thread
From: David Hildenbrand (Arm) @ 2026-11-30 15:43 UTC (permalink / raw)
  To: Pedro Falcato, stable; +Cc: linux-mm

On 11/30/26 14:38, Pedro Falcato wrote:
> +CC linux-mm
> 
> Of course I had to mess up when playing with send-email CC supression :)
> Please see https://lore.kernel.org/stable/20261130132456.391567-1-pfalcato@suse.de/
> for the full backports.

Thanks for taking care of these, highly appreciated!

-- 
Cheers,

David

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

end of thread, other threads:[~2026-11-30 15:43 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-30 13:24 [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
2026-11-30 13:24 ` [PATCH 6.12.y 1/6] mm: constify pagemap related test/getter functions Pedro Falcato
2026-11-30 13:24 ` [PATCH 6.12.y 2/6] filemap: Add folio_next_pos() Pedro Falcato
2026-11-30 13:24 ` [PATCH 6.12.y 3/6] mm: limit pagecache folio refcount when mapping pages Pedro Falcato
2026-11-30 13:24 ` [PATCH 6.12.y 4/6] mm: limit pagecache folio refcount when splicing into pipes Pedro Falcato
2026-11-30 13:24 ` [PATCH 6.12.y 5/6] mm/mmu_gather: flush pending references early before the folio limit Pedro Falcato
2026-11-30 13:24 ` [PATCH 6.12.y 6/6] mm/gup: limit pagecache folio refcount when grabbing references Pedro Falcato
2026-11-30 13:38 ` [PATCH 6.12.y 0/6] Backport of "mm: limit pagecache folio refcount" Pedro Falcato
2026-11-30 15:43   ` David Hildenbrand (Arm)

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