[PATCH 31/32] mm/migrate_device: don't collect KSM folios
From: David Hildenbrand (Arm)
Date: Sun Nov 29 2026 - 05:16:44 EST
From: Chris Mason <mason@xxxxxxxxxx>
KSM can add page table mappings to a KSM folio without holding the folio
lock, and only makes them visible to rmap walks afterwards, when adding
the rmap_item to the stable node in stable_tree_append().
migrate_vma_collect_pmd() finds such a fresh mapping through its page
table walk, locks the folio and replaces the PTE by a migration entry.
But when restoring the migration entries, remove_migration_ptes() relies
on an rmap walk, and rmap_walk_ksm() might not yet find that PTE:
ksmd migrate_vma_setup()
==== ===================
try_to_merge_with_ksm_page()
replace_page()
PTE maps kfolio
migrate_vma_collect_pmd()
folio_trylock(kfolio)
PTE = migration entry
migrate_device_unmap()
remove_migration_ptes()
rmap_walk_ksm() misses it
folio_unlock(kfolio)
folio_lock(kfolio)
stable_tree_append()
Consequently, we can leave a stale migration entry behind. If migration
succeeded, the migration entry will refer to the freed source folio, and
waiting on that migration entry will trigger a use-after-free.
Let's fix it by not collecting KSM folios in migrate_vma_collect_pmd().
This has medium urgency, as it can result in a use-after-free, but might
be hard to trigger in practice.
Fixes: 8c3328f1f36a ("mm/migrate: migrate_vma() unmap page from vma while collecting pages")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Chris Mason <mason@xxxxxxxxxx>
[ david: clarify comment; simplify and clarify description ]
Signed-off-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>
---
mm/migrate_device.c | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/mm/migrate_device.c b/mm/migrate_device.c
index c6473f2e5388b..f98ea2291d532 100644
--- a/mm/migrate_device.c
+++ b/mm/migrate_device.c
@@ -418,6 +418,18 @@ static int migrate_vma_collect_pmd(pmd_t *pmdp,
bool anon_exclusive;
pte_t swp_pte;
+ /*
+ * rmap_walk_ksm() may not find this PTE to restore
+ * the migration entry later.
+ */
+ if (folio_test_ksm(folio)) {
+ if (fault_folio != folio)
+ folio_unlock(folio);
+ folio_put(folio);
+ mpfn = 0;
+ goto next;
+ }
+
if (pte_present(pte))
flush_cache_page(vma, addr, pte_pfn(pte));
anon_exclusive = folio_test_anon(folio) &&
--
2.56.1