summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Hildenbrand (Arm) <david@kernel.org>2026-11-13 11:18:23 +0100
committerDavid Hildenbrand (Arm) <david@kernel.org>2026-11-14 16:36:05 +0100
commit25f5c92e1ac06496679ea229e5c825aa88968efd (patch)
treeeafdb35910f2917d010f02d36b3cc4b0706d4e25
parent7183af7f01c839ecef87840a90c0d8c5843f37d7 (diff)
parent2d9bcd380585abc436f055fbb618b34f98882004 (diff)
Merge patch series "mm: limit pagecache folio refcount"
David Hildenbrand (Arm) <david@kernel.org> says: Users can create a lot of folio references to pagecache folios, making it possible to overflow the refcount of large folios. While we knew that one could in theory overflow a folio's refcount, we mostly assumed that bad things would happen and it wouldn't go unnoticed. Not so sure if that is really always the case, and leaving that problem unsolved is irresponsible, so let's limit pagecache folio refcounts. This is mostly relevant for large folios / thps in the page cache, where a single VMA can hold multiple folio references, allowing for many folio references. But with sufficient (memory+process) resources, it is also possible with small folios, just not that relevant in practice today. With anon folios (including THPs), we should not be able to trigger folio refcount overflows, as one would need so many processes that it becomes impossible in practice. It was likely a problem for anon folios as well before we had a dedicated pincount. Let's limit the refcount before it turns negative, giving admin processes some extra reserves (to recover a problematic system). We still leave some headroom to allow for some slight limit overshooting, to make the implementation easier. But to make that work reliably, we have to make anybody that can take an unbounded number of folio references obey these limits. Patch #1 handles mapping references from page tables. We also have to take care of mmu_gather, to not hold too many references when zapping (whereby new page faults could remap pages concurrently), which we do in patch #3. Patch #4 fixes iommufd cleanup when adding folio pins fails, which these limits make easier to trigger. Splicing pagecache folios to a pipe (patch #2) also needs care. After feedback from Linus, these users really should be using try_get_page(), where we now also implement the new limit check. We also teach GUP in patch #5 to stay below the limit, to avoid negative refcounts that cause trouble. Doing some digging after getting a hint from Andrew, there are various paths in net that can also take an unbounded number of page refs and are problematic. Let's use try_get_page() in all affected paths. Net paths that take page refs that I don't touch because the references are either bounded or the paths are not relevant in practice: - skb_split(): can add one reference per split, but each split allocates a new skb that is charged to the socket, and the references go away once the data was acked. Reworking that to be able to fail requires more plumbing. - IP-TFS reassembly: needs one new inner skb per additional reference. - io_uring zerocopy send (managed frag references): each zerocopy piece is charged at least 4 KiB of TCP memory, so not relevant in practice. - kTLS software splicing: only transfers references from the pipe, so not a problem. - AF_XDP zerocopy TX, nfsd splice reads, sockmap / sk_msg, espintcp: bounded, or require privileges / special setups, so not a problem in practice. - Driver-specific paths (e.g., kTLS device offload): require special hardware, didn't look into these. - page_pool and net_iov frags: not pagecache pages, so not a problem. For page table mappings, this is only a temporary solution for upstream+stable, until we have something better, which will be harder to backport: - Letting the mapcount of large folios be a long - Holding a single refcount if the folio is mapped, across all mappings - Reverting the limits introduced in this series After that, most of patch #1 will be reverted, everything else will stay. Tested on x86-64 by lowering the folio refcount limits such that limits can easily be exceeded, to then test fault (SIGBUS), fork(), splice and GUP behavior briefly when we run into refcount limits on a shmem THP. The net patches were tested similarly with AF_PACKET, nft dup, NFQUEUE, software GSO segmentation, TCP receive coalescing with dropped ACKs and socket splicing. * patches from https://patch.msgid.link/20261112-refcount_overflow_stable-v4-0-ad3deef0bd23@kernel.org: mm/gup: limit pagecache folio refcount when grabbing references iommufd: fix cleanup when adding memfd folio pins fails mm/mmu_gather: flush pending references early before the folio limit mm: limit pagecache folio refcount when splicing into pipes mm: limit pagecache folio refcount when mapping pages The -net patches part of the series will be dealt with separately. Link: https://patch.msgid.link/20261112-refcount_overflow_stable-v4-0-ad3deef0bd23@kernel.org Signed-off-by: David Hildenbrand (Arm) <david@kernel.org>
-rw-r--r--drivers/iommu/iommufd/pages.c15
-rw-r--r--fs/fuse/dev.c4
-rw-r--r--include/asm-generic/tlb.h4
-rw-r--r--include/linux/mm.h89
-rw-r--r--mm/filemap.c28
-rw-r--r--mm/folio.c26
-rw-r--r--mm/gup.c32
-rw-r--r--mm/huge_memory.c32
-rw-r--r--mm/internal.h4
-rw-r--r--mm/memory.c41
-rw-r--r--mm/migrate.c11
-rw-r--r--mm/mmu_gather.c10
-rw-r--r--mm/shmem.c7
-rw-r--r--mm/userfaultfd.c4
14 files changed, 249 insertions, 58 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);
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/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 6af3b7008f1a..daf07b2d208f 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -2249,9 +2249,54 @@ 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))
+#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);
+
+/**
+ * __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
+ * 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
+ * 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,
+ unsigned int ref_count)
+{
+ 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.
@@ -2263,7 +2308,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);
}
@@ -2277,15 +2322,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.
@@ -2925,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/filemap.c b/mm/filemap.c
index b04be64a5069..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;
}
@@ -3774,6 +3780,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/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;
}
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/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/memory.c b/mm/memory.c
index ee792a2c0cce..7f019afc35ca 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);
@@ -2059,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.
*/
@@ -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/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.
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;
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);