[PATCH v2] mm/ksm: keep soft-dirty and uffd-wp when merging a page

From: Samarth Narang

Date: Sun Oct 18 2026 - 21:12:25 EST


replace_page() maps the KSM page with a PTE built from scratch, so the
soft-dirty and uffd bits of the PTE it replaces are lost. Due to this, a
write before the merge no longer shows as soft-dirty, the next write to
a uffd-wp page raises no write-protect fault, and because the page is
mapped with the VMA's normal permissions, on a uffd-rwp VMA the next
access raises no RWP fault.

Copy the soft-dirty and uffd bits from the original PTE to the new PTE,
and restore PAGE_NONE for RWP VMAs, as try_to_map_unused_to_zeropage()
does.

Fixes: 0f8975ec4db2 ("mm: soft-dirty bits for user memory changes tracking")
Fixes: 63b2d4174c4a ("userfaultfd: wp: add the writeprotect API to userfaultfd ioctl")
Fixes: 2d427bb01639 ("mm/userfaultfd: add RWP fault delivery and expose UFFDIO_REGISTER_MODE_RWP")
Cc: stable@xxxxxxxxxxxxxxx
Tested-by: Lance Yang <lance.yang@xxxxxxxxx>
Assisted-by: LLM
Signed-off-by: Samarth Narang <samarth.colleges@xxxxxxxxx>
---

Notes:
v1: https://lore.kernel.org/all/20261018122957.526467-1-samarth.colleges@xxxxxxxxx/

Changes since v1 (thanks, Lance):
- Fixes: point the uffd-wp and RWP tags at the commits that make the
registration modes reachable (63b2d4174c4a, 2d427bb01639).
- Shorten the comment; the uffd bit carries RWP state too.
- Add Lance's Tested-by.

mm/ksm.c | 12 ++++++++++++
1 file changed, 12 insertions(+)

diff --git a/mm/ksm.c b/mm/ksm.c
index dbfb8f98b189..de144fa07c49 100644
--- a/mm/ksm.c
+++ b/mm/ksm.c
@@ -34,6 +34,7 @@
#include <linux/memory.h>
#include <linux/mmu_notifier.h>
#include <linux/swap.h>
+#include <linux/userfaultfd_k.h>
#include <linux/ksm.h>
#include <linux/hashtable.h>
#include <linux/freezer.h>
@@ -1463,6 +1464,17 @@ static int replace_page(struct vm_area_struct *vma, struct page *page,
dec_mm_counter(mm, MM_ANONPAGES);
}

+ /*
+ * Preserve soft-dirty and uffd bits when replacing the page.
+ * Restore PAGE_NONE for RWP-protected PTEs.
+ */
+ if (pte_soft_dirty(orig_pte))
+ newpte = pte_mksoft_dirty(newpte);
+ if (pte_uffd(orig_pte))
+ newpte = pte_mkuffd(newpte);
+ if (pte_uffd(orig_pte) && userfaultfd_rwp(vma))
+ newpte = pte_modify(newpte, PAGE_NONE);
+
flush_cache_page(vma, addr, pte_pfn(ptep_get(ptep)));
/*
* No need to notify as we are replacing a read only page with another

base-commit: 48fe11c8d0f1e4e59426a3606f20ac1130b6d8dc
--
2.53.0