From: Chris Mason 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@vger.kernel.org Signed-off-by: Chris Mason [ david: code cleanups; clarify comment and description ] Signed-off-by: David Hildenbrand (Arm) --- mm/ksm.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/mm/ksm.c b/mm/ksm.c index 90cc83275764d..509bd78156583 100644 --- a/mm/ksm.c +++ b/mm/ksm.c @@ -3211,8 +3211,9 @@ struct folio *ksm_might_need_to_copy(struct folio *folio, struct page *page, * So test, and copy, the page of the slot. */ if (folio_test_ksm(folio)) { - if (folio_stable_node(folio) && - !(ksm_run & KSM_RUN_UNMERGE)) + /* Never place KSM folios into VMAs without VM_MERGEABLE. */ + if (folio_stable_node(folio) && !(ksm_run & KSM_RUN_UNMERGE) && + (vma->vm_flags & VM_MERGEABLE)) return folio; /* no need to copy it */ } else if (folio_anon_rmap_compatible(folio, page, vma, addr)) { return folio; /* still no need to copy it */ -- 2.56.1