Re: [PATCH v3 2/3] selftests/mm: fix false-positive and racy KSM fork test
From: David Hildenbrand (Arm)
Date: Mon Nov 23 2026 - 11:43:59 EST
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@xxxxxxxxx>
> ---
> .../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@xxxxxxxxxx>
--
Cheers,
David