Linux kernel -stable discussions
 help / color / mirror / Atom feed
* [PATCH v3 0/3] mm/ksm: fix ksm_zero_pages accounting on fork
@ 2026-11-23  3:41 Xu Xin (vivo)
  2026-11-23  3:43 ` [PATCH v3 1/3] mm/ksm: do not inherit ksm_zero_pages counter or PTE markers " Xu Xin (vivo)
                   ` (3 more replies)
  0 siblings, 4 replies; 8+ messages in thread
From: Xu Xin (vivo) @ 2026-11-23  3:41 UTC (permalink / raw)
  To: David Hildenbrand
  Cc: akpm, chengming.zhou, linux-mm, stable, xu.xin, linux-kernel,
	donettom

Currently, fork() wrongly inherits the parent's ksm_zero_pages counter
and keeps the KSM dirty-bit marker on zero-page PTEs, inflating both the
child's per-mm counter and the global ksm_zero_pages counter.

Patch 1 fixes this by resetting the child's mm->ksm_zero_pages to 0 in
ksm_fork() and clearing the KSM zero-page marker when copying present
PTEs, and documents the behavior.

Patch 2 fixes false-positive and racy bugs in the existing KSM fork
selftest by dropping init_global_file_handles() in the child, avoiding
8-bit exit status truncation, and pausing ksmd before fork().

Patch 3 extends the selftest to verify that neither ksm_merging_pages
nor ksm_zero_pages is inherited across fork().

---
Changes in v3:
- Rename might_clear_ksm_zero_pte() to ksm_fork_pte() and refactor the
  PTE marker check and comments (David Hildenbrand).

- Add Tested-by tag from Karl Mehltretter to patch 1/3.

- Refine exit status handling and add ksm_pause() in patch 2/3 and patch
  3/3 to prevent races and 8-bit truncation (Sashiko AI).

Changes in v2:
- Encapsulate zero-page PTE marker clearing into a dedicated helper and document ksm_zero_pages fork behavior (David).
- Fix compilation error for !CONFIG_KSM and address initial KSM fork selftest bug fixes.

Xu Xin (vivo) (3):
  mm/ksm: do not inherit ksm_zero_pages counter or PTE markers on fork
  selftests/mm: fix false-positive and racy KSM fork test
  selftests/mm: verify ksm_zero_pages is not inherited on fork

 Documentation/admin-guide/mm/ksm.rst          |  7 ++-
 include/linux/ksm.h                           | 22 +++++++--
 mm/memory.c                                   |  5 +-
 .../selftests/mm/ksm_functional_tests.c       | 48 +++++++++++++++----
 tools/testing/selftests/mm/vm_util.c          | 16 +++++++
 tools/testing/selftests/mm/vm_util.h          |  1 +
 6 files changed, 85 insertions(+), 14 deletions(-)

-- 
2.34.1


^ permalink raw reply	[flat|nested] 8+ messages in thread

* [PATCH v3 1/3] mm/ksm: do not inherit ksm_zero_pages counter or PTE markers on fork
  2026-11-23  3:41 [PATCH v3 0/3] mm/ksm: fix ksm_zero_pages accounting on fork Xu Xin (vivo)
@ 2026-11-23  3:43 ` Xu Xin (vivo)
  2026-11-23  3:43 ` Xu Xin (vivo)
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 8+ messages in thread
From: Xu Xin (vivo) @ 2026-11-23  3:43 UTC (permalink / raw)
  To: xu.xin
  Cc: akpm, chengming.zhou, david, donettom, linux-kernel, linux-mm,
	stable, Karl Mehltretter

As documented in Documentation/admin-guide/mm/ksm.rst, ksm_zero_pages
accounts only for zero pages actually placed by KSM.  However, the
current implementation wrongly accounts for forked zero-page PTEs as
KSM's contribution, inflating both the child's per-mm counter and the
global ksm_zero_pages counter.

Originally, commit e2942062e01d ("ksm: count all zero pages placed by
KSM") marked KSM-placed zero-page PTEs with the dirty bit for unmap
accounting, but forgot to clear this marker during fork().  Later, to
prevent ksm_might_unmap_zero_page() from underflowing the counters on
child exit[1], commit 4d6fc29f3634 ("mm/ksm: fix incorrect KSM counter
handling in mm_struct during fork") kept the child's inherited per-mm
counter and added it to the global counter.

Instead of inflating the counters, fix the root cause by resetting the
child's mm->ksm_zero_pages to 0 in ksm_fork() and clearing the KSM
zero-page marker via ksm_fork_pte() when copying present PTEs in
copy_present_ptes().  With the marker cleared,
ksm_might_unmap_zero_page() will not decrement the counters on child
exit, MADV_UNMERGEABLE in the child will not unnecessarily unshare
inherited zero pages, and the global counter remains untouched.

[1] https://lore.kernel.org/all/53a7bf3d-843d-4e19-b0a3-cc6852fe72c1@redhat.com/

Fixes: 4d6fc29f3634 ("mm/ksm: fix incorrect KSM counter handling in mm_struct during fork")
Cc: stable@vger.kernel.org
Tested-by: Karl Mehltretter <kmehltretter@gmail.com>
Signed-off-by: Xu Xin (vivo) <xu.xin@linux.dev>
---
Changes in v3:
- Rename might_clear_ksm_zero_pte() to ksm_fork_pte() and move the
  is_ksm_zero_pte() check into copy_present_ptes() under the !page
  branch, as suggested by David Hildenbrand.
- Expand the comment above ksm_fork_pte() to explain why the marker is
  cleared on fork.
- Add Tested-by tag from Karl Mehltretter.

 Documentation/admin-guide/mm/ksm.rst |  7 ++++++-
 include/linux/ksm.h                  | 22 +++++++++++++++++++---
 mm/memory.c                          |  5 ++++-
 3 files changed, 29 insertions(+), 5 deletions(-)

diff --git a/Documentation/admin-guide/mm/ksm.rst b/Documentation/admin-guide/mm/ksm.rst
index c329ca747b8c..8968ae3f55c0 100644
--- a/Documentation/admin-guide/mm/ksm.rst
+++ b/Documentation/admin-guide/mm/ksm.rst
@@ -214,7 +214,12 @@ stable_node_dups
         number of duplicated KSM pages
 ksm_zero_pages
         how many zero pages that are still mapped into processes were mapped by
-        KSM when deduplicating.
+        KSM when deduplicating. Note: on fork(), the child process does not
+        inherit the ``ksm_zero_pages`` counter, and any inherited KSM-placed
+        zero-page mappings are converted into ordinary shared zero-page
+        mappings. Consequently, these mappings are neither accounted for in
+        the child's counter nor unshared when ``MADV_UNMERGEABLE`` is called
+        in the child.
 
 When ``use_zero_pages`` is/was enabled, the sum of ``pages_sharing`` +
 ``ksm_zero_pages`` represents the actual number of pages saved by KSM.
diff --git a/include/linux/ksm.h b/include/linux/ksm.h
index 596c04ca7326..f29aec4496d0 100644
--- a/include/linux/ksm.h
+++ b/include/linux/ksm.h
@@ -32,6 +32,17 @@ void __ksm_exit(struct mm_struct *mm);
  */
 #define is_ksm_zero_pte(pte)	(is_zero_pfn(pte_pfn(pte)) && pte_dirty(pte))
 
+/*
+ * Since the inherited mappings on fork are not expected to be accounted for
+ * in the child's ksm_zero_pages counter (reset in ksm_fork()), we must
+ * clear KSM's dirty-bit marker on KSM-placed zero-page PTEs to avoid
+ * underflowing the counters on child exit.
+ */
+static inline pte_t ksm_fork_pte(pte_t pte)
+{
+	return pte_mkclean(pte);
+}
+
 extern atomic_long_t ksm_zero_pages;
 
 static inline void ksm_map_zero_page(struct mm_struct *mm)
@@ -57,11 +68,9 @@ static inline void ksm_fork(struct mm_struct *mm, struct mm_struct *oldmm)
 {
 	/* Adding mm to ksm is best effort on fork. */
 	if (mm_flags_test(MMF_VM_MERGEABLE, oldmm)) {
-		long nr_ksm_zero_pages = atomic_long_read(&mm->ksm_zero_pages);
-
 		mm->ksm_merging_pages = 0;
 		mm->ksm_rmap_items = 0;
-		atomic_long_add(nr_ksm_zero_pages, &ksm_zero_pages);
+		atomic_long_set(&mm->ksm_zero_pages, 0);
 		__ksm_enter(mm);
 	}
 }
@@ -95,6 +104,8 @@ bool ksm_process_mergeable(struct mm_struct *mm);
 
 #else  /* !CONFIG_KSM */
 
+#define is_ksm_zero_pte(pte)	false
+
 static inline vma_flags_t ksm_vma_flags(struct mm_struct *mm,
 		const struct file *file, vma_flags_t vma_flags)
 {
@@ -114,6 +125,11 @@ static inline void ksm_exit(struct mm_struct *mm)
 {
 }
 
+static inline pte_t ksm_fork_pte(pte_t pte)
+{
+	return pte;
+}
+
 static inline void ksm_might_unmap_zero_page(struct mm_struct *mm, pte_t pte)
 {
 }
diff --git a/mm/memory.c b/mm/memory.c
index 6a23198c1c67..f0b5df879e6f 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -1184,8 +1184,11 @@ copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma
 	int err, nr;
 
 	page = vm_normal_page(src_vma, addr, pte);
-	if (unlikely(!page))
+	if (unlikely(!page)) {
+		if (unlikely(is_ksm_zero_pte(pte)))
+			pte = ksm_fork_pte(pte);
 		goto copy_pte;
+	}
 
 	folio = page_folio(page);
 
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH v3 1/3] mm/ksm: do not inherit ksm_zero_pages counter or PTE markers on fork
  2026-11-23  3:41 [PATCH v3 0/3] mm/ksm: fix ksm_zero_pages accounting on fork Xu Xin (vivo)
  2026-11-23  3:43 ` [PATCH v3 1/3] mm/ksm: do not inherit ksm_zero_pages counter or PTE markers " Xu Xin (vivo)
@ 2026-11-23  3:43 ` Xu Xin (vivo)
  2026-11-23 16:38   ` David Hildenbrand (Arm)
  2026-11-23  3:45 ` [PATCH v3 2/3] selftests/mm: fix false-positive and racy KSM fork test Xu Xin (vivo)
  2026-11-23  3:45 ` [PATCH v3 3/3] selftests/mm: verify ksm_zero_pages is not inherited on fork Xu Xin (vivo)
  3 siblings, 1 reply; 8+ messages in thread
From: Xu Xin (vivo) @ 2026-11-23  3:43 UTC (permalink / raw)
  To: xu.xin
  Cc: akpm, chengming.zhou, david, donettom, linux-kernel, linux-mm,
	stable, Karl Mehltretter

As documented in Documentation/admin-guide/mm/ksm.rst, ksm_zero_pages
accounts only for zero pages actually placed by KSM.  However, the
current implementation wrongly accounts for forked zero-page PTEs as
KSM's contribution, inflating both the child's per-mm counter and the
global ksm_zero_pages counter.

Originally, commit e2942062e01d ("ksm: count all zero pages placed by
KSM") marked KSM-placed zero-page PTEs with the dirty bit for unmap
accounting, but forgot to clear this marker during fork().  Later, to
prevent ksm_might_unmap_zero_page() from underflowing the counters on
child exit[1], commit 4d6fc29f3634 ("mm/ksm: fix incorrect KSM counter
handling in mm_struct during fork") kept the child's inherited per-mm
counter and added it to the global counter.

Instead of inflating the counters, fix the root cause by resetting the
child's mm->ksm_zero_pages to 0 in ksm_fork() and clearing the KSM
zero-page marker via ksm_fork_pte() when copying present PTEs in
copy_present_ptes().  With the marker cleared,
ksm_might_unmap_zero_page() will not decrement the counters on child
exit, MADV_UNMERGEABLE in the child will not unnecessarily unshare
inherited zero pages, and the global counter remains untouched.

[1] https://lore.kernel.org/all/53a7bf3d-843d-4e19-b0a3-cc6852fe72c1@redhat.com/

Fixes: 4d6fc29f3634 ("mm/ksm: fix incorrect KSM counter handling in mm_struct during fork")
Cc: stable@vger.kernel.org
Tested-by: Karl Mehltretter <kmehltretter@gmail.com>
Signed-off-by: Xu Xin (vivo) <xu.xin@linux.dev>
---
Changes in v3:
- Rename might_clear_ksm_zero_pte() to ksm_fork_pte() and move the
  is_ksm_zero_pte() check into copy_present_ptes() under the !page
  branch, as suggested by David Hildenbrand.
- Expand the comment above ksm_fork_pte() to explain why the marker is
  cleared on fork.
- Add Tested-by tag from Karl Mehltretter.

 Documentation/admin-guide/mm/ksm.rst |  7 ++++++-
 include/linux/ksm.h                  | 22 +++++++++++++++++++---
 mm/memory.c                          |  5 ++++-
 3 files changed, 29 insertions(+), 5 deletions(-)

diff --git a/Documentation/admin-guide/mm/ksm.rst b/Documentation/admin-guide/mm/ksm.rst
index c329ca747b8c..8968ae3f55c0 100644
--- a/Documentation/admin-guide/mm/ksm.rst
+++ b/Documentation/admin-guide/mm/ksm.rst
@@ -214,7 +214,12 @@ stable_node_dups
         number of duplicated KSM pages
 ksm_zero_pages
         how many zero pages that are still mapped into processes were mapped by
-        KSM when deduplicating.
+        KSM when deduplicating. Note: on fork(), the child process does not
+        inherit the ``ksm_zero_pages`` counter, and any inherited KSM-placed
+        zero-page mappings are converted into ordinary shared zero-page
+        mappings. Consequently, these mappings are neither accounted for in
+        the child's counter nor unshared when ``MADV_UNMERGEABLE`` is called
+        in the child.
 
 When ``use_zero_pages`` is/was enabled, the sum of ``pages_sharing`` +
 ``ksm_zero_pages`` represents the actual number of pages saved by KSM.
diff --git a/include/linux/ksm.h b/include/linux/ksm.h
index 596c04ca7326..f29aec4496d0 100644
--- a/include/linux/ksm.h
+++ b/include/linux/ksm.h
@@ -32,6 +32,17 @@ void __ksm_exit(struct mm_struct *mm);
  */
 #define is_ksm_zero_pte(pte)	(is_zero_pfn(pte_pfn(pte)) && pte_dirty(pte))
 
+/*
+ * Since the inherited mappings on fork are not expected to be accounted for
+ * in the child's ksm_zero_pages counter (reset in ksm_fork()), we must
+ * clear KSM's dirty-bit marker on KSM-placed zero-page PTEs to avoid
+ * underflowing the counters on child exit.
+ */
+static inline pte_t ksm_fork_pte(pte_t pte)
+{
+	return pte_mkclean(pte);
+}
+
 extern atomic_long_t ksm_zero_pages;
 
 static inline void ksm_map_zero_page(struct mm_struct *mm)
@@ -57,11 +68,9 @@ static inline void ksm_fork(struct mm_struct *mm, struct mm_struct *oldmm)
 {
 	/* Adding mm to ksm is best effort on fork. */
 	if (mm_flags_test(MMF_VM_MERGEABLE, oldmm)) {
-		long nr_ksm_zero_pages = atomic_long_read(&mm->ksm_zero_pages);
-
 		mm->ksm_merging_pages = 0;
 		mm->ksm_rmap_items = 0;
-		atomic_long_add(nr_ksm_zero_pages, &ksm_zero_pages);
+		atomic_long_set(&mm->ksm_zero_pages, 0);
 		__ksm_enter(mm);
 	}
 }
@@ -95,6 +104,8 @@ bool ksm_process_mergeable(struct mm_struct *mm);
 
 #else  /* !CONFIG_KSM */
 
+#define is_ksm_zero_pte(pte)	false
+
 static inline vma_flags_t ksm_vma_flags(struct mm_struct *mm,
 		const struct file *file, vma_flags_t vma_flags)
 {
@@ -114,6 +125,11 @@ static inline void ksm_exit(struct mm_struct *mm)
 {
 }
 
+static inline pte_t ksm_fork_pte(pte_t pte)
+{
+	return pte;
+}
+
 static inline void ksm_might_unmap_zero_page(struct mm_struct *mm, pte_t pte)
 {
 }
diff --git a/mm/memory.c b/mm/memory.c
index 6a23198c1c67..f0b5df879e6f 100644
--- a/mm/memory.c
+++ b/mm/memory.c
@@ -1184,8 +1184,11 @@ copy_present_ptes(struct vm_area_struct *dst_vma, struct vm_area_struct *src_vma
 	int err, nr;
 
 	page = vm_normal_page(src_vma, addr, pte);
-	if (unlikely(!page))
+	if (unlikely(!page)) {
+		if (unlikely(is_ksm_zero_pte(pte)))
+			pte = ksm_fork_pte(pte);
 		goto copy_pte;
+	}
 
 	folio = page_folio(page);
 
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH v3 2/3] selftests/mm: fix false-positive and racy KSM fork test
  2026-11-23  3:41 [PATCH v3 0/3] mm/ksm: fix ksm_zero_pages accounting on fork Xu Xin (vivo)
  2026-11-23  3:43 ` [PATCH v3 1/3] mm/ksm: do not inherit ksm_zero_pages counter or PTE markers " Xu Xin (vivo)
  2026-11-23  3:43 ` Xu Xin (vivo)
@ 2026-11-23  3:45 ` Xu Xin (vivo)
  2026-11-23 16:43   ` David Hildenbrand (Arm)
  2026-11-23  3:45 ` [PATCH v3 3/3] selftests/mm: verify ksm_zero_pages is not inherited on fork Xu Xin (vivo)
  3 siblings, 1 reply; 8+ messages in thread
From: Xu Xin (vivo) @ 2026-11-23  3:45 UTC (permalink / raw)
  To: xu.xin
  Cc: akpm, chengming.zhou, david, donettom, linux-kernel, linux-mm,
	stable

Currently, test_fork_ksm_merging_page_count() passes wrongly even if
fork() fails to reset mm->ksm_merging_pages, because the child process
calls init_global_file_handles() -> ksm_stop(), which unmerges all KSM
pages across the system before reading its counters.

Fix three issues in test_fork_ksm_merging_page_count():

- Drop init_global_file_handles() in the child process so it does not
  call ksm_stop() and mutate global KSM sysfs state (unmerging all KSM
  pages across the system) before reading its counters.

- Use '!!' in exit(!!ksm_get_self_merging_pages()) to avoid 8-bit exit
  status truncation (e.g., 512 pages on 4 KiB systems truncating to 0).

- Introduce ksm_pause() to pause ksmd (write "0" to /sys/kernel/mm/ksm/run)
  before fork(), preventing ksmd from scanning the child and incrementing
  its counter before it is read.

Signed-off-by: Xu Xin (vivo) <xu.xin@linux.dev>
---
 .../testing/selftests/mm/ksm_functional_tests.c  |  8 ++++++--
 tools/testing/selftests/mm/vm_util.c             | 16 ++++++++++++++++
 tools/testing/selftests/mm/vm_util.h             |  1 +
 3 files changed, 23 insertions(+), 2 deletions(-)

diff --git a/tools/testing/selftests/mm/ksm_functional_tests.c b/tools/testing/selftests/mm/ksm_functional_tests.c
index 135191f99962..b871d5656688 100644
--- a/tools/testing/selftests/mm/ksm_functional_tests.c
+++ b/tools/testing/selftests/mm/ksm_functional_tests.c
@@ -668,10 +668,14 @@ static void test_fork_ksm_merging_page_count(void)
 	if (map == MAP_FAILED)
 		return;
 
+	if (ksm_pause() < 0) {
+		ksft_test_result_fail("Stop ksmd from running failed\n");
+		goto unmap;
+	}
+
 	child_pid = fork();
 	if (!child_pid) {
-		init_global_file_handles();
-		exit(ksm_get_self_merging_pages());
+		exit(!!ksm_get_self_merging_pages());
 	} else if (child_pid < 0) {
 		ksft_test_result_fail("fork() failed\n");
 		goto unmap;
diff --git a/tools/testing/selftests/mm/vm_util.c b/tools/testing/selftests/mm/vm_util.c
index f26f9e4bfdbe..e638475543e6 100644
--- a/tools/testing/selftests/mm/vm_util.c
+++ b/tools/testing/selftests/mm/vm_util.c
@@ -1080,6 +1080,22 @@ int ksm_stop(void)
 	return ret == 1 ? 0 : -EIO;
 }
 
+int ksm_pause(void)
+{
+	int ksm_fd;
+	ssize_t ret;
+
+	ksm_fd = open("/sys/kernel/mm/ksm/run", O_RDWR);
+	if (ksm_fd < 0)
+		return -errno;
+
+	ret = write(ksm_fd, "0", 1);
+	close(ksm_fd);
+	if (ret < 0)
+		return -errno;
+	return ret == 1 ? 0 : -EIO;
+}
+
 int get_hardware_corrupted_size(unsigned long *val)
 {
 	unsigned long size;
diff --git a/tools/testing/selftests/mm/vm_util.h b/tools/testing/selftests/mm/vm_util.h
index ab1325dc6580..df16973d108a 100644
--- a/tools/testing/selftests/mm/vm_util.h
+++ b/tools/testing/selftests/mm/vm_util.h
@@ -168,6 +168,7 @@ int ksm_set_smart_scan(bool enable);
 int ksm_use_zero_pages(void);
 int ksm_start(void);
 int ksm_stop(void);
+int ksm_pause(void);
 int get_hardware_corrupted_size(unsigned long *val);
 int unpoison_memory(unsigned long pfn);
 
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* [PATCH v3 3/3] selftests/mm: verify ksm_zero_pages is not inherited on fork
  2026-11-23  3:41 [PATCH v3 0/3] mm/ksm: fix ksm_zero_pages accounting on fork Xu Xin (vivo)
                   ` (2 preceding siblings ...)
  2026-11-23  3:45 ` [PATCH v3 2/3] selftests/mm: fix false-positive and racy KSM fork test Xu Xin (vivo)
@ 2026-11-23  3:45 ` Xu Xin (vivo)
  2026-11-23 16:49   ` David Hildenbrand (Arm)
  3 siblings, 1 reply; 8+ messages in thread
From: Xu Xin (vivo) @ 2026-11-23  3:45 UTC (permalink / raw)
  To: xu.xin
  Cc: akpm, chengming.zhou, david, donettom, linux-kernel, linux-mm,
	stable

Extend test_fork_ksm_merging_page_count() to enable use_zero_pages and
merge zero pages alongside non-zero pages before fork(), verifying that
neither ksm_merging_pages nor ksm_zero_pages is inherited by the child.

Signed-off-by: Xu Xin (vivo) <xu.xin@linux.dev>
---
 .../selftests/mm/ksm_functional_tests.c       | 44 +++++++++++++++----
 1 file changed, 35 insertions(+), 9 deletions(-)

diff --git a/tools/testing/selftests/mm/ksm_functional_tests.c b/tools/testing/selftests/mm/ksm_functional_tests.c
index b871d5656688..0e128c579d5c 100644
--- a/tools/testing/selftests/mm/ksm_functional_tests.c
+++ b/tools/testing/selftests/mm/ksm_functional_tests.c
@@ -655,45 +655,71 @@ static void test_prot_none(void)
 	munmap(map, size);
 }
 
-static void test_fork_ksm_merging_page_count(void)
+static void test_fork_ksm_statistic_count(void)
 {
 	const unsigned int size = 2 * MiB;
+	long merging_pages, zero_pages;
 	char *map;
+	char *zero_map;
 	pid_t child_pid;
 	int status;
 
 	ksft_print_msg("[RUN] %s\n", __func__);
 
+	if (ksm_use_zero_pages() < 0) {
+		ksft_test_result_skip("Enabling use_zero_pages failed\n");
+		return;
+	}
+
 	map = mmap_and_merge_range(0xcf, size, PROT_READ | PROT_WRITE, KSM_MERGE_MADVISE);
 	if (map == MAP_FAILED)
 		return;
 
+	zero_map = mmap_and_merge_range(0x00, size, PROT_READ | PROT_WRITE, KSM_MERGE_MADVISE);
+	if (zero_map == MAP_FAILED)
+		goto unmap;
+
+	merging_pages = ksm_get_self_merging_pages();
+	zero_pages = ksm_get_self_zero_pages();
+	if (merging_pages < 0 || zero_pages < 0) {
+		ksft_test_result_skip("read KSM stats failed\n");
+		goto unmap_zero;
+	}
+
+	if (!merging_pages || !zero_pages) {
+		ksft_test_result_fail("KSM failed to merge pages before fork\n");
+		goto unmap_zero;
+	}
+
 	if (ksm_pause() < 0) {
 		ksft_test_result_fail("Stop ksmd from running failed\n");
-		goto unmap;
+		goto unmap_zero;
 	}
 
 	child_pid = fork();
 	if (!child_pid) {
-		exit(!!ksm_get_self_merging_pages());
+		merging_pages = ksm_get_self_merging_pages();
+		zero_pages = ksm_get_self_zero_pages();
+		exit(merging_pages != 0 || zero_pages != 0);
 	} else if (child_pid < 0) {
 		ksft_test_result_fail("fork() failed\n");
-		goto unmap;
+		goto unmap_zero;
 	}
 
 	if (waitpid(child_pid, &status, 0) < 0) {
 		ksft_test_result_fail("waitpid() failed\n");
-		goto unmap;
+		goto unmap_zero;
 	}
 
 	status = WEXITSTATUS(status);
 	if (status) {
 		ksft_test_result_fail("ksm_merging_page in child: %d\n", status);
-		goto unmap;
+		goto unmap_zero;
 	}
 
-	ksft_test_result_pass("ksm_merging_pages is not inherited after fork\n");
-
+	ksft_test_result_pass("ksm_merging_pages and ksm_zero_pages are reset after fork\n");
+unmap_zero:
+	munmap(zero_map, size);
 unmap:
 	ksm_stop();
 	munmap(map, size);
@@ -842,7 +868,7 @@ int main(int argc, char **argv)
 	test_prctl_fork();
 	test_prctl_fork_exec();
 	test_prctl_unmerge();
-	test_fork_ksm_merging_page_count();
+	test_fork_ksm_statistic_count();
 	test_merge_aged_pairs();
 
 	err = ksft_get_fail_cnt();
-- 
2.34.1


^ permalink raw reply related	[flat|nested] 8+ messages in thread

* Re: [PATCH v3 1/3] mm/ksm: do not inherit ksm_zero_pages counter or PTE markers on fork
  2026-11-23  3:43 ` Xu Xin (vivo)
@ 2026-11-23 16:38   ` David Hildenbrand (Arm)
  0 siblings, 0 replies; 8+ messages in thread
From: David Hildenbrand (Arm) @ 2026-11-23 16:38 UTC (permalink / raw)
  To: Xu Xin (vivo)
  Cc: akpm, chengming.zhou, donettom, linux-kernel, linux-mm, stable,
	Karl Mehltretter

On 11/23/26 04:43, Xu Xin (vivo) wrote:
> As documented in Documentation/admin-guide/mm/ksm.rst, ksm_zero_pages
> accounts only for zero pages actually placed by KSM.  However, the
> current implementation wrongly accounts for forked zero-page PTEs as
> KSM's contribution, inflating both the child's per-mm counter and the
> global ksm_zero_pages counter.
> 
> Originally, commit e2942062e01d ("ksm: count all zero pages placed by
> KSM") marked KSM-placed zero-page PTEs with the dirty bit for unmap
> accounting, but forgot to clear this marker during fork().  Later, to
> prevent ksm_might_unmap_zero_page() from underflowing the counters on
> child exit[1], commit 4d6fc29f3634 ("mm/ksm: fix incorrect KSM counter
> handling in mm_struct during fork") kept the child's inherited per-mm
> counter and added it to the global counter.
> 
> Instead of inflating the counters, fix the root cause by resetting the
> child's mm->ksm_zero_pages to 0 in ksm_fork() and clearing the KSM
> zero-page marker via ksm_fork_pte() when copying present PTEs in
> copy_present_ptes().  With the marker cleared,
> ksm_might_unmap_zero_page() will not decrement the counters on child
> exit, MADV_UNMERGEABLE in the child will not unnecessarily unshare
> inherited zero pages, and the global counter remains untouched.
> 
> [1] https://lore.kernel.org/all/53a7bf3d-843d-4e19-b0a3-cc6852fe72c1@redhat.com/
> 
> Fixes: 4d6fc29f3634 ("mm/ksm: fix incorrect KSM counter handling in mm_struct during fork")
> Cc: stable@vger.kernel.org
> Tested-by: Karl Mehltretter <kmehltretter@gmail.com>
> Signed-off-by: Xu Xin (vivo) <xu.xin@linux.dev>
> ---
> Changes in v3:
> - Rename might_clear_ksm_zero_pte() to ksm_fork_pte() and move the
>   is_ksm_zero_pte() check into copy_present_ptes() under the !page
>   branch, as suggested by David Hildenbrand.
> - Expand the comment above ksm_fork_pte() to explain why the marker is
>   cleared on fork.
> - Add Tested-by tag from Karl Mehltretter.
> 
>  Documentation/admin-guide/mm/ksm.rst |  7 ++++++-
>  include/linux/ksm.h                  | 22 +++++++++++++++++++---
>  mm/memory.c                          |  5 ++++-
>  3 files changed, 29 insertions(+), 5 deletions(-)
> 
> diff --git a/Documentation/admin-guide/mm/ksm.rst b/Documentation/admin-guide/mm/ksm.rst
> index c329ca747b8c..8968ae3f55c0 100644
> --- a/Documentation/admin-guide/mm/ksm.rst
> +++ b/Documentation/admin-guide/mm/ksm.rst
> @@ -214,7 +214,12 @@ stable_node_dups
>          number of duplicated KSM pages
>  ksm_zero_pages
>          how many zero pages that are still mapped into processes were mapped by
> -        KSM when deduplicating.
> +        KSM when deduplicating. Note: on fork(), the child process does not
> +        inherit the ``ksm_zero_pages`` counter, and any inherited KSM-placed
> +        zero-page mappings are converted into ordinary shared zero-page
> +        mappings. Consequently, these mappings are neither accounted for in
> +        the child's counter nor unshared when ``MADV_UNMERGEABLE`` is called
> +        in the child.
>  
>  When ``use_zero_pages`` is/was enabled, the sum of ``pages_sharing`` +
>  ``ksm_zero_pages`` represents the actual number of pages saved by KSM.
> diff --git a/include/linux/ksm.h b/include/linux/ksm.h
> index 596c04ca7326..f29aec4496d0 100644
> --- a/include/linux/ksm.h
> +++ b/include/linux/ksm.h
> @@ -32,6 +32,17 @@ void __ksm_exit(struct mm_struct *mm);
>   */
>  #define is_ksm_zero_pte(pte)	(is_zero_pfn(pte_pfn(pte)) && pte_dirty(pte))
>  
> +/*
> + * Since the inherited mappings on fork are not expected to be accounted for
> + * in the child's ksm_zero_pages counter (reset in ksm_fork()), we must
> + * clear KSM's dirty-bit marker on KSM-placed zero-page PTEs to avoid
> + * underflowing the counters on child exit.
> + */
> +static inline pte_t ksm_fork_pte(pte_t pte)
> +{

Instead of the long function comment, I'd just have here instead:

/*
 * Strip KSM information from the PTE for the child to simplify
 * ksm_zero_pages accounting, and to indicate each deduplicated zeropage
 * only once towards the user.
 */

I can fix that up when applying.

-- 
Cheers,

David

^ permalink raw reply	[flat|nested] 8+ messages in thread

* Re: [PATCH v3 2/3] selftests/mm: fix false-positive and racy KSM fork test
  2026-11-23  3:45 ` [PATCH v3 2/3] selftests/mm: fix false-positive and racy KSM fork test Xu Xin (vivo)
@ 2026-11-23 16:43   ` David Hildenbrand (Arm)
  0 siblings, 0 replies; 8+ messages in thread
From: David Hildenbrand (Arm) @ 2026-11-23 16:43 UTC (permalink / raw)
  To: Xu Xin (vivo)
  Cc: akpm, chengming.zhou, donettom, linux-kernel, linux-mm, stable

On 11/23/26 04:45, Xu Xin (vivo) wrote:
> Currently, test_fork_ksm_merging_page_count() passes wrongly even if
> fork() fails to reset mm->ksm_merging_pages, because the child process
> calls init_global_file_handles() -> ksm_stop(), which unmerges all KSM
> pages across the system before reading its counters.
> 
> Fix three issues in test_fork_ksm_merging_page_count():
> 
> - Drop init_global_file_handles() in the child process so it does not
>   call ksm_stop() and mutate global KSM sysfs state (unmerging all KSM
>   pages across the system) before reading its counters.

Right, that's not required just to access proc_self_ksm_merging_pages_fd.

> 
> - Use '!!' in exit(!!ksm_get_self_merging_pages()) to avoid 8-bit exit
>   status truncation (e.g., 512 pages on 4 KiB systems truncating to 0).

Ack.

> 
> - Introduce ksm_pause() to pause ksmd (write "0" to /sys/kernel/mm/ksm/run)
>   before fork(), preventing ksmd from scanning the child and incrementing
>   its counter before it is read.
> 
> Signed-off-by: Xu Xin (vivo) <xu.xin@linux.dev>
> ---
>  .../testing/selftests/mm/ksm_functional_tests.c  |  8 ++++++--
>  tools/testing/selftests/mm/vm_util.c             | 16 ++++++++++++++++
>  tools/testing/selftests/mm/vm_util.h             |  1 +
>  3 files changed, 23 insertions(+), 2 deletions(-)
> 
> diff --git a/tools/testing/selftests/mm/ksm_functional_tests.c b/tools/testing/selftests/mm/ksm_functional_tests.c
> index 135191f99962..b871d5656688 100644
> --- a/tools/testing/selftests/mm/ksm_functional_tests.c
> +++ b/tools/testing/selftests/mm/ksm_functional_tests.c
> @@ -668,10 +668,14 @@ static void test_fork_ksm_merging_page_count(void)
>  	if (map == MAP_FAILED)
>  		return;
>  
> +	if (ksm_pause() < 0) {
> +		ksft_test_result_fail("Stop ksmd from running failed\n");
> +		goto unmap;
> +	}
> +
>  	child_pid = fork();
>  	if (!child_pid) {
> -		init_global_file_handles();
> -		exit(ksm_get_self_merging_pages());
> +		exit(!!ksm_get_self_merging_pages());
>  	} else if (child_pid < 0) {
>  		ksft_test_result_fail("fork() failed\n");
>  		goto unmap;
> diff --git a/tools/testing/selftests/mm/vm_util.c b/tools/testing/selftests/mm/vm_util.c
> index f26f9e4bfdbe..e638475543e6 100644
> --- a/tools/testing/selftests/mm/vm_util.c
> +++ b/tools/testing/selftests/mm/vm_util.c
> @@ -1080,6 +1080,22 @@ int ksm_stop(void)
>  	return ret == 1 ? 0 : -EIO;
>  }
>  
> +int ksm_pause(void)
> +{
> +	int ksm_fd;
> +	ssize_t ret;
> +
> +	ksm_fd = open("/sys/kernel/mm/ksm/run", O_RDWR);
> +	if (ksm_fd < 0)
> +		return -errno;
> +
> +	ret = write(ksm_fd, "0", 1);
> +	close(ksm_fd);
> +	if (ret < 0)
> +		return -errno;

Could close() fail and set a different errno? Unlikely I guess, so this is
probably sufficient as is.

Reviewed-by: David Hildenbrand (Arm) <david@kernel.org>

-- 
Cheers,

David

^ permalink raw reply	[flat|nested] 8+ messages in thread

* Re: [PATCH v3 3/3] selftests/mm: verify ksm_zero_pages is not inherited on fork
  2026-11-23  3:45 ` [PATCH v3 3/3] selftests/mm: verify ksm_zero_pages is not inherited on fork Xu Xin (vivo)
@ 2026-11-23 16:49   ` David Hildenbrand (Arm)
  0 siblings, 0 replies; 8+ messages in thread
From: David Hildenbrand (Arm) @ 2026-11-23 16:49 UTC (permalink / raw)
  To: Xu Xin (vivo)
  Cc: akpm, chengming.zhou, donettom, linux-kernel, linux-mm, stable

On 11/23/26 04:45, Xu Xin (vivo) wrote:
> Extend test_fork_ksm_merging_page_count() to enable use_zero_pages and
> merge zero pages alongside non-zero pages before fork(), verifying that>
neither ksm_merging_pages nor ksm_zero_pages is inherited by the child.
> 
> Signed-off-by: Xu Xin (vivo) <xu.xin@linux.dev>
> ---
>  .../selftests/mm/ksm_functional_tests.c       | 44 +++++++++++++++----
>  1 file changed, 35 insertions(+), 9 deletions(-)
> 
> diff --git a/tools/testing/selftests/mm/ksm_functional_tests.c b/tools/testing/selftests/mm/ksm_functional_tests.c
> index b871d5656688..0e128c579d5c 100644
> --- a/tools/testing/selftests/mm/ksm_functional_tests.c
> +++ b/tools/testing/selftests/mm/ksm_functional_tests.c
> @@ -655,45 +655,71 @@ static void test_prot_none(void)
>  	munmap(map, size);
>  }
>  
> -static void test_fork_ksm_merging_page_count(void)
> +static void test_fork_ksm_statistic_count(void)

"statistic_count" sounds odd. did you mean "statistics" or "counters". Below you
use "stats".

>  {
>  	const unsigned int size = 2 * MiB;
> +	long merging_pages, zero_pages;
>  	char *map;
> +	char *zero_map;

Can combine with previous line.

>  	pid_t child_pid;
>  	int status;
>  
>  	ksft_print_msg("[RUN] %s\n", __func__);
>  
> +	if (ksm_use_zero_pages() < 0) {
> +		ksft_test_result_skip("Enabling use_zero_pages failed\n");
> +		return;
> +	}
> +
>  	map = mmap_and_merge_range(0xcf, size, PROT_READ | PROT_WRITE, KSM_MERGE_MADVISE);
>  	if (map == MAP_FAILED)
>  		return;
>  
> +	zero_map = mmap_and_merge_range(0x00, size, PROT_READ | PROT_WRITE, KSM_MERGE_MADVISE);
> +	if (zero_map == MAP_FAILED)
> +		goto unmap;
> +
> +	merging_pages = ksm_get_self_merging_pages();
> +	zero_pages = ksm_get_self_zero_pages();
> +	if (merging_pages < 0 || zero_pages < 0) {
> +		ksft_test_result_skip("read KSM stats failed\n");

"reading"

> +		goto unmap_zero;
> +	}
> +
> +	if (!merging_pages || !zero_pages) {
> +		ksft_test_result_fail("KSM failed to merge pages before fork\n");
> +		goto unmap_zero;
> +	}
> +
>  	if (ksm_pause() < 0) {
>  		ksft_test_result_fail("Stop ksmd from running failed\n");
> -		goto unmap;
> +		goto unmap_zero;
>  	}
>  
>  	child_pid = fork();
>  	if (!child_pid) {
> -		exit(!!ksm_get_self_merging_pages());
> +		merging_pages = ksm_get_self_merging_pages();
> +		zero_pages = ksm_get_self_zero_pages();
> +		exit(merging_pages != 0 || zero_pages != 0);
>  	} else if (child_pid < 0) {
>  		ksft_test_result_fail("fork() failed\n");
> -		goto unmap;
> +		goto unmap_zero;
>  	}
>  
>  	if (waitpid(child_pid, &status, 0) < 0) {
>  		ksft_test_result_fail("waitpid() failed\n");
> -		goto unmap;
> +		goto unmap_zero;
>  	}
>  
>  	status = WEXITSTATUS(status);
>  	if (status) {
>  		ksft_test_result_fail("ksm_merging_page in child: %d\n", status);
> -		goto unmap;
> +		goto unmap_zero;
>  	}
>  
> -	ksft_test_result_pass("ksm_merging_pages is not inherited after fork\n");
> -
> +	ksft_test_result_pass("ksm_merging_pages and ksm_zero_pages are reset after fork\n");
> +unmap_zero:
> +	munmap(zero_map, size);
>  unmap:
>  	ksm_stop();
>  	munmap(map, size);

This ordering is odd.

Why stop in between?

Also, I suggest using a single label, like:

char *zero_map = MAP_FAILED, *map = MAP_FAILED;

...

if (zero_map != MAP_FAILED)
	munmap(zero_map, size);
if (map != MAP_FAILED)
	munmap(map, size);

-- 
Cheers,

David

^ permalink raw reply	[flat|nested] 8+ messages in thread

end of thread, other threads:[~2026-11-23 16:49 UTC | newest]

Thread overview: 8+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-11-23  3:41 [PATCH v3 0/3] mm/ksm: fix ksm_zero_pages accounting on fork Xu Xin (vivo)
2026-11-23  3:43 ` [PATCH v3 1/3] mm/ksm: do not inherit ksm_zero_pages counter or PTE markers " Xu Xin (vivo)
2026-11-23  3:43 ` Xu Xin (vivo)
2026-11-23 16:38   ` David Hildenbrand (Arm)
2026-11-23  3:45 ` [PATCH v3 2/3] selftests/mm: fix false-positive and racy KSM fork test Xu Xin (vivo)
2026-11-23 16:43   ` David Hildenbrand (Arm)
2026-11-23  3:45 ` [PATCH v3 3/3] selftests/mm: verify ksm_zero_pages is not inherited on fork Xu Xin (vivo)
2026-11-23 16:49   ` David Hildenbrand (Arm)

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox