Re: [PATCH v2 26/31] mm/ksm: copy KSM folios at swap-in without VM_MERGEABLE

From: David Hildenbrand (Arm)

Date: Fri Dec 04 2026 - 08:02:11 EST


On 12/4/26 14:00, Lorenzo Stoakes (ARM) wrote:
> On Fri, Dec 04, 2026 at 01:50:17PM +0100, David Hildenbrand (Arm) wrote:
>> From: Chris Mason <mason@xxxxxxxxxx>
>>
>> So far we were under the assumption that only VM_MERGEABLE VMAs may
>> contain KSM folios, because we unmerge when clearing VM_MERGEABLE, and
>> KSM only merges within VM_MERGEABLE VMAs. Various infrastructure (e.g.,
>> rmap walks) relies on related properties: for example that a KSM folio
>> is always mapped at rmap_item->address, also in child processes.
>>
>> We ignored one scenario: when unmerging, break_ksm() skips swap entries.
>> If the KSM folio is still in the swap cache, swapping it in after
>> clearing VM_MERGEABLE will map the KSM folio in a VMA without
>> VM_MERGEABLE.
>>
>> Consequently, rmap walks can miss such folio mappings, resulting in
>> the KSM folio no longer being reclaimable or migratable.
>>
>> Worse, until ksmd notices that VM_MERGEABLE was cleared and drops the
>> rmap_item of the process, rmap walks still look for the KSM folio at the
>> old address. If the rmap_item belongs to the parent process instead,
>> that will never happen. If the process calls mremap() while the kernel
>> is migrating the KSM folio, mremap() moves the migration entry that
>> try_to_migrate() installed, and remove_migration_ptes() will not find it
>> at its new address. Once migration frees the source folio, the moved PTE
>> still holds a migration entry that refers to the freed, and possibly
>> already reused, folio: the next access through that PTE will hang, or
>> worse.
>>
>> Let's fix it by copying KSM folios during swap-in if the VMA lacks
>> VM_MERGEABLE, like we already do while KSM_RUN_UNMERGE is set.
>>
>> Note that mremap() in a VM_MERGEABLE VMA can similarly move a swap entry
>> of a KSM folio, as break_ksm() skips swap entries. But in that case,
>> rmap walks will find the KSM folio again once ksmd scanned the new
>> address, and we cannot end up with a stale migration entry, so we'll
>> leave that for another day.
>>
>> This has medium urgency, as an unprivileged process can trigger a
>> use-after-free if KSM is enabled.
>>
>> Fixes: 5ad6468801d2 ("ksm: let shared pages be swappable")
>> Cc: stable@xxxxxxxxxxxxxxx
>> Signed-off-by: Chris Mason <mason@xxxxxxxxxx>
>> [ david: code cleanups; clarify comment and description ]
>> Tested-by: Gregory Price (Meta) <gourry@xxxxxxxxxx>
>> Reviewed-by: Gregory Price (Meta) <gourry@xxxxxxxxxx>
>> Signed-off-by: David Hildenbrand (Arm) <david@xxxxxxxxxx>
>
> Oops send the tag while you were respinning I think, so:
>
> Reviewed-by: Lorenzo Stoakes (ARM) <ljs@xxxxxxxxxx>

Thanks! :)

--
Cheers,

David