Re: [PATCH 31/32] mm/migrate_device: don't collect KSM folios

From: Gregory Price (Meta)

Date: Wed Dec 02 2026 - 16:55:44 EST


On 2026-11-29 11:07 +0100, David Hildenbrand (Arm) wrote:
> 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>

I could not reproduce a UAF, but i could trigger the stale migration
entry and this just seems reasonably correct either way.

Tested-by: Gregory Price (Meta) <gourry@xxxxxxxxxx>
Reviewed-by: Gregory Price (Meta) <gourry@xxxxxxxxxx>

--
~Gregory