Re: [PATCH] mm/khugepaged: don't map folios that are not uptodate in MADV_COLLAPSE

From: Kiryl Shutsemau

Date: Fri Nov 06 2026 - 08:43:00 EST


On Fri, Nov 06, 2026 at 01:29:31PM +0100, David Hildenbrand (Arm) wrote:
> > Separately from this fix: nothing on the mapping side catches this.
> > Every caller checks uptodate on its own (next_uptodate_folio(),
> > filemap_fault(), shmem_get_folio()), and khugepaged was the one that
> > went straight from filemap_lock_folio() to do_set_pmd().
> >
> > Should do_set_pmd() and set_pte_range() assert it? Something like
> >
> > VM_WARN_ON_ONCE_FOLIO(folio->mapping && !folio_test_anon(folio) &&
> > !folio_test_uptodate(folio), folio);
>
> I think so. But looking at these hard-to-trigger but in the end very nasty
> problems, should we actually reject the operation and do a pr_warn_once() or
> something?

Yes, rejecting sounds better.

Not in set_pte_range() as I suggested, though. Fault-around only gets
there with folios that next_uptodate_folio() checked under the folio
lock, and for CoW it maps the new anon folio after do_cow_fault() has
already copied from the page cache one.

Checking the folio ->fault() returned in finish_fault() covers PTE, PMD
and CoW; do_set_pmd() covers khugepaged. Both return VM_FAULT_SIGBUS.

Something like this, only compile-tested:

diff --git a/mm/memory.c b/mm/memory.c
index 6fe0b7dab927..ff2f2deff761 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -5674,6 +5674,22 @@ static vm_fault_t __do_fault(struct vm_fault *vmf)
return ret;
}

+/*
+ * A page cache folio that is not uptodate holds data that was never read in
+ * or cleared, and mapping it leaks stale memory to userspace. The callers are
+ * expected to check, so treat a hit as a kernel bug and refuse the mapping.
+ */
+static bool file_folio_not_uptodate(struct folio *folio)
+{
+ if (likely(folio_test_uptodate(folio)))
+ return false;
+ /* Driver pages from ->fault() never get PG_uptodate */
+ if (folio_test_anon(folio) || !folio->mapping)
+ return false;
+ WARN_ONCE(1, "refusing to map a page cache folio that is not uptodate\n");
+ return true;
+}
+
#ifdef CONFIG_TRANSPARENT_HUGEPAGE
static void deposit_prealloc_pte(struct vm_fault *vmf)
{
@@ -5714,6 +5730,9 @@ vm_fault_t do_set_pmd(struct vm_fault *vmf, struct folio *folio, struct page *pa
return ret;
page = &folio->page;

+ if (file_folio_not_uptodate(folio))
+ return VM_FAULT_SIGBUS;
+
/*
* Just backoff if any subpage of a THP is corrupted otherwise
* the corrupted page may mapped by PMD silently to escape the
@@ -5849,6 +5868,16 @@ vm_fault_t finish_fault(struct vm_fault *vmf)
unsigned long addr;
bool needs_fallback = false;

+ /*
+ * Check the folio ->fault() returned. For CoW that is the source of the
+ * copy; DAX CoW has none.
+ */
+ if (vmf->page) {
+ folio = page_folio(vmf->page);
+ if (file_folio_not_uptodate(folio))
+ return VM_FAULT_SIGBUS;
+ }
+
fallback:
addr = vmf->address;
--
Kiryl Shutsemau / Kirill A. Shutemov