Re: [PATCH 29/32] mm/ksm: use a migration counter to detect KSM folio migration

From: Gregory Price (Meta)

Date: Thu Dec 03 2026 - 00:27:39 EST


On 2026-11-29 11:07 +0100, David Hildenbrand (Arm) wrote:
> ksm_get_folio() holds no reference on the folio referenced by
> stable_node->kpfn. If the folio at stable_node->kpfn is no longer our KSM
> folio, it was either freed or migrated. When freed, we can drop the
> stable node; when migrated, we have to look again for the migrated
> folio.
>
> However, a second migration might have migrated the KSM folio back to
> the very same page in the meantime: stable_node->kpfn would be
> effectively unchanged and the KSM folio is still alive.
>
> Consequently, we might remove the stable node of a KSM folio that is
> still mapped, resulting in a use-after-free of the stable node, for
> example, in rmap_walk_ksm().
>
> Let's fix it by storing a migration counter in the upper bits of
> stable_node->kpfn, incremented on each migration of the KSM folio. The
> existing check whether the value changed will then also detect a KSM
> folio that migrated back, and a freed KSM folio will still be detected
> as such.
>
> As a pfn never needs more than 64 - PAGE_SHIFT bits, convert
> stable_node->kpfn to a u64, and use the remaining PAGE_SHIFT bits (at
> least 12) for the counter. A wrap-around would require 4096 migrations
> of the KSM folio while ksmd is between two reads in ksm_get_folio():
> not relevant in practice, because even two migrations back and forth
> would be hard to hit.
>
> This change doesn't grow the size of a stable node on 64-bit, which is
> what we care about. We don't care about 32-bit and likely we should make
> KSM 64-bit-only soon.
>
> Note that on 32-bit, the pfn will always reside in the lower 32 bits,
> and every update changes the upper 32 bits, which hold the counter. So
> even if we read a value torn by a concurrent update (2x32-bit accesses),
> the pfn will be valid, and due to the existing barriers, the value
> cannot look unchanged after a migration.
>
> Rename stable_node->kpfn to stable_node->kpfn_seq to catch all users,
> and add helpers to access the pfn.
>
> This has low urgency, as it should be extremely hard to hit in practice.
> As this was not reproducible and wasn't reported so far, and the change
> is not trivial to backport, let's not CC stable.
>
> Fixes: c8d6553b9580 ("ksm: make KSM page migration possible")
> Reported-by: Chris Mason <mason@xxxxxxxxxx>
> Signed-off-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>

Did finally reproduce the UAF. It was very convoluted and required
root to get there.

I don't love the new counter but i don't have a better suggestion so
bleugh.

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

--
~Gregory