From 043a2260b96ffc13121a1dd65282e67eb2e1d8a8 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 5 Nov 2026 19:16:44 +0100 Subject: mm/khugepaged: don't map folios that are not uptodate in MADV_COLLAPSE madvise(MADV_COLLAPSE) can map PMD-sized pagecache folios that are not uptodate. For example, shmem fallocate() can put such folios into the page cache. collapse_file() already refuses to proceed with folios that are not uptodate. Let's just do the same in try_collapse_pte_mapped_thp() and skip such folios, leaving handling to the page faults. Note that collapse_file() effectively clears shmem folios through shmem_get_folio(); let's keep this fix simple and simply let the page fault path deal with that. Fixes: 34488399fa08 ("mm/madvise: add file and shmem support to MADV_COLLAPSE") Reported-by: Chris Mason Cc: stable@vger.kernel.org Reviewed-by: Lorenzo Stoakes (ARM) Acked-by: Hugh Dickins Acked-by: Zi Yan Reviewed-by: Zach O'Keefe Reviewed-by: SJ Park Reviewed-by: Baolin Wang Reviewed-by: Lance Yang Reviewed-by: Kiryl Shutsemau (Meta) Link: https://patch.msgid.link/20261105-set_huge_pmd_uptodate-v1-1-a78d8a1b7117@kernel.org Reviewed-by: Pedro Falcato Signed-off-by: David Hildenbrand (Arm) --- mm/khugepaged.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mm/khugepaged.c b/mm/khugepaged.c index 4bbe319ef86f..964f78c3856b 100644 --- a/mm/khugepaged.c +++ b/mm/khugepaged.c @@ -1888,6 +1888,12 @@ static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsign goto drop_folio; } + /* Leave any uninitialized folios to the page fault path. */ + if (!folio_test_uptodate(folio)) { + result = SCAN_FAIL; + goto drop_folio; + } + result = find_pmd_or_thp_or_none(mm, haddr, &pmd); switch (result) { case SCAN_SUCCEED: -- cgit v1.3.1-4-g156e From d369ba5a46c65c54b94c94713ca1fb4ad6a87ebf Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Tue, 3 Nov 2026 19:31:44 +0100 Subject: mm/memfd: handle GUP pins more reliably when write-sealing memfd_wait_for_pins() detects GUP references by comparing a folio's actual refcount with its expected refcount. As spelled out by folio_expected_ref_count(), obtaining the expected refcount when there can be concurrent folio (un)mapping is racy. So it is possible that a changing folio mapcount can race with our check for GUP references, and F_SEAL_WRITE might succeed even if there are some, allowing file contents to be modified after sealing. For folios with a reliable pincount, detect FOLL_PIN references using folio_maybe_dma_pinned() before falling back to the refcount comparison. For small folios without that, the 1024 pinning BIAS makes it very hard (although not impossible) to misguide the refcount comparison. This improves FOLL_PIN detection for folios with a pincount. Handling FOLL_GET and small folios requires a more fundamental change. Fortunately, most interfaces that allow for GUP'ing such pages use FOLL_PIN, in particular interfaces using FOLL_LONGTERM. However, we still have some FOLL_GET leftovers ... Fixes: 05f65b5c7090 ("shm: wait for pins to be released when sealing") Cc: stable@vger.kernel.org Cc: Chris Mason Reviewed-by: Lorenzo Stoakes (ARM) Link: https://patch.msgid.link/20261103-fixes_core_2-v1-1-f332954f1df4@kernel.org Reviewed-by: Lance Yang Signed-off-by: David Hildenbrand (Arm) --- mm/memfd.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/mm/memfd.c b/mm/memfd.c index 0e3ff3eebfa8..05088ab210ba 100644 --- a/mm/memfd.c +++ b/mm/memfd.c @@ -32,6 +32,13 @@ static bool memfd_folio_has_extra_refs(struct folio *folio) { + /* + * Use the precise pincount where available to avoid racy refcount + * comparisons. + */ + if (folio_has_pincount(folio) && folio_maybe_dma_pinned(folio)) + return true; + return folio_ref_count(folio) != folio_expected_ref_count(folio); } -- cgit v1.3.1-4-g156e From 169169e26ab498e4a3ee07313e986176f4bc52f0 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Wed, 11 Nov 2026 22:59:59 +0100 Subject: mm/userfaultfd: fix PTE table overruns in UFFDIO_MOVE With a folded PMD, pmd_addr_end() simply returns the supplied end. move_present_ptes() can therefore walk past the source or destination PTE table during UFFDIO_MOVE. pmd_addr_end() is only intended for page table traversal, in patterns like "next = pmd_addr_end(addr, end);". With folded PMDs, a higher level has already clamped the range to the PTE table. Folded PMDs are uncommon, but can occur even on arm64, for example with 64K pages and a 42-bit virtual address space. Extract the calculation from folio_pte_range() into pte_table_clamped_end() and use it to clamp both ranges. This preserves the wraparound handling from commit f681d4580d5c ("mm: fix address wraparound when scanning large folio PTEs"). Fixes: 50944692052b ("userfaultfd: opportunistic TLB-flush batching for present pages in MOVE") Cc: stable@vger.kernel.org Reported-by: Chris Mason Reviewed-by: Baolin Wang Link: https://patch.msgid.link/20261111-pte_table_clamped_end-v1-1-2dbe339c487a@kernel.org Reviewed-by: Lokesh Gidra Signed-off-by: David Hildenbrand (Arm) --- include/linux/pgtable.h | 24 ++++++++++++++++++++++++ mm/memory.c | 7 +------ mm/userfaultfd.c | 4 ++-- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/include/linux/pgtable.h b/include/linux/pgtable.h index 780fe849ff8b..66d369870a74 100644 --- a/include/linux/pgtable.h +++ b/include/linux/pgtable.h @@ -12,6 +12,7 @@ #ifdef CONFIG_MMU #include +#include #include #include #include @@ -1518,6 +1519,29 @@ static inline void arch_swap_restore(swp_entry_t entry, struct folio *folio) }) #endif +/** + * pte_table_clamped_end() - Limit a range to a single PTE table. + * @addr: Start address. + * @end: Exclusive end address. + * + * Only use pmd_addr_end() when traversing page tables, in a pattern like:: + * + * next = pmd_addr_end(addr, end); + * + * Higher levels already bound the range when PMDs are folded. Use this + * helper elsewhere to clamp the range regardless of PMD folding. + * + * Return: The exclusive end of the PTE table containing @addr, capped at @end. + */ +static inline unsigned long pte_table_clamped_end(unsigned long addr, + unsigned long end) +{ + const unsigned long pmd_end = (addr & PMD_MASK) + PMD_SIZE; + + /* Compare inclusive ends to avoid wraparounds. */ + return min(pmd_end - 1, end - 1) + 1; +} + /* * When walking page tables, we usually want to skip any p?d_none entries; * and any p?d_bad entries - reporting the error before resetting to none. diff --git a/mm/memory.c b/mm/memory.c index ec3d9d99ccee..ee792a2c0cce 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -4959,13 +4959,8 @@ static void folio_pte_range(const struct folio *folio, { /* Stay within the page table and VMA boundaries. */ const unsigned long pmd_start = addr & PMD_MASK; - const unsigned long pmd_end = pmd_start + PMD_SIZE; const unsigned long lower = max(pmd_start, vma->vm_start); - /* - * We cannot use pmd_addr_end(), as it does not clamp reliably. To - * avoid wraparounds, compute using the inclusive end. - */ - const unsigned long upper = min(pmd_end - 1, vma->vm_end - 1) + 1; + const unsigned long upper = pte_table_clamped_end(addr, vma->vm_end); const unsigned long offset = idx << PAGE_SHIFT; /* diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 169f681f9849..57650e6f040d 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -1266,8 +1266,8 @@ static long move_present_ptes(struct mm_struct *mm, unsigned long src_start = src_addr; unsigned long src_end; - len = pmd_addr_end(dst_addr, dst_addr + len) - dst_addr; - src_end = pmd_addr_end(src_addr, src_addr + len); + len = pte_table_clamped_end(dst_addr, dst_addr + len) - dst_addr; + src_end = pte_table_clamped_end(src_addr, src_addr + len); flush_cache_range(src_vma, src_addr, src_end); double_pt_lock(dst_ptl, src_ptl); -- cgit v1.3.1-4-g156e From d8bbf585893c7868234b71d7e7f32484ed0d8458 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Wed, 11 Nov 2026 23:00:00 +0100 Subject: mm/rmap: fix PTE table overruns during batched unmap With a folded PMD, pmd_addr_end() simply returns the supplied end. folio_unmap_pte_batch() can therefore walk past the PTE table when unmapping a large folio. Folded PMDs are uncommon, but can occur even on arm64, for example with 64K pages and a 42-bit virtual address space. Use pte_table_clamped_end() to clamp the range to the PTE table and VMA boundaries. Fixes: 354dffd29575 ("mm: support batched unmap for lazyfree large folios during reclamation") Cc: stable@vger.kernel.org Reported-by: Chris Mason Reviewed-by: Baolin Wang Link: https://patch.msgid.link/20261111-pte_table_clamped_end-v1-2-2dbe339c487a@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/rmap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mm/rmap.c b/mm/rmap.c index 0faef46806e5..491a954b7fa4 100644 --- a/mm/rmap.c +++ b/mm/rmap.c @@ -1978,7 +1978,7 @@ static inline unsigned int folio_unmap_pte_batch(struct folio *folio, return 1; /* We may only batch within a single VMA and a single page table. */ - end_addr = pmd_addr_end(addr, vma->vm_end); + end_addr = pte_table_clamped_end(addr, vma->vm_end); max_nr = (end_addr - addr) >> PAGE_SHIFT; /* We only support lazyfree or file folios batching for now ... */ -- cgit v1.3.1-4-g156e From 2d9b9352ef885837f246225e9b814a05e9ed2a4a Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Wed, 11 Nov 2026 23:00:01 +0100 Subject: mm/rmap: fix PTE table overruns during batched reference checks With a folded PMD, pmd_addr_end() simply returns the supplied end. folio_referenced_one() can therefore walk past the PTE table when checking references to a large folio. Folded PMDs are uncommon, but can occur even on arm64, for example with 64K pages and a 42-bit virtual address space. Use pte_table_clamped_end() to clamp the range to the PTE table and VMA boundaries. Fixes: 52e054f71840 ("mm: rmap: support batched checks of the references for large folios") Cc: stable@vger.kernel.org Reported-by: Chris Mason Reviewed-by: Baolin Wang Link: https://patch.msgid.link/20261111-pte_table_clamped_end-v1-3-2dbe339c487a@kernel.org Signed-off-by: David Hildenbrand (Arm) --- mm/rmap.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mm/rmap.c b/mm/rmap.c index 491a954b7fa4..65646ed6fc45 100644 --- a/mm/rmap.c +++ b/mm/rmap.c @@ -973,7 +973,7 @@ static bool folio_referenced_one(struct folio *folio, pteval = ptep_get(pvmw.pte); if (pvmw.pte && pte_present(pteval) && folio_test_large(folio)) { - const unsigned long end_addr = pmd_addr_end(address, vma->vm_end); + const unsigned long end_addr = pte_table_clamped_end(address, vma->vm_end); const unsigned int max_nr = (end_addr - address) >> PAGE_SHIFT; nr = folio_pte_batch(folio, pvmw.pte, pteval, max_nr); -- cgit v1.3.1-4-g156e From 7183af7f01c839ecef87840a90c0d8c5843f37d7 Mon Sep 17 00:00:00 2001 From: Zi Yan Date: Tue, 10 Nov 2026 22:19:25 -0500 Subject: mm/huge_memory: prevent losing PG_waiters in __split_folio_to_order() __split_folio_to_order() calls prep_compound_page() on each new head page to create a compound page after clear_compound_head(). prep_compound_page() uses non atomic __SetPageHead(). It is mostly OK, since the folio is locked and frozen and no one else is supposed to modify the folio's flags. However, code calling migration_entry_wait() can reach the folio by PFN, then access its flags. It is because softleaf_entry_wait_on_locked() used by migration_entry_wait() sets PG_waiters concurrently without taking a reference and the frozen refcount during split cannot block it. Meanwhile, __SetPageHead() does a plain read and write, so PG_waiters atomically set by softleaf_entry_wait_on_locked() will be lost if the set happens after __SetPageHead()'s read and before its write. One example code interleaving: CPU0: __split_folio_to_order(new_order>0) CPU1: do_swap_page() 1. clear_compound_head(new_head) new_head->compound_info = 0 (page_folio(new_head) == new_head now) 2. migration_entry_wait() softleaf_to_folio(entry) page_folio() -> new_head (not the old head any more) 3. prep_compound_page(new_head, new_order) __SetPageHead(new_head) tmp = new_head->flags.f <-- load; PG_waiters == 0 in tmp 4. folio_set_waiters(new_head) set_bit(PG_waiters, &flags.f) enqueue on waitqueue, sleep 5. new_head->flags.f = tmp | (1UL << PG_head) <-- store; overwrites step 4, PG_waiters == 0 again Later, folio_unlock(new_folio) sees no PG_waiters, skips folio_wake_bit(), and CPU1 can remain blocked indefinitely. Fix it by setting PG_head along with other flags in new_folio->flags before smp_wmb() and clear_compound_head(). The remaining compound page metadata is set after clear_compound_head(). In that way, after clear_compound_head() makes new_folio visible, nothing overwrites the PG_waiters from softleaf_entry_wait_on_locked() by modifying new_folio->flags non-atomically. While at it, use data_race() to suppress the KCSAN issue reported by Ye Liu's patch (the second Closes) on reading folio->flags in __split_folio_to_order(). Suggested-by: Kiryl Shutsemau Reported-by: David Hildenbrand Closes: https://lore.kernel.org/all/DMHE8BEEER1H.2BIY52NXATPIA@nvidia.com/ Reported-by: Ye Liu Closes: https://lore.kernel.org/all/20261029-data_race_huge_mem-v1-1-112e331291c1@linux.dev/ Fixes: c010d47f107f6 ("mm: thp: split huge page to any lower order pages") Cc: stable@vger.kernel.org Signed-off-by: Zi Yan Reviewed-by: David Hildenbrand (Arm) Reviewed-by: Kiryl Shutsemau (Meta) Reviewed-by: Baolin Wang Reviewed-by: Ye Liu Link: https://patch.msgid.link/20261110-fix-split_folio_to_order-race-v4-1-cc5042f33408@nvidia.com Signed-off-by: David Hildenbrand (Arm) --- mm/huge_memory.c | 32 ++++++++++++++++++++++++++++---- mm/internal.h | 2 ++ mm/page_alloc.c | 17 +++++++++++++++-- 3 files changed, 45 insertions(+), 6 deletions(-) diff --git a/mm/huge_memory.c b/mm/huge_memory.c index eb913acb03b7..2e7f4e4c13d2 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -3775,6 +3775,7 @@ static void __split_folio_to_order(struct folio *folio, int old_order, * Don't pass it around before clear_compound_head(). */ struct folio *new_folio = (struct folio *)new_head; + memdesc_flags_t new_flags; VM_BUG_ON_PAGE(atomic_read(&new_folio->_mapcount) != -1, new_head); @@ -3791,8 +3792,15 @@ static void __split_folio_to_order(struct folio *folio, int old_order, * unreferenced sub-pages of an anonymous THP: we can simply drop * PG_anon_exclusive (-> PG_mappedtodisk) for these here. */ - new_folio->flags.f &= ~PAGE_FLAGS_CHECK_AT_PREP; - new_folio->flags.f |= (folio->flags.f & + new_flags.f = new_folio->flags.f & ~PAGE_FLAGS_CHECK_AT_PREP; + /* + * data_race() is used because folio->flags is only read here, + * but a reference-less writer can still write to it, e.g., + * PG_waiters update from softleaf_entry_wait_on_locked(). + * The flag is not transferred to new_flags as it is + * folio specific, so it is not lost. + */ + new_flags.f |= data_race(folio->flags.f) & ((1L << PG_referenced) | (1L << PG_swapbacked) | (1L << PG_swapcache) | @@ -3810,7 +3818,19 @@ static void __split_folio_to_order(struct folio *folio, int old_order, #endif (1L << PG_dirty) | (1L << PG_dropbehind) | - LRU_GEN_MASK | LRU_REFS_MASK)); + LRU_GEN_MASK | LRU_REFS_MASK); + + /* + * Set PG_head before smp_wmb() and clear_compound_head(). + * After clear_compound_head() marks new_head as a folio of its + * own, new_head->flags must not be modified by plain RMWs. + * A plain RMW can cause a loss of atomic PG_* updates from + * a reference-less writer, e.g., setting PG_waiters via + * softleaf_entry_wait_on_locked(). + */ + if (new_order) + new_flags.f |= 1L << PG_head; + WRITE_ONCE(new_folio->flags.f, new_flags.f); new_folio->mapping = folio->mapping; new_folio->index = folio->index + i; @@ -3840,7 +3860,11 @@ static void __split_folio_to_order(struct folio *folio, int old_order, */ clear_compound_head(new_head); if (new_order) { - prep_compound_page(new_head, new_order); + /* + * PG_head is set above, so only set up the remaining + * metadata on head page and tail pages. + */ + __prep_compound_page(new_head, new_order); folio_set_large_rmappable(new_folio); } diff --git a/mm/internal.h b/mm/internal.h index e3f92883bf23..a0e0c4f91020 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -834,6 +834,8 @@ static inline void prep_compound_tail(struct page *tail, VM_WARN_ON_ONCE(tail->private); } +void __prep_compound_page(struct page *page, unsigned int order); + #if defined CONFIG_COMPACTION || defined CONFIG_CMA /* diff --git a/mm/page_alloc.c b/mm/page_alloc.c index eb4f02617f53..fcc6ec394678 100644 --- a/mm/page_alloc.c +++ b/mm/page_alloc.c @@ -682,18 +682,31 @@ static inline bool pcp_allowed_order(unsigned int order) * This usage means that zero-order pages may not be compound. */ -void prep_compound_page(struct page *page, unsigned int order) +/* + * Set up the metadata on head page and tail pages. + * Caller must set PG_head before this. + */ +void __prep_compound_page(struct page *page, unsigned int order) { int i; int nr_pages = 1 << order; - __SetPageHead(page); for (i = 1; i < nr_pages; i++) prep_compound_tail(page + i, page, order); prep_compound_head(page, order); } +/* + * PG_head is set non-atomically. It should be used when no one else can modify + * @page's flags. + */ +void prep_compound_page(struct page *page, unsigned int order) +{ + __SetPageHead(page); + __prep_compound_page(page, order); +} + static inline void set_buddy_order(struct page *page, unsigned int order) { set_page_private(page, order); -- cgit v1.3.1-4-g156e From 26b8f029ce5224dd5c5f45a4bc964a209c259914 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:20 +0100 Subject: mm: limit pagecache folio refcount when mapping pages 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 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 Acked-by: Zi Yan Reviewed-by: Pedro Falcato Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-1-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- include/linux/mm.h | 36 ++++++++++++++++++++++++++++++++---- mm/filemap.c | 2 ++ mm/folio.c | 26 ++++++++++++++++++++++++++ mm/huge_memory.c | 32 ++++++++++++++++++++++++++++++-- mm/memory.c | 37 +++++++++++++++++++++++++++++++++---- mm/migrate.c | 11 +++++++++++ mm/userfaultfd.c | 4 ++++ 7 files changed, 138 insertions(+), 10 deletions(-) diff --git a/include/linux/mm.h b/include/linux/mm.h index 6af3b7008f1a..e948aea60d19 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -2249,9 +2249,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. @@ -2263,7 +2291,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 b04be64a5069..453d88db5ee2 100644 --- a/mm/filemap.c +++ b/mm/filemap.c @@ -3774,6 +3774,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/folio.c b/mm/folio.c index 35e242b48870..38046a40a9db 100644 --- a/mm/folio.c +++ b/mm/folio.c @@ -107,6 +107,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/huge_memory.c b/mm/huge_memory.c index 2e7f4e4c13d2..7791872f14af 100644 --- a/mm/huge_memory.c +++ b/mm/huge_memory.c @@ -1626,6 +1626,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; @@ -1662,6 +1663,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); @@ -1688,7 +1693,7 @@ out_unlock: spin_unlock(ptl); if (pgtable) pte_free(mm, pgtable); - return VM_FAULT_NOPAGE; + return ret; } /** @@ -1759,6 +1764,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; @@ -1784,6 +1790,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); @@ -1799,7 +1809,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; } /** @@ -2095,6 +2105,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 @@ -5239,6 +5257,16 @@ void remove_migration_pmd(struct page_vma_mapped_walk *pvmw, struct folio *folio 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 = softleaf_from_pmd(*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 ee792a2c0cce..115b994cabfd 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -1168,7 +1168,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, @@ -1186,6 +1189,20 @@ 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; + if (userfaultfd_pte_rwp(dst_vma, pte)) + return -ENOMEM; + /* Preserve uffd-wp protection when faulting the page back in. */ + cond_install_uffd_wp_ptes(dst_vma, addr, dst_pte, pte, 1); + 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 @@ -1367,9 +1384,9 @@ again: /* * 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)) { /* @@ -1399,7 +1416,7 @@ again: 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); @@ -2474,6 +2491,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) { @@ -5747,6 +5766,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. @@ -5801,6 +5823,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) @@ -5967,6 +5992,10 @@ fallback: 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 875079464930..e6cd83cf32aa 100644 --- a/mm/migrate.c +++ b/mm/migrate.c @@ -385,6 +385,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); + cond_install_uffd_wp_ptes(vma, pvmw.address, + pvmw.pte, old_pte, 1); + update_hiwater_rss(vma->vm_mm); + dec_mm_counter(vma->vm_mm, mm_counter_file(folio)); + continue; + } + folio_get(folio); new = folio_page(folio, idx); pte = mk_pte(new, READ_ONCE(vma->vm_page_prot)); diff --git a/mm/userfaultfd.c b/mm/userfaultfd.c index 57650e6f040d..14fdbf217f00 100644 --- a/mm/userfaultfd.c +++ b/mm/userfaultfd.c @@ -373,6 +373,10 @@ static 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; + } folio_add_file_rmap_pte(folio, page, dst_vma); } else { folio_add_new_anon_rmap(folio, dst_vma, dst_addr, RMAP_EXCLUSIVE); -- cgit v1.3.1-4-g156e From c6c9a4c1c9a1669693330205cb9d86fafd3cf235 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:21 +0100 Subject: mm: limit pagecache folio refcount when splicing into pipes 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 Reviewed-by: Pedro Falcato Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-2-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- 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 3641abb90d6b..50f41bb28783 100644 --- a/fs/fuse/dev.c +++ b/fs/fuse/dev.c @@ -1230,7 +1230,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 e948aea60d19..95d5e9a13e51 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -2257,8 +2257,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 @@ -2272,15 +2273,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. @@ -2305,15 +2318,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 453d88db5ee2..f9e34144c53c 100644 --- a/mm/filemap.c +++ b/mm/filemap.c @@ -3047,10 +3047,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); @@ -3063,13 +3064,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; @@ -3094,9 +3097,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, @@ -3154,7 +3158,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; @@ -3170,13 +3174,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 a0e0c4f91020..85cf7becf858 100644 --- a/mm/internal.h +++ b/mm/internal.h @@ -1274,8 +1274,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); static inline bool vma_is_single_threaded_private(struct vm_area_struct *vma) { diff --git a/mm/shmem.c b/mm/shmem.c index b8399bb71997..4d73fbf081f9 100644 --- a/mm/shmem.c +++ b/mm/shmem.c @@ -3744,7 +3744,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; @@ -3830,8 +3831,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; -- cgit v1.3.1-4-g156e From 317bd7d28b248fd4d4e14614d7c30b17a36ef4d7 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:22 +0100 Subject: mm/mmu_gather: flush pending references early before the folio limit 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 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 Reviewed-by: Lance Yang Reviewed-by: Pedro Falcato Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-3-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- 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 3f4a180b48f3..4bba02fd5d54 100644 --- a/include/asm-generic/tlb.h +++ b/include/asm-generic/tlb.h @@ -75,8 +75,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 95d5e9a13e51..12a090d8d07f 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -2252,6 +2252,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 115b994cabfd..7f019afc35ca 100644 --- a/mm/memory.c +++ b/mm/memory.c @@ -2076,8 +2076,8 @@ retry: 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 9f353f0e2ef4..e98397ac577c 100644 --- a/mm/mmu_gather.c +++ b/mm/mmu_gather.c @@ -179,10 +179,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 { @@ -190,6 +187,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. -- cgit v1.3.1-4-g156e From b8ba6cc9943222676d46ac77d3d3de2685a55bf8 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:23 +0100 Subject: iommufd: fix cleanup when adding memfd folio pins fails 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 Reviewed-by: Jason Gunthorpe Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-4-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- 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 2f6153108add..fcdbde007a9a 100644 --- a/drivers/iommu/iommufd/pages.c +++ b/drivers/iommu/iommufd/pages.c @@ -781,6 +781,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; }; @@ -800,6 +801,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; } @@ -843,6 +845,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++) { @@ -859,8 +862,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++); @@ -1251,14 +1258,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); @@ -1320,7 +1327,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); -- cgit v1.3.1-4-g156e From 2d9bcd380585abc436f055fbb618b34f98882004 Mon Sep 17 00:00:00 2001 From: "David Hildenbrand (Arm)" Date: Thu, 12 Nov 2026 23:53:24 +0100 Subject: mm/gup: limit pagecache folio refcount when grabbing references 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 Reviewed-by: Pedro Falcato Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-5-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) --- 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 12a090d8d07f..daf07b2d208f 100644 --- a/include/linux/mm.h +++ b/include/linux/mm.h @@ -2266,6 +2266,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 @@ -2987,12 +2990,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 2b405cce2ca5..7605da0e06d8 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 @@ next_page: 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; } } @@ -3538,10 +3548,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; } -- cgit v1.3.1-4-g156e