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

From: Alistair Popple

Date: Wed Dec 02 2026 - 17:47:45 EST


On 2026-12-03 at 08:55 +1100, "Gregory Price (Meta)" <gourry@xxxxxxxxxx> wrote...
> 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.

I think in practice it would be quite difficult to trigger. Waiting on a
migration entry only requires a struct folio, so it doesn't matter that the
source folio is in the free state. It would require the memory to be hot
unplugged while the stale migration entry was present to free the struct folio
itself to get a UAF.

Not impossible of course, and the fix seems correct regardless - migration is
always allowed to fail. So:

Reviewed-by: Alistair Popple <apopple@xxxxxxxxxx>

- Alistair