| Seq | Timestamp | Type | Name | Duration |
|---|---|---|---|---|
| 0/0 | 2026/08/03 01:03 | flow | patch-triage |
0mArgs:null Results: {
"EnableConfigs": null,
"FocusSymbols": [],
"Reasoning": "The patch only modifies userspace selftests (tools/testing/selftests/mm/*) and does not make any functional changes to the kernel itself.",
"WorthFuzzing": false
} |
| 1/1 | 2026/08/03 01:03 | action | read-patch-diff |
0mArgs:null Results: {
"PatchDiff": "commit 3fa40324c911cdd9f435266d3eceea6b52ef71c6\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate: Mon Aug 3 01:03:13 2026 +0000\n\n syz-cluster: applied patch under review\n\ndiff --git a/tools/testing/selftests/mm/.gitignore b/tools/testing/selftests/mm/.gitignore\nindex 9ccd9e1447e66..616043a0fcd22 100644\n--- a/tools/testing/selftests/mm/.gitignore\n+++ b/tools/testing/selftests/mm/.gitignore\n@@ -66,3 +66,6 @@ merge\n prctl_thp_disable\n rmap\n folio_split_race_test\n+folio_order_check\n+khugepaged_sync_check\n+khugepaged_race\ndiff --git a/tools/testing/selftests/mm/Makefile b/tools/testing/selftests/mm/Makefile\nindex 25d10ced3b3b9..026d4b61414d4 100644\n--- a/tools/testing/selftests/mm/Makefile\n+++ b/tools/testing/selftests/mm/Makefile\n@@ -104,6 +104,9 @@ TEST_GEN_FILES += guard-regions\n TEST_GEN_FILES += merge\n TEST_GEN_FILES += rmap\n TEST_GEN_FILES += folio_split_race_test\n+TEST_GEN_FILES += folio_order_check\n+TEST_GEN_FILES += khugepaged_sync_check\n+TEST_GEN_FILES += khugepaged_race\n \n ifneq ($(ARCH),arm64)\n TEST_GEN_FILES += soft-dirty\ndiff --git a/tools/testing/selftests/mm/folio_order_check.c b/tools/testing/selftests/mm/folio_order_check.c\nnew file mode 100644\nindex 0000000000000..f70d766ff3eb3\n--- /dev/null\n+++ b/tools/testing/selftests/mm/folio_order_check.c\n@@ -0,0 +1,138 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Self-check for the vm_util folio-order detection helpers,\n+ * is_backed_by_folio() and is_range_backed_by_folio_orders().\n+ *\n+ * For every anon THP order the kernel supports, fault memory in with only\n+ * that order enabled and verify the helpers report exactly that order:\n+ * not a neighbouring order, and plain 4K memory as order 0. The helpers\n+ * are what the khugepaged mTHP tests use to detect collapse results, so\n+ * they must agree with the kernel's own idea of the backing before any\n+ * collapse test relies on them.\n+ */\n+#define _GNU_SOURCE\n+#include \u003cfcntl.h\u003e\n+#include \u003cstdio.h\u003e\n+#include \u003cstdlib.h\u003e\n+#include \u003csys/mman.h\u003e\n+#include \u003cunistd.h\u003e\n+\n+#include \"kselftest.h\"\n+#include \"vm_util.h\"\n+#include \"hugepage_settings.h\"\n+\n+static int pagemap_fd;\n+static int kpageflags_fd;\n+\n+/* mmap an anon VMA of exactly @size bytes at a @size-aligned address. */\n+static char *alloc_aligned(size_t size)\n+{\n+\tsize_t len = size * 2;\n+\tuintptr_t aligned;\n+\tchar *p;\n+\n+\tp = mmap(NULL, len, PROT_READ | PROT_WRITE,\n+\t\t MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);\n+\tif (p == MAP_FAILED)\n+\t\tksft_exit_fail_perror(\"mmap()\");\n+\n+\taligned = ((uintptr_t)p + size - 1) \u0026 ~(size - 1);\n+\tif (aligned != (uintptr_t)p)\n+\t\tmunmap(p, aligned - (uintptr_t)p);\n+\tif (aligned + size != (uintptr_t)p + len)\n+\t\tmunmap((char *)aligned + size,\n+\t\t (uintptr_t)p + len - aligned - size);\n+\n+\treturn (char *)aligned;\n+}\n+\n+/*\n+ * Enable only @order (order 0: nothing), fault one aligned window in and\n+ * check the helpers see exactly @order.\n+ */\n+static void check_order(int order)\n+{\n+\tstruct thp_settings settings = *thp_current_settings();\n+\tsize_t size = psize() \u003c\u003c order;\n+\tbool ok = true;\n+\tchar *p;\n+\tint i;\n+\n+\tfor (i = 0; i \u003c NR_ORDERS; i++)\n+\t\tsettings.hugepages[i].enabled = THP_NEVER;\n+\tif (order)\n+\t\tsettings.hugepages[order].enabled = THP_ALWAYS;\n+\tthp_push_settings(\u0026settings);\n+\n+\tp = alloc_aligned(size);\n+\t*p = 1;\n+\n+\tif (!is_range_backed_by_folio_orders(p, size, order,\n+\t\t\t\t\t pagemap_fd, kpageflags_fd)) {\n+\t\tksft_print_msg(\"order %d not detected after fault\\n\", order);\n+\t\tok = false;\n+\t}\n+\n+\t/* A lower order must be rejected: the folio is larger. */\n+\tif (order \u0026\u0026 is_range_backed_by_folio_orders(p, size, order - 1,\n+\t\t\t\t\t\t pagemap_fd,\n+\t\t\t\t\t\t kpageflags_fd)) {\n+\t\tksft_print_msg(\"order %d also reported as order %d\\n\",\n+\t\t\t order, order - 1);\n+\t\tok = false;\n+\t}\n+\n+\t/* Order 0 pages must not look like any large folio, and vice versa. */\n+\tif (order \u0026\u0026 is_range_backed_by_folio_orders(p, size, 0,\n+\t\t\t\t\t\t pagemap_fd,\n+\t\t\t\t\t\t kpageflags_fd)) {\n+\t\tksft_print_msg(\"order %d also reported as order 0\\n\", order);\n+\t\tok = false;\n+\t}\n+\n+\tmunmap(p, size);\n+\tthp_pop_settings();\n+\n+\tksft_test_result(ok, \"order %d classified\\n\", order);\n+}\n+\n+int main(void)\n+{\n+\tstruct thp_settings settings;\n+\tunsigned long orders;\n+\tint order;\n+\n+\tksft_print_header();\n+\n+\tif (!thp_available())\n+\t\tksft_exit_skip(\"Transparent Hugepages not available\\n\");\n+\n+\tpagemap_fd = open(\"/proc/self/pagemap\", O_RDONLY);\n+\tif (pagemap_fd \u003c 0)\n+\t\tksft_exit_fail_perror(\"open(\\\"/proc/self/pagemap\\\")\");\n+\tkpageflags_fd = open(\"/proc/kpageflags\", O_RDONLY);\n+\tif (kpageflags_fd \u003c 0)\n+\t\tksft_exit_skip(\"open(\\\"/proc/kpageflags\\\") requires root\\n\");\n+\n+\torders = thp_supported_orders();\n+\tif (!orders)\n+\t\tksft_exit_skip(\"No supported THP orders\\n\");\n+\n+\tksft_set_plan(__builtin_popcountl(orders) + 1);\n+\n+\tthp_save_settings();\n+\tthp_read_settings(\u0026settings);\n+\t/* Base of the settings stack; the bottom entry is never popped. */\n+\tthp_push_settings(\u0026settings);\n+\n+\tcheck_order(0);\n+\tfor (order = 1; order \u003c NR_ORDERS; order++) {\n+\t\tif (!(orders \u0026 (1UL \u003c\u003c order)))\n+\t\t\tcontinue;\n+\t\tcheck_order(order);\n+\t}\n+\n+\tthp_restore_settings();\n+\n+\tksft_finished();\n+}\ndiff --git a/tools/testing/selftests/mm/hugepage_settings.c b/tools/testing/selftests/mm/hugepage_settings.c\nindex d7917dce3abac..a26a0cffa9c5b 100644\n--- a/tools/testing/selftests/mm/hugepage_settings.c\n+++ b/tools/testing/selftests/mm/hugepage_settings.c\n@@ -183,6 +183,17 @@ void thp_read_settings(struct thp_settings *settings)\n \t}\n }\n \n+/*\n+ * Write only on change: any store to a khugepaged sysfs knob wakes the\n+ * daemon, and settings pushes/pops must not start scan passes nobody\n+ * asked for — khugepaged_full_pass() is the only sanctioned wake.\n+ */\n+static void thp_update_num(const char *name, unsigned long num)\n+{\n+\tif (thp_read_num(name) != num)\n+\t\tthp_write_num(name, num);\n+}\n+\n void thp_write_settings(struct thp_settings *settings)\n {\n \tstruct khugepaged_settings *khugepaged = \u0026settings-\u003ekhugepaged;\n@@ -198,15 +209,15 @@ void thp_write_settings(struct thp_settings *settings)\n \t\t\tshmem_enabled_strings[settings-\u003eshmem_enabled]);\n \tthp_write_num(\"use_zero_page\", settings-\u003euse_zero_page);\n \n-\tthp_write_num(\"khugepaged/defrag\", khugepaged-\u003edefrag);\n-\tthp_write_num(\"khugepaged/alloc_sleep_millisecs\",\n-\t\t\tkhugepaged-\u003ealloc_sleep_millisecs);\n-\tthp_write_num(\"khugepaged/scan_sleep_millisecs\",\n-\t\t\tkhugepaged-\u003escan_sleep_millisecs);\n-\tthp_write_num(\"khugepaged/max_ptes_none\", khugepaged-\u003emax_ptes_none);\n-\tthp_write_num(\"khugepaged/max_ptes_swap\", khugepaged-\u003emax_ptes_swap);\n-\tthp_write_num(\"khugepaged/max_ptes_shared\", khugepaged-\u003emax_ptes_shared);\n-\tthp_write_num(\"khugepaged/pages_to_scan\", khugepaged-\u003epages_to_scan);\n+\tthp_update_num(\"khugepaged/defrag\", khugepaged-\u003edefrag);\n+\tthp_update_num(\"khugepaged/alloc_sleep_millisecs\",\n+\t\t khugepaged-\u003ealloc_sleep_millisecs);\n+\tthp_update_num(\"khugepaged/scan_sleep_millisecs\",\n+\t\t khugepaged-\u003escan_sleep_millisecs);\n+\tthp_update_num(\"khugepaged/max_ptes_none\", khugepaged-\u003emax_ptes_none);\n+\tthp_update_num(\"khugepaged/max_ptes_swap\", khugepaged-\u003emax_ptes_swap);\n+\tthp_update_num(\"khugepaged/max_ptes_shared\", khugepaged-\u003emax_ptes_shared);\n+\tthp_update_num(\"khugepaged/pages_to_scan\", khugepaged-\u003epages_to_scan);\n \n \tif (dev_queue_read_ahead_path[0])\n \t\twrite_num(dev_queue_read_ahead_path, settings-\u003eread_ahead_kb);\n@@ -230,6 +241,43 @@ void thp_write_settings(struct thp_settings *settings)\n \t}\n }\n \n+/*\n+ * Completion barrier for khugepaged: wait until a full scan pass that\n+ * started after this call has finished. full_scans must advance by two;\n+ * a +1 step may complete a pass that examined this mm before the\n+ * caller's setup was in place.\n+ *\n+ * Any store to scan_sleep_millisecs wakes the daemon, so the barrier\n+ * works regardless of the configured scan cadence. It wakes exactly\n+ * once per missing pass — over-waking would queue a straggler pass\n+ * behind the barrier, perturbing whatever the caller sets up next.\n+ * One wake completes one full pass only if the whole mm list fits in\n+ * one scan batch, so callers must pair this with a large\n+ * pages_to_scan.\n+ */\n+bool khugepaged_full_pass(unsigned int timeout_s)\n+{\n+\tunsigned long deadline_ms = timeout_s * 1000UL;\n+\tunsigned long sleep_ms =\n+\t\tthp_read_num(\"khugepaged/scan_sleep_millisecs\");\n+\tunsigned long elapsed_ms = 0;\n+\tint pass;\n+\n+\tfor (pass = 0; pass \u003c 2; pass++) {\n+\t\tunsigned long target =\n+\t\t\tthp_read_num(\"khugepaged/full_scans\") + 1;\n+\n+\t\tthp_write_num(\"khugepaged/scan_sleep_millisecs\", sleep_ms);\n+\t\twhile (thp_read_num(\"khugepaged/full_scans\") \u003c target) {\n+\t\t\tif (elapsed_ms \u003e= deadline_ms)\n+\t\t\t\treturn false;\n+\t\t\tusleep(10 * 1000);\n+\t\t\telapsed_ms += 10;\n+\t\t}\n+\t}\n+\treturn true;\n+}\n+\n struct thp_settings *thp_current_settings(void)\n {\n \tif (!settings_index) {\ndiff --git a/tools/testing/selftests/mm/hugepage_settings.h b/tools/testing/selftests/mm/hugepage_settings.h\nindex 726c73c43c05b..8de446affeecd 100644\n--- a/tools/testing/selftests/mm/hugepage_settings.h\n+++ b/tools/testing/selftests/mm/hugepage_settings.h\n@@ -83,6 +83,8 @@ static inline void thp_save_settings(void)\n \thugepage_save_settings(/* thp = */ true, /* hugetlb = */ false);\n }\n \n+bool khugepaged_full_pass(unsigned int timeout_s);\n+\n void thp_set_read_ahead_path(char *path);\n unsigned long thp_supported_orders(void);\n unsigned long thp_shmem_supported_orders(void);\ndiff --git a/tools/testing/selftests/mm/khugepaged.c b/tools/testing/selftests/mm/khugepaged.c\nindex 10e8dedcb087d..c5a3c39225819 100644\n--- a/tools/testing/selftests/mm/khugepaged.c\n+++ b/tools/testing/selftests/mm/khugepaged.c\n@@ -26,9 +26,13 @@\n \n #define BASE_ADDR ((void *)(1UL \u003c\u003c 30))\n static unsigned long hpage_pmd_size;\n+static int hpage_pmd_order;\n static unsigned long page_size;\n static int hpage_pmd_nr;\n static int anon_order;\n+static int anon_target_order;\n+static int pagemap_fd = -1;\n+static int kpageflags_fd = -1;\n \n #define PID_SMAPS \"/proc/self/smaps\"\n #define TEST_FILE \"collapse_test_file\"\n@@ -177,6 +181,21 @@ static void get_finfo(const char *dir)\n \tksft_exit_fail_msg(\"%s: Could not read: %s\\n\", __func__, path);\n }\n \n+static bool has_swap(void)\n+{\n+\tFILE *fp = fopen(\"/proc/swaps\", \"r\");\n+\tchar line[MAX_LINE_LENGTH];\n+\tbool ret = false;\n+\n+\tif (!fp)\n+\t\treturn false;\n+\t/* First line is the header; any following line is a swap area. */\n+\tif (fgets(line, sizeof(line), fp) \u0026\u0026 fgets(line, sizeof(line), fp))\n+\t\tret = true;\n+\tfclose(fp);\n+\treturn ret;\n+}\n+\n static bool check_swap(void *addr, unsigned long size)\n {\n \tbool swap = false;\n@@ -554,8 +573,17 @@ static void madvise_collapse(const char *msg, char *p, int nr_hpages,\n static bool wait_for_scan(const char *msg, char *p, int nr_hpages,\n \t\t\t struct mem_ops *ops)\n {\n+\t/*\n+\t * The budget has to cover khugepaged copying nr_hpages *\n+\t * hpage_pmd_size, plus two of its passes over the mm. Three seconds\n+\t * does that at a 2M PMD, but the same test moves 2G at a 512M PMD\n+\t * (arm64 with 64K base pages) and 3s is then marginal: it fails on a\n+\t * collapse that completes correctly, just not inside the budget.\n+\t * Allow a further second per 64M to collapse.\n+\t */\n+\tconst unsigned long bytes = (unsigned long)nr_hpages * hpage_pmd_size;\n+\tint timeout = 6 + 2 * (bytes / (64UL \u003c\u003c 20));\n \tint full_scans;\n-\tint timeout = 6; /* 3 seconds */\n \n \t/* Sanity check */\n \tif (!ops-\u003echeck_huge(p, 0))\n@@ -735,6 +763,10 @@ static void collapse_swapin_single_pte(struct collapse_context *c, struct mem_op\n \tvoid *p;\n \n \tp = ops-\u003esetup_area(1);\n+\tif (!has_swap()) {\n+\t\tskip(\"Skip (no swap configured)\");\n+\t\tgoto out;\n+\t}\n \tops-\u003efault(p, 0, hpage_pmd_size);\n \n \tksft_print_msg(\"Swapout one page...\");\n@@ -761,6 +793,10 @@ static void collapse_max_ptes_swap(struct collapse_context *c, struct mem_ops *o\n \tvoid *p;\n \n \tp = ops-\u003esetup_area(1);\n+\tif (!has_swap()) {\n+\t\tskip(\"Skip (no swap configured)\");\n+\t\tgoto out;\n+\t}\n \tops-\u003efault(p, 0, hpage_pmd_size);\n \n \tksft_print_msg(\"Swapout %d of %d pages...\", max_ptes_swap + 1, hpage_pmd_nr);\n@@ -853,6 +889,21 @@ static void collapse_compound_extreme(struct collapse_context *c, struct mem_ops\n \tvoid *p;\n \tint i;\n \n+\t/*\n+\t * Builds a PMD's worth of distinct PTE-mapped compound pages by cycling\n+\t * hpage_pmd_nr fault-time THPs through mremap. Fault-time THP allocation\n+\t * is best-effort, and this needs hpage_pmd_nr PMD-order pages in a row:\n+\t * fine at a 2M (4K base) or 32M (16K base) PMD, but a 512M PMD (arm64/64K)\n+\t * is an order-13 allocation the allocator cannot reliably hand out even\n+\t * once, let alone 8192 times. Cap at a 32M PMD; MADV_COLLAPSE-driven cases\n+\t * still cover PMD-order collapse on the larger configs.\n+\t */\n+\tif (hpage_pmd_size \u003e (32UL \u003c\u003c 20)) {\n+\t\tksft_test_result_skip(\"%s: PMD too large for fault-time THP construction\\n\",\n+\t\t\t\t __func__);\n+\t\treturn;\n+\t}\n+\n \tp = ops-\u003esetup_area(1);\n \tksft_print_msg(\"Construct PTE page table full of different PTE-mapped compound pages\\n\");\n \tfor (i = 0; i \u003c hpage_pmd_nr; i++) {\n@@ -1043,6 +1094,61 @@ static void collapse_max_ptes_shared(struct collapse_context *c, struct mem_ops\n \tksft_test_result_report(exit_status, \"%s\\n\", __func__);\n }\n \n+/*\n+ * Content stays isolated while a co-sharer writes concurrently. A shared\n+ * source is copied live (not frozen), relying on it being CoW - immutable\n+ * for the duration of the copy; a co-sharer's write goes to a CoW copy. The\n+ * collapsing child must see the pre-fork content, the writing parent only\n+ * its own writes.\n+ */\n+static void collapse_fork_cow_race(struct collapse_context *c, struct mem_ops *ops)\n+{\n+\tconst unsigned long shared = 64 * page_size;\n+\tconst int stride = page_size / sizeof(int);\n+\tint wstatus, i, n = shared / page_size;\n+\tint *ip;\n+\tvoid *p;\n+\n+\tp = ops-\u003esetup_area(1);\n+\tip = p;\n+\tops-\u003efault(p, 0, shared);\t\t/* shared prefix, pre-fork pattern */\n+\n+\tksft_print_msg(\"Fork, collapse in the child while the parent rewrites...\");\n+\tif (!fork()) {\n+\t\tops-\u003efault(p, shared, hpage_pmd_size);\t/* private remainder */\n+\t\tc-\u003ecollapse(\"Collapse a range shared with a writing co-sharer\",\n+\t\t\t p, 1, ops, true);\n+\t\tfor (i = 0; i \u003c n; i++)\n+\t\t\tif (ip[i * stride] != i + 0xdead0000) {\n+\t\t\t\tfail(\"Fail: child content\");\n+\t\t\t\tops-\u003ecleanup_area(p, hpage_pmd_size);\n+\t\t\t\t_exit(exit_status);\n+\t\t\t}\n+\t\tsuccess(\"OK\");\n+\t\tops-\u003ecleanup_area(p, hpage_pmd_size);\n+\t\t_exit(exit_status);\n+\t}\n+\n+\t/* Hammer the parent's own writes over the shared prefix. */\n+\tfor (int it = 0; it \u003c 200000; it++)\n+\t\tfor (i = 0; i \u003c n; i++)\n+\t\t\tip[i * stride] = i + 0xbeef0000;\n+\n+\twait(\u0026wstatus);\n+\texit_status = WEXITSTATUS(wstatus);\n+\n+\tksft_print_msg(\"Check the parent sees only its own writes...\");\n+\tfor (i = 0; i \u003c n; i++)\n+\t\tif (ip[i * stride] != i + 0xbeef0000)\n+\t\t\tbreak;\n+\tif (i == n)\n+\t\tsuccess(\"OK\");\n+\telse\n+\t\tfail(\"Fail: parent content\");\n+\tops-\u003ecleanup_area(p, hpage_pmd_size);\n+\tksft_test_result_report(exit_status, \"%s\\n\", __func__);\n+}\n+\n static void madvise_collapse_existing_thps(struct collapse_context *c,\n \t\t\t\t\t struct mem_ops *ops)\n {\n@@ -1088,6 +1194,222 @@ static void madvise_retracted_page_tables(struct collapse_context *c,\n \tksft_test_result_report(exit_status, \"%s\\n\", __func__);\n }\n \n+/*\n+ * Order-parameterized collapse cases (-o \u003corder\u003e): khugepaged collapses\n+ * 4K-faulted memory into folios of the given sub-PMD order. Detection is\n+ * folio-based (vm_util), not smaps: AnonHugePages only accounts PMD\n+ * mappings.\n+ *\n+ * The region is faulted before MADV_HUGEPAGE and the target order is\n+ * configured \"inherit\" under enabled=madvise, so faults are always\n+ * order 0 and the collapse product can only come from khugepaged.\n+ */\n+static size_t anon_order_size(void)\n+{\n+\treturn page_size \u003c\u003c anon_target_order;\n+}\n+\n+static bool range_collapsed(void *p, size_t len)\n+{\n+\treturn is_range_backed_by_folio_orders(p, len, anon_target_order,\n+\t\t\t\t\t pagemap_fd, kpageflags_fd);\n+}\n+\n+/* No aligned window in [p, p + len) is backed at the target order. */\n+static bool range_not_collapsed(void *p, size_t len)\n+{\n+\tsize_t window = anon_order_size();\n+\tchar *addr = p;\n+\n+\tfor (; len \u003e= window; addr += window, len -= window) {\n+\t\tif (range_collapsed(addr, window))\n+\t\t\treturn false;\n+\t}\n+\treturn true;\n+}\n+\n+static bool khugepaged_wait_full_pass(void)\n+{\n+\t/* Wait up to 30 seconds for the pass to complete. */\n+\treturn khugepaged_full_pass(30);\n+}\n+\n+/*\n+ * Cases whose geometry needs a window strictly below the PMD skip at\n+ * -o \u003cPMD order\u003e; the rest run there unchanged, baselining the legacy\n+ * PMD engine with the same test text used for the mTHP orders.\n+ */\n+static bool skip_at_pmd_order(const char *name)\n+{\n+\tif (anon_target_order \u003c hpage_pmd_order)\n+\t\treturn false;\n+\tksft_test_result_skip(\"%s: needs a window below the PMD\\n\", name);\n+\treturn true;\n+}\n+\n+static void collapse_order_full(struct collapse_context *c, struct mem_ops *ops)\n+{\n+\tvoid *p;\n+\n+\tp = ops-\u003esetup_area(1);\n+\tops-\u003efault(p, 0, hpage_pmd_size);\n+\tif (!range_not_collapsed(p, hpage_pmd_size))\n+\t\tksft_exit_fail_msg(\"Unexpected large folio after fault\\n\");\n+\n+\tmadvise(p, hpage_pmd_size, MADV_HUGEPAGE);\n+\tksft_print_msg(\"Collapse fully populated PTE table to target order...\");\n+\tif (!khugepaged_wait_full_pass())\n+\t\tfail(\"Timeout\");\n+\telse if (range_collapsed(p, hpage_pmd_size))\n+\t\tsuccess(\"OK\");\n+\telse\n+\t\tfail(\"Fail\");\n+\n+\tvalidate_memory(p, 0, hpage_pmd_size);\n+\tops-\u003ecleanup_area(p, hpage_pmd_size);\n+\tksft_test_result_report(exit_status, \"%s\\n\", __func__);\n+}\n+\n+static void collapse_order_single_window(struct collapse_context *c,\n+\t\t\t\t\t struct mem_ops *ops)\n+{\n+\tsize_t window = anon_order_size();\n+\tvoid *p;\n+\n+\tif (skip_at_pmd_order(__func__))\n+\t\treturn;\n+\n+\tp = ops-\u003esetup_area(1);\n+\tops-\u003efault(p, window, 2 * window);\n+\tif (!range_not_collapsed(p, hpage_pmd_size))\n+\t\tksft_exit_fail_msg(\"Unexpected large folio after fault\\n\");\n+\n+\tmadvise(p, hpage_pmd_size, MADV_HUGEPAGE);\n+\tksft_print_msg(\"Collapse one fully populated window...\");\n+\tif (!khugepaged_wait_full_pass())\n+\t\tfail(\"Timeout\");\n+\telse if (range_collapsed(p + window, window) \u0026\u0026\n+\t\t range_not_collapsed(p, window) \u0026\u0026\n+\t\t range_not_collapsed(p + 2 * window,\n+\t\t\t\t hpage_pmd_size - 2 * window))\n+\t\tsuccess(\"OK\");\n+\telse\n+\t\tfail(\"Fail\");\n+\n+\tvalidate_memory(p, window, 2 * window);\n+\tops-\u003ecleanup_area(p, hpage_pmd_size);\n+\tksft_test_result_report(exit_status, \"%s\\n\", __func__);\n+}\n+\n+static void collapse_order_partial_window(struct collapse_context *c,\n+\t\t\t\t\t struct mem_ops *ops)\n+{\n+\tvoid *p;\n+\n+\tp = ops-\u003esetup_area(1);\n+\tops-\u003efault(p, 0, page_size);\n+\tif (!range_not_collapsed(p, hpage_pmd_size))\n+\t\tksft_exit_fail_msg(\"Unexpected large folio after fault\\n\");\n+\n+\tmadvise(p, hpage_pmd_size, MADV_HUGEPAGE);\n+\tksft_print_msg(\"Collapse window with single PTE entry present...\");\n+\tif (!khugepaged_wait_full_pass())\n+\t\tfail(\"Timeout\");\n+\telse if (range_collapsed(p, anon_order_size()))\n+\t\tsuccess(\"OK\");\n+\telse\n+\t\tfail(\"Fail\");\n+\n+\tvalidate_memory(p, 0, page_size);\n+\tops-\u003ecleanup_area(p, hpage_pmd_size);\n+\tksft_test_result_report(exit_status, \"%s\\n\", __func__);\n+}\n+\n+static void collapse_order_max_ptes_none(struct collapse_context *c,\n+\t\t\t\t\t struct mem_ops *ops)\n+{\n+\tstruct thp_settings settings = *thp_current_settings();\n+\tsize_t window = anon_order_size();\n+\tvoid *p;\n+\n+\tif (skip_at_pmd_order(__func__))\n+\t\treturn;\n+\n+\tsettings.khugepaged.max_ptes_none = 0;\n+\tthp_push_settings(\u0026settings);\n+\n+\tp = ops-\u003esetup_area(1);\n+\tops-\u003efault(p, 0, 2 * window - page_size);\n+\tif (!range_not_collapsed(p, hpage_pmd_size))\n+\t\tksft_exit_fail_msg(\"Unexpected large folio after fault\\n\");\n+\n+\tmadvise(p, hpage_pmd_size, MADV_HUGEPAGE);\n+\tksft_print_msg(\"Collapse full window, not the one missing a page...\");\n+\tif (!khugepaged_wait_full_pass())\n+\t\tfail(\"Timeout\");\n+\telse if (range_collapsed(p, window) \u0026\u0026\n+\t\t range_not_collapsed(p + window, window))\n+\t\tsuccess(\"OK\");\n+\telse\n+\t\tfail(\"Fail\");\n+\n+\tvalidate_memory(p, 0, 2 * window - page_size);\n+\tops-\u003ecleanup_area(p, hpage_pmd_size);\n+\tthp_pop_settings();\n+\tksft_test_result_report(exit_status, \"%s\\n\", __func__);\n+}\n+\n+/* Smallest order khugepaged will consider for mTHP collapse. */\n+#define MIN_MTHP_ORDER 2\n+\n+/*\n+ * A region backed by large folios of a smaller order is a valid source\n+ * for collapse to the target order:\n+ * __collapse_huge_page_isolate() accepts any source folio of an order\n+ * strictly below the candidate's.\n+ */\n+static void collapse_order_mixed_sources(struct collapse_context *c,\n+\t\t\t\t\t struct mem_ops *ops)\n+{\n+\tstruct thp_settings settings = *thp_current_settings();\n+\tint source_order = anon_order ? anon_order : MIN_MTHP_ORDER;\n+\tvoid *p;\n+\n+\t/* Sources must be a supported mTHP order strictly below the target. */\n+\tif (source_order \u003e= anon_target_order ||\n+\t !(thp_supported_orders() \u0026 (1UL \u003c\u003c source_order))) {\n+\t\tksft_test_result_skip(\"%s: no source order below target\\n\",\n+\t\t\t\t __func__);\n+\t\treturn;\n+\t}\n+\n+\t/* Fault the whole region as order-@source_order folios. */\n+\tsettings.hugepages[source_order].enabled = THP_ALWAYS;\n+\tthp_push_settings(\u0026settings);\n+\tp = ops-\u003esetup_area(1);\n+\tops-\u003efault(p, 0, hpage_pmd_size);\n+\tthp_pop_settings();\n+\n+\tif (!is_range_backed_by_folio_orders(p, hpage_pmd_size, source_order,\n+\t\t\t\t\t pagemap_fd, kpageflags_fd))\n+\t\tksft_exit_fail_msg(\"Region not backed by order-%d folios after fault\\n\",\n+\t\t\t\t source_order);\n+\n+\tmadvise(p, hpage_pmd_size, MADV_HUGEPAGE);\n+\tksft_print_msg(\"Collapse region backed by order-%d sources...\",\n+\t\t source_order);\n+\tif (!khugepaged_wait_full_pass())\n+\t\tfail(\"Timeout\");\n+\telse if (range_collapsed(p, hpage_pmd_size))\n+\t\tsuccess(\"OK\");\n+\telse\n+\t\tfail(\"Fail\");\n+\n+\tvalidate_memory(p, 0, hpage_pmd_size);\n+\tops-\u003ecleanup_area(p, hpage_pmd_size);\n+\tksft_test_result_report(exit_status, \"%s\\n\", __func__);\n+}\n+\n static void usage(void)\n {\n \tfprintf(stderr, \"\\nUsage: ./khugepaged [OPTIONS] \u003ctest type\u003e [dir]\\n\\n\");\n@@ -1103,6 +1425,11 @@ static void usage(void)\n \tfprintf(stderr,\t\"\\t\\t-h: This help message.\\n\");\n \tfprintf(stderr,\t\"\\t\\t-s: mTHP size, expressed as page order.\\n\");\n \tfprintf(stderr,\t\"\\t\\t Defaults to 0. Use this size for anon or shmem allocations.\\n\");\n+\tfprintf(stderr,\t\"\\t\\t-o: collapse target order for khugepaged:anon.\\n\");\n+\tfprintf(stderr,\t\"\\t\\t Runs the order-parameterized collapse cases instead\\n\");\n+\tfprintf(stderr,\t\"\\t\\t of the PMD cases.\\n\");\n+\tfprintf(stderr,\t\"\\t\\t With -s, -s names the mTHP source order for the\\n\");\n+\tfprintf(stderr,\t\"\\t\\t mixed-source case (source order below the target).\\n\");\n \texit(1);\n }\n \n@@ -1112,17 +1439,31 @@ static void parse_test_type(int argc, char **argv)\n \tchar *buf;\n \tconst char *token;\n \n-\twhile ((opt = getopt(argc, argv, \"s:h\")) != -1) {\n+\twhile ((opt = getopt(argc, argv, \"s:o:h\")) != -1) {\n \t\tswitch (opt) {\n \t\tcase 's':\n \t\t\tanon_order = atoi(optarg);\n \t\t\tbreak;\n+\t\tcase 'o':\n+\t\t\tanon_target_order = atoi(optarg);\n+\t\t\tbreak;\n \t\tcase 'h':\n \t\tdefault:\n \t\t\tusage();\n \t\t}\n \t}\n \n+\t/*\n+\t * -s and -o compose: -s then names the mTHP source order for the\n+\t * mixed-source case, which needs a source strictly below the\n+\t * target (and at or above the smallest mTHP order). Alone, -s is\n+\t * the source order for the default PMD suite; alone, -o is the\n+\t * collapse target for the order-parameterized suite.\n+\t */\n+\tif (anon_target_order \u0026\u0026 anon_order \u0026\u0026\n+\t (anon_order \u003c MIN_MTHP_ORDER || anon_order \u003e= anon_target_order))\n+\t\tusage();\n+\n \targv += optind;\n \targc -= optind;\n \n@@ -1207,7 +1548,6 @@ static int nr_test_cases;\n \n int main(int argc, char **argv)\n {\n-\tint hpage_pmd_order;\n \tstruct thp_settings default_settings = {\n \t\t.thp_enabled = THP_MADVISE,\n \t\t.thp_defrag = THP_DEFRAG_ALWAYS,\n@@ -1244,18 +1584,94 @@ int main(int argc, char **argv)\n \thpage_pmd_nr = hpage_pmd_size / page_size;\n \thpage_pmd_order = __builtin_ctz(hpage_pmd_nr);\n \n+\t/*\n+\t * The page cache caps folio order at MAX_PAGECACHE_ORDER, which\n+\t * xas_split_alloc() puts below the PMD order on arm64 with 64K pages.\n+\t * A PMD-sized page cache folio is then impossible, so the kernel\n+\t * refuses these collapses by design and there is nothing to test.\n+\t */\n+\tif (!(thp_shmem_supported_orders() \u0026 (1UL \u003c\u003c hpage_pmd_order))) {\n+\t\tif (shmem_ops) {\n+\t\t\tksft_print_msg(\"no PMD-order page cache folio: skipping shmem\\n\");\n+\t\t\tshmem_ops = NULL;\n+\t\t}\n+\t\tif (finfo.type == VMA_SHMEM \u0026\u0026 read_only_file_ops) {\n+\t\t\tksft_print_msg(\"no PMD-order page cache folio: skipping tmpfs file\\n\");\n+\t\t\tread_only_file_ops = NULL;\n+\t\t\tread_write_file_read_ops = NULL;\n+\t\t\tread_write_file_write_ops = NULL;\n+\t\t}\n+\t\tif (!anon_ops \u0026\u0026 !shmem_ops \u0026\u0026 !read_only_file_ops)\n+\t\t\tksft_exit_skip(\"Nothing left to collapse into\\n\");\n+\t}\n+\n+\tif (anon_target_order \u0026\u0026\n+\t !(thp_supported_orders() \u0026 (1UL \u003c\u003c anon_target_order)))\n+\t\tksft_exit_skip(\"Order %d is not a supported anon THP order\\n\",\n+\t\t\t anon_target_order);\n+\tif (anon_target_order \u003e hpage_pmd_order)\n+\t\tksft_exit_fail_msg(\"-o takes at most the PMD order\\n\");\n+\n \tdefault_settings.khugepaged.max_ptes_none = hpage_pmd_nr - 1;\n \tdefault_settings.khugepaged.max_ptes_swap = hpage_pmd_nr / 8;\n \tdefault_settings.khugepaged.max_ptes_shared = hpage_pmd_nr / 2;\n \tdefault_settings.khugepaged.pages_to_scan = hpage_pmd_nr * 8;\n \tdefault_settings.hugepages[hpage_pmd_order].enabled = THP_INHERIT;\n-\tdefault_settings.hugepages[anon_order].enabled = THP_ALWAYS;\n \tdefault_settings.shmem_hugepages[hpage_pmd_order].enabled = SHMEM_INHERIT;\n-\tdefault_settings.shmem_hugepages[anon_order].enabled = SHMEM_ALWAYS;\n+\t/*\n+\t * Under -o the order-parameterized cases want order-0 sources by\n+\t * default; the mixed-source case enables its own (possibly -s\n+\t * selected) source order locally. Enabling it globally here would\n+\t * make every case fault that order.\n+\t */\n+\tif (!anon_target_order) {\n+\t\tdefault_settings.hugepages[anon_order].enabled = THP_ALWAYS;\n+\t\tdefault_settings.shmem_hugepages[anon_order].enabled = SHMEM_ALWAYS;\n+\t}\n+\n+\tif (anon_target_order) {\n+\t\t/*\n+\t\t * Only the target order may produce large folios, and only\n+\t\t * from khugepaged: \"inherit\" under enabled=madvise keeps\n+\t\t * pre-MADV_HUGEPAGE faults at order 0.\n+\t\t */\n+\t\tdefault_settings.hugepages[hpage_pmd_order].enabled = THP_NEVER;\n+\t\tdefault_settings.hugepages[anon_target_order].enabled = THP_INHERIT;\n+\t\t/*\n+\t\t * Order-parameterized cases are driven strictly by the\n+\t\t * khugepaged_full_pass() barrier, which wakes the daemon\n+\t\t * itself. A long scan_sleep keeps khugepaged from\n+\t\t * free-running between barrier steps, and a pages_to_scan\n+\t\t * covering everything makes one wake complete one full\n+\t\t * pass (the barrier's contract), so a run performs a\n+\t\t * deterministic number of passes — what the stage A/B\n+\t\t * trace comparisons rely on.\n+\t\t */\n+\t\tdefault_settings.khugepaged.scan_sleep_millisecs = 60000;\n+\t\tdefault_settings.khugepaged.pages_to_scan = 1UL \u003c\u003c 24;\n+\n+\t\tpagemap_fd = open(\"/proc/self/pagemap\", O_RDONLY);\n+\t\tif (pagemap_fd \u003c 0)\n+\t\t\tksft_exit_fail_perror(\"open(\\\"/proc/self/pagemap\\\")\");\n+\t\tkpageflags_fd = open(\"/proc/kpageflags\", O_RDONLY);\n+\t\tif (kpageflags_fd \u003c 0)\n+\t\t\tksft_exit_skip(\"open(\\\"/proc/kpageflags\\\") requires root\\n\");\n+\t}\n \n \tsave_settings();\n \tthp_push_settings(\u0026default_settings);\n \n+\tif (anon_target_order) {\n+\t\tTEST(collapse_order_full, khugepaged_context, anon_ops);\n+\t\tTEST(collapse_order_single_window, khugepaged_context, anon_ops);\n+\t\tTEST(collapse_order_partial_window, khugepaged_context, anon_ops);\n+\t\tTEST(collapse_order_max_ptes_none, khugepaged_context, anon_ops);\n+\t\tTEST(collapse_order_mixed_sources, khugepaged_context, anon_ops);\n+\n+\t\tksft_set_plan(nr_test_cases);\n+\t\tgoto run;\n+\t}\n+\n \tTEST(collapse_full, khugepaged_context, anon_ops);\n \tTEST(collapse_full, khugepaged_context, read_only_file_ops);\n \tTEST(collapse_full, khugepaged_context, read_write_file_read_ops);\n@@ -1324,6 +1740,9 @@ int main(int argc, char **argv)\n \tTEST(collapse_max_ptes_shared, khugepaged_context, anon_ops);\n \tTEST(collapse_max_ptes_shared, madvise_context, anon_ops);\n \n+\tTEST(collapse_fork_cow_race, khugepaged_context, anon_ops);\n+\tTEST(collapse_fork_cow_race, madvise_context, anon_ops);\n+\n \tTEST(madvise_collapse_existing_thps, madvise_context, anon_ops);\n \tTEST(madvise_collapse_existing_thps, madvise_context, read_only_file_ops);\n \tTEST(madvise_collapse_existing_thps, madvise_context, read_write_file_read_ops);\n@@ -1336,6 +1755,7 @@ int main(int argc, char **argv)\n \tksft_set_plan(nr_test_cases + 1);\n \n \talloc_at_fault();\n+run:\n \tfor (int i = 0; i \u003c nr_test_cases; i++) {\n \t\tstruct test_case *t = \u0026test_cases[i];\n \ndiff --git a/tools/testing/selftests/mm/khugepaged_race.c b/tools/testing/selftests/mm/khugepaged_race.c\nnew file mode 100644\nindex 0000000000000..2aa45c9e8a77f\n--- /dev/null\n+++ b/tools/testing/selftests/mm/khugepaged_race.c\n@@ -0,0 +1,483 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * khugepaged race harness.\n+ *\n+ * Runs collapse against concurrent faults, transient GUP pins\n+ * (gup_test), fork, mremap and MADV_DONTNEED over the same ranges, in\n+ * one of three driver modes:\n+ *\n+ * stepped\tkhugepaged, driven synchronously one full pass at a time\n+ *\t\tthrough khugepaged_full_pass() — the primary driver: the\n+ *\t\tfull scan+collapse path with a deterministic extent per\n+ *\t\tstep;\n+ * free\tfree-running khugepaged (scan_sleep_millisecs=0) — the\n+ *\t\tsoak;\n+ * madvise\tMADV_COLLAPSE in a loop — the legacy-PMD regression\n+ *\t\taxis.\n+ *\n+ * All anon THP orders are enabled (inherit). max_ptes_none is 0 by\n+ * default — racing MADV_DONTNEED then steers selection across orders —\n+ * or the permissive limit with -z, which floods the batch engine with\n+ * hole and zeropage slots so the population paths (park-time zeropage\n+ * clear, zero-filled copy, install-time pte_none() verify and abort)\n+ * race the faulters directly.\n+ *\n+ * -p adds memory pressure to any of the above: MADV_PAGEOUT cycling\n+ * on a dedicated neighbor region (swap traffic and LRU churn; skipped\n+ * with a note when the host has no swap) and a compact_memory trigger\n+ * loop (compaction migrates source folios, racing collapse's freeze\n+ * with refcount elevation and migration entries of its own).\n+ *\n+ * Correctness signals: every racing page must read as its pattern or\n+ * zero (MADV_DONTNEED), never anything else — checked continuously by\n+ * the faulters and the fork children and once at the end — plus\n+ * whatever DEBUG_VM / page_table_check / KASAN / lockdep report in\n+ * dmesg, which the caller is expected to inspect.\n+ */\n+#define _GNU_SOURCE\n+#include \u003cerrno.h\u003e\n+#include \u003cfcntl.h\u003e\n+#include \u003cpthread.h\u003e\n+#include \u003cstdio.h\u003e\n+#include \u003cstdlib.h\u003e\n+#include \u003cstring.h\u003e\n+#include \u003csys/ioctl.h\u003e\n+#include \u003csys/mman.h\u003e\n+#include \u003csys/time.h\u003e\n+#include \u003csys/wait.h\u003e\n+#include \u003cunistd.h\u003e\n+\n+#include \"kselftest.h\"\n+#include \"vm_util.h\"\n+#include \"hugepage_settings.h\"\n+#include \"../../../../mm/gup_test.h\"\n+\n+#define BASE_ADDR\t((void *)(1UL \u003c\u003c 30))\n+/*\n+ * Shared playground for faults/pins/fork/dontneed: several PMD-sized\n+ * areas the racing threads spread across, plus one area owned by the\n+ * mremap thread. More areas means more independent regions collapsing\n+ * at once; the default suits a normal machine. On a memory-constrained\n+ * host -- or under emulation, where a 512M PMD (arm64/64K) makes the\n+ * default playground multi-gigabyte -- pass -a to shrink it.\n+ */\n+#define DEFAULT_SHARED_AREAS\t3\n+static int nr_shared_areas;\n+static int nr_areas;\n+\n+static unsigned long hpage_pmd_size;\n+static unsigned long page_size;\n+static char *region;\t\t/* NR_AREAS * hpage_pmd_size */\n+static char *mremap_area;\t/* region + NR_SHARED_AREAS areas */\n+static char *mremap_scratch;\t/* well above the region */\n+static char *pageout_area;\t/* -p: dedicated pressure region */\n+static size_t pageout_size;\n+static int gup_fd = -1;\n+static volatile int stop;\n+static volatile int corrupted;\n+\n+static unsigned int pattern(unsigned long page_idx)\n+{\n+\tunsigned int val = (unsigned int)page_idx * 2654435761U;\n+\n+\treturn val ? val : 1;\t/* never collides with the zero-fill */\n+}\n+\n+static void check_page(unsigned long page_idx)\n+{\n+\tunsigned int val = *(unsigned int *)(region + page_idx * page_size);\n+\n+\tif (val \u0026\u0026 val != pattern(page_idx)) {\n+\t\tcorrupted = 1;\n+\t\tksft_print_msg(\"Corruption at page %lu: %#x != %#x\\n\",\n+\t\t\t page_idx, val, pattern(page_idx));\n+\t}\n+}\n+\n+static unsigned long rand_page(unsigned int *seed)\n+{\n+\treturn (unsigned long)rand_r(seed) %\n+\t (nr_shared_areas * hpage_pmd_size / page_size);\n+}\n+\n+static void *faulter_fn(void *arg)\n+{\n+\tunsigned int seed = (unsigned long)arg;\n+\n+\twhile (!stop) {\n+\t\tunsigned long page_idx = rand_page(\u0026seed);\n+\n+\t\tif (rand_r(\u0026seed) \u0026 1)\n+\t\t\t*(unsigned int *)(region + page_idx * page_size) =\n+\t\t\t\tpattern(page_idx);\n+\t\telse\n+\t\t\tcheck_page(page_idx);\n+\t}\n+\treturn NULL;\n+}\n+\n+static void *dontneed_fn(void *arg)\n+{\n+\tunsigned int seed = (unsigned long)arg;\n+\n+\twhile (!stop) {\n+\t\tunsigned long page_idx = rand_page(\u0026seed);\n+\t\tunsigned long nr = 1UL \u003c\u003c (rand_r(\u0026seed) % 6);\t/* 1..32 pages */\n+\n+\t\t/*\n+\t\t * Once in a while zap a whole PMD-aligned area: only a\n+\t\t * zap spanning the full table triggers the empty-table\n+\t\t * reclaim (CONFIG_PT_RECLAIM), which can free a table\n+\t\t * out from under a parked collapse — sub-table zaps\n+\t\t * never reach that path.\n+\t\t */\n+\t\tif (!(rand_r(\u0026seed) % 64)) {\n+\t\t\tunsigned long area = page_idx /\n+\t\t\t\t\t(hpage_pmd_size / page_size);\n+\n+\t\t\tmadvise(region + area * hpage_pmd_size,\n+\t\t\t\thpage_pmd_size, MADV_DONTNEED);\n+\t\t} else {\n+\t\t\tmadvise(region + page_idx * page_size,\n+\t\t\t\tnr * page_size, MADV_DONTNEED);\n+\t\t}\n+\t\tusleep(rand_r(\u0026seed) % 500);\n+\t}\n+\treturn NULL;\n+}\n+\n+static void *pinner_fn(void *arg)\n+{\n+\tunsigned int seed = (unsigned long)arg;\n+\n+\twhile (!stop) {\n+\t\tstruct gup_test gup = {};\n+\t\tunsigned long page_idx = rand_page(\u0026seed);\n+\n+\t\tgup.addr = (unsigned long)(region + page_idx * page_size);\n+\t\tgup.size = 16 * page_size;\n+\t\tgup.nr_pages_per_call = 16;\n+\t\tgup.gup_flags = 1;\t/* FOLL_WRITE */\n+\t\t/* Racing MADV_DONTNEED makes transient failures expected. */\n+\t\tioctl(gup_fd, PIN_FAST_BENCHMARK, \u0026gup);\n+\t\tusleep(rand_r(\u0026seed) % 200);\n+\t}\n+\treturn NULL;\n+}\n+\n+static void *forker_fn(void *arg)\n+{\n+\tunsigned int seed = (unsigned long)arg;\n+\n+\twhile (!stop) {\n+\t\tpid_t pid = fork();\n+\n+\t\tif (pid == 0) {\n+\t\t\tfor (int i = 0; i \u003c 16; i++)\n+\t\t\t\tcheck_page(rand_page(\u0026seed));\n+\t\t\t_exit(corrupted);\n+\t\t}\n+\t\tif (pid \u003e 0) {\n+\t\t\tint wstatus;\n+\n+\t\t\twaitpid(pid, \u0026wstatus, 0);\n+\t\t\tif (WIFEXITED(wstatus) \u0026\u0026 WEXITSTATUS(wstatus))\n+\t\t\t\tcorrupted = 1;\n+\t\t}\n+\t\tusleep(rand_r(\u0026seed) % 2000);\n+\t}\n+\treturn NULL;\n+}\n+\n+static void *mremapper_fn(void *arg)\n+{\n+\tunsigned int seed = (unsigned long)arg;\n+\n+\twhile (!stop) {\n+\t\tvoid *p;\n+\n+\t\tp = mremap(mremap_area, hpage_pmd_size, hpage_pmd_size,\n+\t\t\t MREMAP_MAYMOVE | MREMAP_FIXED, mremap_scratch);\n+\t\tif (p == MAP_FAILED)\n+\t\t\tksft_exit_fail_perror(\"mremap() away\");\n+\t\tfor (int i = 0; i \u003c 8; i++)\n+\t\t\tmremap_scratch[(rand_r(\u0026seed) %\n+\t\t\t\t(hpage_pmd_size / page_size)) * page_size] = 1;\n+\t\tp = mremap(mremap_scratch, hpage_pmd_size, hpage_pmd_size,\n+\t\t\t MREMAP_MAYMOVE | MREMAP_FIXED, mremap_area);\n+\t\tif (p == MAP_FAILED)\n+\t\t\tksft_exit_fail_perror(\"mremap() back\");\n+\t\tusleep(rand_r(\u0026seed) % 2000);\n+\t}\n+\treturn NULL;\n+}\n+\n+/*\n+ * -p: swap traffic and LRU churn on a region of our own. The content\n+ * check is exact — a page out and back through swap must preserve the\n+ * pattern, and nothing else ever writes here.\n+ */\n+static void *pageout_fn(void *arg)\n+{\n+\tunsigned int seed = (unsigned long)arg;\n+\tunsigned long nr = pageout_size / page_size;\n+\tunsigned long i;\n+\n+\tfor (i = 0; i \u003c nr; i++)\n+\t\t*(unsigned int *)(pageout_area + i * page_size) = pattern(i);\n+\n+\twhile (!stop) {\n+\t\tmadvise(pageout_area, pageout_size, MADV_PAGEOUT);\n+\t\tfor (i = 0; i \u003c nr \u0026\u0026 !stop; i++) {\n+\t\t\tunsigned int val = *(unsigned int *)(pageout_area +\n+\t\t\t\t\t\t\t i * page_size);\n+\n+\t\t\tif (val != pattern(i)) {\n+\t\t\t\tcorrupted = 1;\n+\t\t\t\tksft_print_msg(\"Pageout corruption at page %lu: %#x != %#x\\n\",\n+\t\t\t\t\t i, val, pattern(i));\n+\t\t\t}\n+\t\t}\n+\t\tusleep(rand_r(\u0026seed) % 2000);\n+\t}\n+\treturn NULL;\n+}\n+\n+/* -p: compaction migrates the collapse sources out from under us. */\n+static void *compactor_fn(void *arg)\n+{\n+\tunsigned int seed = (unsigned long)arg;\n+\tint fd = open(\"/proc/sys/vm/compact_memory\", O_WRONLY);\n+\n+\tif (fd \u003c 0) {\n+\t\tksft_print_msg(\"No compact_memory; compactor idle\\n\");\n+\t\treturn NULL;\n+\t}\n+\twhile (!stop) {\n+\t\tif (write(fd, \"1\", 1) \u003c 0)\n+\t\t\tbreak;\n+\t\tusleep(10000 + rand_r(\u0026seed) % 100000);\n+\t}\n+\tclose(fd);\n+\treturn NULL;\n+}\n+\n+static bool swap_available(void)\n+{\n+\tchar line[256];\n+\tint lines = 0;\n+\tFILE *fp = fopen(\"/proc/swaps\", \"r\");\n+\n+\tif (!fp)\n+\t\treturn false;\n+\twhile (fgets(line, sizeof(line), fp))\n+\t\tlines++;\n+\tfclose(fp);\n+\treturn lines \u003e 1;\n+}\n+\n+static unsigned long now_ms(void)\n+{\n+\tstruct timeval tv;\n+\n+\tgettimeofday(\u0026tv, NULL);\n+\treturn tv.tv_sec * 1000UL + tv.tv_usec / 1000;\n+}\n+\n+static void usage(void)\n+{\n+\tfprintf(stderr,\n+\t\t\"Usage: khugepaged_race [-d seconds] [-m stepped|free|madvise] [-z] [-p] [-a areas]\\n\"\n+\t\t\"\\t-z: permissive max_ptes_none (hole-heavy windows)\\n\"\n+\t\t\"\\t-p: memory pressure (pageout + compaction) threads\\n\"\n+\t\t\"\\t-a: number of shared PMD-sized playground areas (default 3)\\n\");\n+\texit(1);\n+}\n+\n+int main(int argc, char **argv)\n+{\n+\tstatic const char * const thread_names[] = {\n+\t\t\"faulter\", \"faulter2\", \"dontneed\", \"pinner\", \"forker\",\n+\t\t\"mremapper\", \"pageout\", \"compactor\",\n+\t};\n+\tvoid *(*const thread_fns[])(void *) = {\n+\t\tfaulter_fn, faulter_fn, dontneed_fn, pinner_fn, forker_fn,\n+\t\tmremapper_fn, pageout_fn, compactor_fn,\n+\t};\n+\tconst unsigned long pageout_bit = 1UL \u003c\u003c 6, compactor_bit = 1UL \u003c\u003c 7;\n+\tconst int nr_threads = ARRAY_SIZE(thread_names);\n+\tpthread_t threads[ARRAY_SIZE(thread_names)];\n+\tconst char *mode = \"stepped\";\n+\tstruct thp_settings settings;\n+\tunsigned long end_ms;\n+\tint duration_s = 10;\n+\tunsigned long thread_mask = ~0UL;\n+\tint nr_areas_arg = 0;\n+\tbool permissive_none = false;\n+\tbool pressure = false;\n+\tunsigned long i;\n+\tint steps = 0;\n+\tint opt;\n+\n+\twhile ((opt = getopt(argc, argv, \"a:d:m:t:zph\")) != -1) {\n+\t\tswitch (opt) {\n+\t\tcase 'a':\n+\t\t\tnr_areas_arg = atoi(optarg);\n+\t\t\tbreak;\n+\t\tcase 'd':\n+\t\t\tduration_s = atoi(optarg);\n+\t\t\tbreak;\n+\t\tcase 'm':\n+\t\t\tmode = optarg;\n+\t\t\tbreak;\n+\t\tcase 't':\n+\t\t\t/* debug: bitmask of racing threads to start */\n+\t\t\tthread_mask = strtoul(optarg, NULL, 0);\n+\t\t\tbreak;\n+\t\tcase 'z':\n+\t\t\tpermissive_none = true;\n+\t\t\tbreak;\n+\t\tcase 'p':\n+\t\t\tpressure = true;\n+\t\t\tbreak;\n+\t\tdefault:\n+\t\t\tusage();\n+\t\t}\n+\t}\n+\tif (strcmp(mode, \"stepped\") \u0026\u0026 strcmp(mode, \"free\") \u0026\u0026\n+\t strcmp(mode, \"madvise\"))\n+\t\tusage();\n+\n+\tksft_print_header();\n+\tif (!thp_available())\n+\t\tksft_exit_skip(\"Transparent Hugepages not available\\n\");\n+\n+\tpage_size = getpagesize();\n+\thpage_pmd_size = read_pmd_pagesize();\n+\tif (!hpage_pmd_size)\n+\t\tksft_exit_fail_msg(\"Reading PMD pagesize failed\\n\");\n+\n+\tgup_fd = open(\"/sys/kernel/debug/gup_test\", O_RDWR);\n+\tif (gup_fd \u003c 0)\n+\t\tksft_exit_skip(\"/sys/kernel/debug/gup_test requires CONFIG_GUP_TEST and root\\n\");\n+\n+\tnr_shared_areas = nr_areas_arg \u003e 0 ? nr_areas_arg : DEFAULT_SHARED_AREAS;\n+\tnr_areas = nr_shared_areas + 1;\n+\n+\tif (!pressure) {\n+\t\tthread_mask \u0026= ~(pageout_bit | compactor_bit);\n+\t} else if (!swap_available()) {\n+\t\t/* No swap, no anon reclaim: compaction-only pressure. */\n+\t\tksft_print_msg(\"-p without swap: pageout thread disabled\\n\");\n+\t\tthread_mask \u0026= ~pageout_bit;\n+\t}\n+\n+\tksft_set_plan(1);\n+\n+\tthp_save_settings();\n+\tthp_read_settings(\u0026settings);\n+\tsettings.thp_enabled = THP_MADVISE;\n+\tsettings.thp_defrag = THP_DEFRAG_ALWAYS;\n+\tsettings.shmem_enabled = SHMEM_NEVER;\n+\tsettings.khugepaged.defrag = 1;\n+\tsettings.khugepaged.scan_sleep_millisecs =\n+\t\tstrcmp(mode, \"free\") ? 1000 : 0;\n+\tsettings.khugepaged.alloc_sleep_millisecs = 10;\n+\t/*\n+\t * mTHP collapse only supports the two ends of the occupancy\n+\t * scale: 0 or HPAGE_PMD_NR - 1 (anything else coerces to 0).\n+\t * Strict is the default — it also keeps khugepaged from burning\n+\t * the whole step in doomed PMD-sized allocations on 512M-PMD\n+\t * configs, where a fully populated area is rare under racing\n+\t * MADV_DONTNEED. -z selects the permissive end: selection then\n+\t * emits hole-heavy windows and the engine's population paths\n+\t * take the brunt of the racing faults and zaps.\n+\t */\n+\tsettings.khugepaged.max_ptes_none = permissive_none ?\n+\t\t(hpage_pmd_size / page_size) - 1 : 0;\n+\tsettings.khugepaged.pages_to_scan =\n+\t\tnr_areas * (hpage_pmd_size / page_size) * 8;\n+\tfor (i = 0; i \u003c NR_ORDERS; i++) {\n+\t\tif (thp_supported_orders() \u0026 (1UL \u003c\u003c i))\n+\t\t\tsettings.hugepages[i].enabled = THP_INHERIT;\n+\t}\n+\t/* Base of the settings stack; the bottom entry is never popped. */\n+\tthp_push_settings(\u0026settings);\n+\n+\tregion = mmap(BASE_ADDR, nr_areas * hpage_pmd_size,\n+\t\t PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE,\n+\t\t -1, 0);\n+\tif (region != BASE_ADDR)\n+\t\tksft_exit_fail_msg(\"Failed to allocate VMA at %p\\n\", BASE_ADDR);\n+\tmremap_area = region + nr_shared_areas * hpage_pmd_size;\n+\tmremap_scratch = (char *)BASE_ADDR + 2 * nr_areas * hpage_pmd_size;\n+\n+\tif (thread_mask \u0026 pageout_bit) {\n+\t\t/*\n+\t\t * Big enough to cycle real reclaim, small enough not to\n+\t\t * dominate a TCG guest: 4 PMD areas, clamped to [16M, 64M].\n+\t\t */\n+\t\tpageout_size = 4 * hpage_pmd_size;\n+\t\tpageout_size = pageout_size \u003c (16UL \u003c\u003c 20) ? (16UL \u003c\u003c 20) :\n+\t\t\t pageout_size \u003e (64UL \u003c\u003c 20) ? (64UL \u003c\u003c 20) :\n+\t\t\t pageout_size;\n+\t\tpageout_area = mmap(NULL, pageout_size, PROT_READ | PROT_WRITE,\n+\t\t\t\t MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);\n+\t\tif (pageout_area == MAP_FAILED)\n+\t\t\tksft_exit_fail_perror(\"mmap() pageout area\");\n+\t}\n+\n+\t/* Populate so the first pass has something to collapse. */\n+\tfor (i = 0; i \u003c nr_shared_areas * hpage_pmd_size / page_size; i++)\n+\t\t*(unsigned int *)(region + i * page_size) = pattern(i);\n+\tmemset(mremap_area, 1, hpage_pmd_size);\n+\tmadvise(region, nr_areas * hpage_pmd_size, MADV_HUGEPAGE);\n+\n+\tfor (i = 0; i \u003c nr_threads; i++) {\n+\t\tif (!(thread_mask \u0026 (1UL \u003c\u003c i))) {\n+\t\t\tthreads[i] = 0;\n+\t\t\tcontinue;\n+\t\t}\n+\t\tif (pthread_create(\u0026threads[i], NULL, thread_fns[i],\n+\t\t\t\t (void *)(i + 1)))\n+\t\t\tksft_exit_fail_perror(\"pthread_create()\");\n+\t}\n+\n+\tend_ms = now_ms() + duration_s * 1000UL;\n+\tif (!strcmp(mode, \"stepped\")) {\n+\t\twhile (now_ms() \u003c end_ms \u0026\u0026 !corrupted) {\n+\t\t\tif (!khugepaged_full_pass(600))\n+\t\t\t\tksft_exit_fail_msg(\"khugepaged pass timed out\\n\");\n+\t\t\tsteps++;\n+\t\t}\n+\t} else if (!strcmp(mode, \"free\")) {\n+\t\twhile (now_ms() \u003c end_ms \u0026\u0026 !corrupted)\n+\t\t\tusleep(100 * 1000);\n+\t} else {\t/* madvise */\n+\t\twhile (now_ms() \u003c end_ms \u0026\u0026 !corrupted) {\n+\t\t\tfor (i = 0; i \u003c nr_shared_areas; i++) {\n+\t\t\t\tmadvise(region + i * hpage_pmd_size,\n+\t\t\t\t\thpage_pmd_size, MADV_COLLAPSE);\n+\t\t\t}\n+\t\t\tmadvise(region, nr_shared_areas * hpage_pmd_size,\n+\t\t\t\tMADV_DONTNEED);\n+\t\t\tsteps++;\n+\t\t}\n+\t}\n+\n+\tstop = 1;\n+\tfor (i = 0; i \u003c nr_threads; i++) {\n+\t\tif (threads[i])\n+\t\t\tpthread_join(threads[i], NULL);\n+\t}\n+\n+\t/* Final integrity sweep. */\n+\tfor (i = 0; i \u003c nr_shared_areas * hpage_pmd_size / page_size; i++)\n+\t\tcheck_page(i);\n+\n+\tthp_restore_settings();\n+\n+\tksft_test_result(!corrupted, \"%s: %ds, %d steps, no corruption\\n\",\n+\t\t\t mode, duration_s, steps);\n+\tksft_finished();\n+}\ndiff --git a/tools/testing/selftests/mm/khugepaged_sync_check.c b/tools/testing/selftests/mm/khugepaged_sync_check.c\nnew file mode 100644\nindex 0000000000000..13215cb370ceb\n--- /dev/null\n+++ b/tools/testing/selftests/mm/khugepaged_sync_check.c\n@@ -0,0 +1,198 @@\n+// SPDX-License-Identifier: GPL-2.0\n+/*\n+ * Synchronous khugepaged driving check.\n+ *\n+ * Race tests drive khugepaged through the existing sysfs controls: a\n+ * store to scan_sleep_millisecs wakes the daemon, and full_scans\n+ * advancing by two is a completion barrier for one full pass that\n+ * started after setup (khugepaged_full_pass()). Verify the pair gives\n+ * deterministic, attributable results: one barrier step over one\n+ * prepared window produces exactly one collapse attempt on that\n+ * window's source pages — mm_collapse_huge_page_isolate events\n+ * filtered by source PFN and order — and the window is collapsed\n+ * afterwards, repeatably.\n+ *\n+ * scan_sleep_millisecs is set to 60s to prove the wake path: without\n+ * the wake, one barrier step would sleep multiples of that and blow\n+ * the timeout. It also keeps the daemon from free-running between\n+ * steps, per the khugepaged_full_pass() discipline.\n+ */\n+#define _GNU_SOURCE\n+#include \u003cfcntl.h\u003e\n+#include \u003cstdio.h\u003e\n+#include \u003cstdlib.h\u003e\n+#include \u003cstring.h\u003e\n+#include \u003csys/mman.h\u003e\n+#include \u003cunistd.h\u003e\n+\n+#include \"kselftest.h\"\n+#include \"vm_util.h\"\n+#include \"hugepage_settings.h\"\n+\n+#define BASE_ADDR ((void *)(1UL \u003c\u003c 30))\n+#define TARGET_ORDER 2\t/* smallest order khugepaged considers */\n+#define NR_ITERATIONS 5\n+\n+static int pagemap_fd;\n+static int kpageflags_fd;\n+static unsigned long hpage_pmd_size;\n+\n+/*\n+ * Count collapse attempts attributable to our window: legacy-engine\n+ * isolate events whose scan_pfn is one of the window's source PFNs,\n+ * plus batch-engine per-candidate install events at the window's\n+ * address. Either engine reports exactly once per attempt.\n+ */\n+static int count_attributed(unsigned long *pfns, int nr_pfns,\n+\t\t\t unsigned long addr, unsigned int order)\n+{\n+\tchar line[1024];\n+\tint count = 0;\n+\tFILE *fp;\n+\n+\tfp = tracing_open_trace();\n+\tif (!fp)\n+\t\tksft_exit_fail_msg(\"Cannot open trace buffer\\n\");\n+\n+\twhile (fgets(line, sizeof(line), fp)) {\n+\t\tchar *s;\n+\t\tunsigned long val;\n+\t\tunsigned int ord;\n+\t\tchar *o;\n+\t\tint i;\n+\n+\t\ts = strstr(line, \"mm_collapse_huge_page_isolate:\");\n+\t\tif (s) {\n+\t\t\tif (sscanf(s, \"mm_collapse_huge_page_isolate: scan_pfn=0x%lx\",\n+\t\t\t\t \u0026val) != 1)\n+\t\t\t\tcontinue;\n+\t\t\to = strstr(s, \"order=\");\n+\t\t\tif (!o || sscanf(o, \"order=%u\", \u0026ord) != 1 ||\n+\t\t\t ord != order)\n+\t\t\t\tcontinue;\n+\t\t\tfor (i = 0; i \u003c nr_pfns; i++) {\n+\t\t\t\tif (val == pfns[i]) {\n+\t\t\t\t\tcount++;\n+\t\t\t\t\tbreak;\n+\t\t\t\t}\n+\t\t\t}\n+\t\t\tcontinue;\n+\t\t}\n+\n+\t\ts = strstr(line, \"mm_collapse_candidate:\");\n+\t\tif (s) {\n+\t\t\tif (!strstr(s, \"pass=install\") ||\n+\t\t\t !strstr(s, \"result=succeeded\"))\n+\t\t\t\tcontinue;\n+\t\t\to = strstr(s, \"addr=\");\n+\t\t\tif (!o || sscanf(o, \"addr=0x%lx\", \u0026val) != 1 ||\n+\t\t\t val != addr)\n+\t\t\t\tcontinue;\n+\t\t\to = strstr(s, \"order=\");\n+\t\t\tif (!o || sscanf(o, \"order=%u\", \u0026ord) != 1 ||\n+\t\t\t ord != order)\n+\t\t\t\tcontinue;\n+\t\t\tcount++;\n+\t\t}\n+\t}\n+\tfclose(fp);\n+\treturn count;\n+}\n+\n+static void one_step(int iteration)\n+{\n+\tconst size_t window = getpagesize() \u003c\u003c TARGET_ORDER;\n+\tconst int nr_pages = 1 \u003c\u003c TARGET_ORDER;\n+\tunsigned long pfns[1 \u003c\u003c TARGET_ORDER];\n+\tbool collapsed;\n+\tint attributed;\n+\tchar *p;\n+\tint i;\n+\n+\tp = mmap(BASE_ADDR, hpage_pmd_size, PROT_READ | PROT_WRITE,\n+\t\t MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);\n+\tif (p != BASE_ADDR)\n+\t\tksft_exit_fail_msg(\"Failed to allocate VMA at %p\\n\",\n+\t\t\t\t BASE_ADDR);\n+\n+\t/* Prepare one window; record its source PFNs. */\n+\tfor (i = 0; i \u003c nr_pages; i++) {\n+\t\tp[i * getpagesize()] = i + 1;\n+\t\tpfns[i] = pagemap_get_pfn(pagemap_fd, p + i * getpagesize());\n+\t\tif (pfns[i] == -1UL)\n+\t\t\tksft_exit_fail_msg(\"Source page not present\\n\");\n+\t}\n+\n+\tif (tracing_events_start(\"huge_memory\"))\n+\t\tksft_exit_fail_msg(\"Cannot enable huge_memory events\\n\");\n+\n+\tmadvise(p, hpage_pmd_size, MADV_HUGEPAGE);\n+\t/* Wait up to 120 seconds for the pass to complete. */\n+\tif (!khugepaged_full_pass(120))\n+\t\tksft_exit_fail_msg(\"khugepaged did not complete a full pass\\n\");\n+\n+\ttracing_events_stop(\"huge_memory\");\n+\n+\tcollapsed = is_range_backed_by_folio_orders(p, window, TARGET_ORDER,\n+\t\t\t\t\t\t pagemap_fd, kpageflags_fd);\n+\tattributed = count_attributed(pfns, nr_pages, (unsigned long)p,\n+\t\t\t\t TARGET_ORDER);\n+\n+\tksft_test_result(collapsed \u0026\u0026 attributed == 1,\n+\t\t\t \"step %d: window collapsed, %d attributed result(s)\\n\",\n+\t\t\t iteration, attributed);\n+\n+\tmunmap(p, hpage_pmd_size);\n+}\n+\n+int main(void)\n+{\n+\tstruct thp_settings settings;\n+\tint i;\n+\n+\tksft_print_header();\n+\n+\tif (!thp_available())\n+\t\tksft_exit_skip(\"Transparent Hugepages not available\\n\");\n+\tif (!(thp_supported_orders() \u0026 (1UL \u003c\u003c TARGET_ORDER)))\n+\t\tksft_exit_skip(\"Order %d is not a supported anon THP order\\n\",\n+\t\t\t TARGET_ORDER);\n+\n+\thpage_pmd_size = read_pmd_pagesize();\n+\tif (!hpage_pmd_size)\n+\t\tksft_exit_fail_msg(\"Reading PMD pagesize failed\\n\");\n+\tpagemap_fd = open(\"/proc/self/pagemap\", O_RDONLY);\n+\tif (pagemap_fd \u003c 0)\n+\t\tksft_exit_fail_perror(\"open(\\\"/proc/self/pagemap\\\")\");\n+\tkpageflags_fd = open(\"/proc/kpageflags\", O_RDONLY);\n+\tif (kpageflags_fd \u003c 0)\n+\t\tksft_exit_skip(\"open(\\\"/proc/kpageflags\\\") requires root\\n\");\n+\tif (tracing_events_start(\"huge_memory\"))\n+\t\tksft_exit_skip(\"tracefs unavailable\\n\");\n+\ttracing_events_stop(\"huge_memory\");\n+\n+\tksft_set_plan(NR_ITERATIONS);\n+\n+\tthp_save_settings();\n+\tthp_read_settings(\u0026settings);\n+\tsettings.thp_enabled = THP_MADVISE;\n+\tsettings.thp_defrag = THP_DEFRAG_ALWAYS;\n+\tsettings.khugepaged.defrag = 1;\n+\tsettings.khugepaged.scan_sleep_millisecs = 60000;\n+\tsettings.khugepaged.alloc_sleep_millisecs = 60000;\n+\tsettings.khugepaged.max_ptes_none = (hpage_pmd_size / getpagesize()) - 1;\n+\t/* One wake must complete one full pass; see khugepaged_full_pass(). */\n+\tsettings.khugepaged.pages_to_scan = 1UL \u003c\u003c 24;\n+\tfor (i = 0; i \u003c NR_ORDERS; i++)\n+\t\tsettings.hugepages[i].enabled = THP_NEVER;\n+\tsettings.hugepages[TARGET_ORDER].enabled = THP_INHERIT;\n+\t/* Base of the settings stack; the bottom entry is never popped. */\n+\tthp_push_settings(\u0026settings);\n+\n+\tfor (i = 0; i \u003c NR_ITERATIONS; i++)\n+\t\tone_step(i);\n+\n+\tthp_restore_settings();\n+\n+\tksft_finished();\n+}\ndiff --git a/tools/testing/selftests/mm/run_vmtests.sh b/tools/testing/selftests/mm/run_vmtests.sh\nindex 687d115e3bd80..f826cf940c3d4 100755\n--- a/tools/testing/selftests/mm/run_vmtests.sh\n+++ b/tools/testing/selftests/mm/run_vmtests.sh\n@@ -402,10 +402,27 @@ CATEGORY=\"pfnmap\" run_test ./pfnmap\n # COW tests\n CATEGORY=\"cow\" run_test ./cow\n \n+CATEGORY=\"thp\" run_test ./folio_order_check\n+\n+\n+CATEGORY=\"thp\" run_test ./khugepaged_sync_check\n+\n+CATEGORY=\"thp\" run_test ./khugepaged_race -d 5 -m stepped\n+\n+CATEGORY=\"thp\" run_test ./khugepaged_race -d 5 -m free\n+\n+CATEGORY=\"thp\" run_test ./khugepaged_race -d 5 -m madvise\n+\n+CATEGORY=\"thp\" run_test ./khugepaged_race -d 5 -m stepped -z\n+\n+CATEGORY=\"thp\" run_test ./khugepaged_race -d 5 -m stepped -p\n+\n CATEGORY=\"thp\" run_test ./khugepaged\n \n CATEGORY=\"thp\" run_test ./khugepaged -s 2\n \n+CATEGORY=\"thp\" run_test ./khugepaged -o 2 khugepaged:anon\n+\n CATEGORY=\"thp\" run_test ./khugepaged all:shmem\n \n CATEGORY=\"thp\" run_test ./khugepaged -s 4 all:shmem\ndiff --git a/tools/testing/selftests/mm/split_huge_page_test.c b/tools/testing/selftests/mm/split_huge_page_test.c\nindex 32b991472f744..9b3885bd001be 100644\n--- a/tools/testing/selftests/mm/split_huge_page_test.c\n+++ b/tools/testing/selftests/mm/split_huge_page_test.c\n@@ -42,68 +42,6 @@ const char *kpageflags_proc = \"/proc/kpageflags\";\n int pagemap_fd;\n int kpageflags_fd;\n \n-static bool is_backed_by_folio(char *vaddr, int order, int pagemap_fd,\n-\t\tint kpageflags_fd)\n-{\n-\tconst uint64_t folio_head_flags = KPF_THP | KPF_COMPOUND_HEAD;\n-\tconst uint64_t folio_tail_flags = KPF_THP | KPF_COMPOUND_TAIL;\n-\tconst unsigned long nr_pages = 1UL \u003c\u003c order;\n-\tunsigned long pfn_head;\n-\tuint64_t pfn_flags;\n-\tunsigned long pfn;\n-\tunsigned long i;\n-\n-\tpfn = pagemap_get_pfn(pagemap_fd, vaddr);\n-\n-\t/* non present page */\n-\tif (pfn == -1UL)\n-\t\treturn false;\n-\n-\tif (pageflags_get(pfn, kpageflags_fd, \u0026pfn_flags))\n-\t\tgoto fail;\n-\n-\t/* check for order-0 pages */\n-\tif (!order) {\n-\t\tif (pfn_flags \u0026 (folio_head_flags | folio_tail_flags))\n-\t\t\treturn false;\n-\t\treturn true;\n-\t}\n-\n-\t/* non THP folio */\n-\tif (!(pfn_flags \u0026 KPF_THP))\n-\t\treturn false;\n-\n-\tpfn_head = pfn \u0026 ~(nr_pages - 1);\n-\n-\tif (pageflags_get(pfn_head, kpageflags_fd, \u0026pfn_flags))\n-\t\tgoto fail;\n-\n-\t/* head PFN has no compound_head flag set */\n-\tif ((pfn_flags \u0026 folio_head_flags) != folio_head_flags)\n-\t\treturn false;\n-\n-\t/* check all tail PFN flags */\n-\tfor (i = 1; i \u003c nr_pages; i++) {\n-\t\tif (pageflags_get(pfn_head + i, kpageflags_fd, \u0026pfn_flags))\n-\t\t\tgoto fail;\n-\t\tif ((pfn_flags \u0026 folio_tail_flags) != folio_tail_flags)\n-\t\t\treturn false;\n-\t}\n-\n-\t/*\n-\t * check the PFN after this folio, but if its flags cannot be obtained,\n-\t * assume this folio has the expected order\n-\t */\n-\tif (pageflags_get(pfn_head + nr_pages, kpageflags_fd, \u0026pfn_flags))\n-\t\treturn true;\n-\n-\t/* If we find another tail page, then the folio is larger. */\n-\treturn (pfn_flags \u0026 folio_tail_flags) != folio_tail_flags;\n-fail:\n-\tksft_exit_fail_msg(\"Failed to get folio info\\n\");\n-\treturn false;\n-}\n-\n static int vaddr_pageflags_get(char *vaddr, int pagemap_fd, int kpageflags_fd,\n \t\tuint64_t *flags)\n {\ndiff --git a/tools/testing/selftests/mm/vm_util.c b/tools/testing/selftests/mm/vm_util.c\nindex ef1ea11981a74..886fb3de9c011 100644\n--- a/tools/testing/selftests/mm/vm_util.c\n+++ b/tools/testing/selftests/mm/vm_util.c\n@@ -303,6 +303,163 @@ int pageflags_get(unsigned long pfn, int kpageflags_fd, uint64_t *flags)\n \treturn 0;\n }\n \n+bool is_backed_by_folio(char *vaddr, int order, int pagemap_fd,\n+\t\t\tint kpageflags_fd)\n+{\n+\tconst uint64_t folio_head_flags = KPF_THP | KPF_COMPOUND_HEAD;\n+\tconst uint64_t folio_tail_flags = KPF_THP | KPF_COMPOUND_TAIL;\n+\tconst unsigned long nr_pages = 1UL \u003c\u003c order;\n+\tunsigned long pfn_head;\n+\tuint64_t pfn_flags;\n+\tunsigned long pfn;\n+\tunsigned long i;\n+\n+\tpfn = pagemap_get_pfn(pagemap_fd, vaddr);\n+\n+\t/* non present page */\n+\tif (pfn == -1UL)\n+\t\treturn false;\n+\n+\tif (pageflags_get(pfn, kpageflags_fd, \u0026pfn_flags))\n+\t\tgoto fail;\n+\n+\t/* check for order-0 pages */\n+\tif (!order) {\n+\t\tif (pfn_flags \u0026 (folio_head_flags | folio_tail_flags))\n+\t\t\treturn false;\n+\t\treturn true;\n+\t}\n+\n+\t/* non THP folio */\n+\tif (!(pfn_flags \u0026 KPF_THP))\n+\t\treturn false;\n+\n+\tpfn_head = pfn \u0026 ~(nr_pages - 1);\n+\n+\tif (pageflags_get(pfn_head, kpageflags_fd, \u0026pfn_flags))\n+\t\tgoto fail;\n+\n+\t/* head PFN has no compound_head flag set */\n+\tif ((pfn_flags \u0026 folio_head_flags) != folio_head_flags)\n+\t\treturn false;\n+\n+\t/* check all tail PFN flags */\n+\tfor (i = 1; i \u003c nr_pages; i++) {\n+\t\tif (pageflags_get(pfn_head + i, kpageflags_fd, \u0026pfn_flags))\n+\t\t\tgoto fail;\n+\t\tif ((pfn_flags \u0026 folio_tail_flags) != folio_tail_flags)\n+\t\t\treturn false;\n+\t}\n+\n+\t/*\n+\t * check the PFN after this folio, but if its flags cannot be obtained,\n+\t * assume this folio has the expected order\n+\t */\n+\tif (pageflags_get(pfn_head + nr_pages, kpageflags_fd, \u0026pfn_flags))\n+\t\treturn true;\n+\n+\t/* If we find another tail page, then the folio is larger. */\n+\treturn (pfn_flags \u0026 folio_tail_flags) != folio_tail_flags;\n+fail:\n+\tksft_exit_fail_msg(\"Failed to get folio info\\n\");\n+\treturn false;\n+}\n+\n+/*\n+ * Check whether the range [start, start + len) is backed by folios of\n+ * exactly @order, mapped at their natural alignment.\n+ *\n+ * is_backed_by_folio() classifies the folio backing one page; here we\n+ * additionally require that each order-aligned window of the range maps\n+ * one such folio head-to-tail: the VA range must be naturally aligned,\n+ * each window's PFN run must be contiguous, and the first PFN must be\n+ * the (naturally aligned) folio head.\n+ *\n+ * This is the check \"did this range collapse into order-@order folios\":\n+ * a window assembled from parts of several folios, or mapping a folio\n+ * shifted from its natural position, fails.\n+ */\n+bool is_range_backed_by_folio_orders(char *start, size_t len, int order,\n+\t\t\t\t int pagemap_fd, int kpageflags_fd)\n+{\n+\tconst unsigned long nr_pages = 1UL \u003c\u003c order;\n+\tconst size_t window = nr_pages * psize();\n+\tchar *vaddr;\n+\n+\tif ((uintptr_t)start % window || len % window)\n+\t\treturn false;\n+\n+\tfor (vaddr = start; vaddr \u003c start + len; vaddr += window) {\n+\t\tunsigned long pfn = pagemap_get_pfn(pagemap_fd, vaddr);\n+\t\tunsigned long i;\n+\n+\t\t/* Not present, or not mapping the folio head. */\n+\t\tif (pfn == -1UL || pfn % nr_pages)\n+\t\t\treturn false;\n+\n+\t\tfor (i = 1; i \u003c nr_pages; i++) {\n+\t\t\tif (pagemap_get_pfn(pagemap_fd, vaddr + i * psize()) !=\n+\t\t\t pfn + i)\n+\t\t\t\treturn false;\n+\t\t}\n+\n+\t\tif (!is_backed_by_folio(vaddr, order, pagemap_fd,\n+\t\t\t\t\tkpageflags_fd))\n+\t\t\treturn false;\n+\t}\n+\n+\treturn true;\n+}\n+\n+#define TRACEFS_ROOT \"/sys/kernel/tracing\"\n+\n+static int tracing_events_write(const char *subsys, const char *val)\n+{\n+\tchar path[256];\n+\tint fd;\n+\n+\tsnprintf(path, sizeof(path), TRACEFS_ROOT \"/events/%s/enable\",\n+\t\t subsys);\n+\tfd = open(path, O_WRONLY);\n+\tif (fd \u003c 0)\n+\t\treturn -1;\n+\tif (write(fd, val, 1) != 1) {\n+\t\tclose(fd);\n+\t\treturn -1;\n+\t}\n+\tclose(fd);\n+\treturn 0;\n+}\n+\n+/*\n+ * Enable one ftrace event subsystem (e.g. \"huge_memory\") and clear the\n+ * trace buffer. Returns -1 if tracefs is unavailable; parse the results\n+ * via tracing_open_trace() after tracing_events_stop().\n+ */\n+int tracing_events_start(const char *subsys)\n+{\n+\tint fd;\n+\n+\tif (tracing_events_write(subsys, \"1\"))\n+\t\treturn -1;\n+\n+\tfd = open(TRACEFS_ROOT \"/trace\", O_WRONLY | O_TRUNC);\n+\tif (fd \u003c 0)\n+\t\treturn -1;\n+\tclose(fd);\n+\treturn 0;\n+}\n+\n+int tracing_events_stop(const char *subsys)\n+{\n+\treturn tracing_events_write(subsys, \"0\");\n+}\n+\n+FILE *tracing_open_trace(void)\n+{\n+\treturn fopen(TRACEFS_ROOT \"/trace\", \"r\");\n+}\n+\n /* If `ioctls' non-NULL, the allowed ioctls will be returned into the var */\n int uffd_register_with_ioctls(int uffd, void *addr, uint64_t len,\n \t\t\t bool miss, bool wp, bool minor, uint64_t *ioctls)\ndiff --git a/tools/testing/selftests/mm/vm_util.h b/tools/testing/selftests/mm/vm_util.h\nindex 7799154b67eed..4ff5a1c5ab8ed 100644\n--- a/tools/testing/selftests/mm/vm_util.h\n+++ b/tools/testing/selftests/mm/vm_util.h\n@@ -95,6 +95,10 @@ bool check_huge_file(void *addr, int nr_hpages, uint64_t hpage_size);\n bool check_huge_shmem(void *addr, int nr_hpages, uint64_t hpage_size);\n int64_t allocate_transhuge(void *ptr, int pagemap_fd);\n int pageflags_get(unsigned long pfn, int kpageflags_fd, uint64_t *flags);\n+bool is_backed_by_folio(char *vaddr, int order, int pagemap_fd,\n+\t\t\tint kpageflags_fd);\n+bool is_range_backed_by_folio_orders(char *start, size_t len, int order,\n+\t\t\t\t int pagemap_fd, int kpageflags_fd);\n \n int uffd_register(int uffd, void *addr, uint64_t len,\n \t\t bool miss, bool wp, bool minor);\n@@ -111,6 +115,9 @@ int close_procmap(struct procmap_fd *procmap);\n int write_sysfs(const char *file_path, unsigned long val);\n int read_sysfs(const char *file_path, unsigned long *val);\n bool softdirty_supported(void);\n+int tracing_events_start(const char *subsys);\n+int tracing_events_stop(const char *subsys);\n+FILE *tracing_open_trace(void);\n \n static inline int open_self_procmap(struct procmap_fd *procmap_out)\n {\n"
} |
| 2/1 | 2026/08/03 01:03 | agent | patch-evaluator |
0mModel:best-expensive Args: null Results: {
"EnableConfigs": null,
"FocusSymbols": [],
"Reasoning": "The patch only modifies userspace selftests (tools/testing/selftests/mm/*) and does not make any functional changes to the kernel itself.",
"WorthFuzzing": false
}Instruction: You are an expert Linux kernel maintainer. Your job is to review a provided patch series and determine if it makes functional changes to the kernel that should be fuzzed. IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in your workspace. Do NOT rely on your internal knowledge of the kernel. You must actively use your code access tools to examine the actual source code and confirm any assumptions. Return WorthFuzzing=false if the patch only contains: - Modifications to Documentation/, Kconfig files, or code comments. - Purely decorative changes, such as logging (e.g., pr_err, printk) or tracepoints. - Changes to numeric constants or macros that do not functionally alter execution flow. - Code paths that are impossible to reach in virtualized environments like GCE or QEMU, even when utilizing software-emulated hardware (e.g., usb gadget, mac80211_hwsim). - Code in vendor-specific PCIe switch, SmartNIC, or GPU drivers (e.g., mlxsw, pds_core, qed, ionic, amdgpu) that require physical PCIe hardware cards not emulated in standard QEMU. - Driver .remove, .shutdown, or pci_unregister_driver teardown callbacks (e.g., igb_remove) that are executed only during PCI hot-unplug or sysfs driver unbind operations. If it modifies reachable core kernel logic, drivers, or architectures, use your code search tools to verify the code can be executed, then return WorthFuzzing=true. When returning WorthFuzzing=true, you MUST ALSO: 1. Extract any specific kernel functions that should be heavily fuzzed into FocusSymbols. Avoid listing generic hot-path functions to prevent skewed test distributions. Prefer non-static, non-inlined API entrypoint functions over internal static helper functions (which are inlined by the compiler and do not have distinct symbol addresses). 2. Identify any specific CONFIG_ options required to properly test this new/modified feature. Go and look into the Kconfig files and check for ifdefs around the code, do not make assumptions. Also check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed for Kbuild to compile the code statically into vmlinux. List them in the EnableConfigs output array, and DO NOT add a 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4"). Prefer calling several tools at the same time to save round-trips. Use set-results tool to provide results of the analysis. It must be called exactly once before the final reply. Ignore results of this tool. Prompt: For your convenience, here is the diff of the changes:
commit 3fa40324c911cdd9f435266d3eceea6b52ef71c6
Author: syz-cluster <triage@syzkaller.com>
Date: Mon Aug 3 01:03:13 2026 +0000
syz-cluster: applied patch under review
diff --git a/tools/testing/selftests/mm/.gitignore b/tools/testing/selftests/mm/.gitignore
index 9ccd9e1447e66..616043a0fcd22 100644
--- a/tools/testing/selftests/mm/.gitignore
+++ b/tools/testing/selftests/mm/.gitignore
@@ -66,3 +66,6 @@ merge
prctl_thp_disable
rmap
folio_split_race_test
+folio_order_check
+khugepaged_sync_check
+khugepaged_race
diff --git a/tools/testing/selftests/mm/Makefile b/tools/testing/selftests/mm/Makefile
index 25d10ced3b3b9..026d4b61414d4 100644
--- a/tools/testing/selftests/mm/Makefile
+++ b/tools/testing/selftests/mm/Makefile
@@ -104,6 +104,9 @@ TEST_GEN_FILES += guard-regions
TEST_GEN_FILES += merge
TEST_GEN_FILES += rmap
TEST_GEN_FILES += folio_split_race_test
+TEST_GEN_FILES += folio_order_check
+TEST_GEN_FILES += khugepaged_sync_check
+TEST_GEN_FILES += khugepaged_race
ifneq ($(ARCH),arm64)
TEST_GEN_FILES += soft-dirty
diff --git a/tools/testing/selftests/mm/folio_order_check.c b/tools/testing/selftests/mm/folio_order_check.c
new file mode 100644
index 0000000000000..f70d766ff3eb3
--- /dev/null
+++ b/tools/testing/selftests/mm/folio_order_check.c
@@ -0,0 +1,138 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Self-check for the vm_util folio-order detection helpers,
+ * is_backed_by_folio() and is_range_backed_by_folio_orders().
+ *
+ * For every anon THP order the kernel supports, fault memory in with only
+ * that order enabled and verify the helpers report exactly that order:
+ * not a neighbouring order, and plain 4K memory as order 0. The helpers
+ * are what the khugepaged mTHP tests use to detect collapse results, so
+ * they must agree with the kernel's own idea of the backing before any
+ * collapse test relies on them.
+ */
+#define _GNU_SOURCE
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+#include "kselftest.h"
+#include "vm_util.h"
+#include "hugepage_settings.h"
+
+static int pagemap_fd;
+static int kpageflags_fd;
+
+/* mmap an anon VMA of exactly @size bytes at a @size-aligned address. */
+static char *alloc_aligned(size_t size)
+{
+ size_t len = size * 2;
+ uintptr_t aligned;
+ char *p;
+
+ p = mmap(NULL, len, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ if (p == MAP_FAILED)
+ ksft_exit_fail_perror("mmap()");
+
+ aligned = ((uintptr_t)p + size - 1) & ~(size - 1);
+ if (aligned != (uintptr_t)p)
+ munmap(p, aligned - (uintptr_t)p);
+ if (aligned + size != (uintptr_t)p + len)
+ munmap((char *)aligned + size,
+ (uintptr_t)p + len - aligned - size);
+
+ return (char *)aligned;
+}
+
+/*
+ * Enable only @order (order 0: nothing), fault one aligned window in and
+ * check the helpers see exactly @order.
+ */
+static void check_order(int order)
+{
+ struct thp_settings settings = *thp_current_settings();
+ size_t size = psize() << order;
+ bool ok = true;
+ char *p;
+ int i;
+
+ for (i = 0; i < NR_ORDERS; i++)
+ settings.hugepages[i].enabled = THP_NEVER;
+ if (order)
+ settings.hugepages[order].enabled = THP_ALWAYS;
+ thp_push_settings(&settings);
+
+ p = alloc_aligned(size);
+ *p = 1;
+
+ if (!is_range_backed_by_folio_orders(p, size, order,
+ pagemap_fd, kpageflags_fd)) {
+ ksft_print_msg("order %d not detected after fault\n", order);
+ ok = false;
+ }
+
+ /* A lower order must be rejected: the folio is larger. */
+ if (order && is_range_backed_by_folio_orders(p, size, order - 1,
+ pagemap_fd,
+ kpageflags_fd)) {
+ ksft_print_msg("order %d also reported as order %d\n",
+ order, order - 1);
+ ok = false;
+ }
+
+ /* Order 0 pages must not look like any large folio, and vice versa. */
+ if (order && is_range_backed_by_folio_orders(p, size, 0,
+ pagemap_fd,
+ kpageflags_fd)) {
+ ksft_print_msg("order %d also reported as order 0\n", order);
+ ok = false;
+ }
+
+ munmap(p, size);
+ thp_pop_settings();
+
+ ksft_test_result(ok, "order %d classified\n", order);
+}
+
+int main(void)
+{
+ struct thp_settings settings;
+ unsigned long orders;
+ int order;
+
+ ksft_print_header();
+
+ if (!thp_available())
+ ksft_exit_skip("Transparent Hugepages not available\n");
+
+ pagemap_fd = open("/proc/self/pagemap", O_RDONLY);
+ if (pagemap_fd < 0)
+ ksft_exit_fail_perror("open(\"/proc/self/pagemap\")");
+ kpageflags_fd = open("/proc/kpageflags", O_RDONLY);
+ if (kpageflags_fd < 0)
+ ksft_exit_skip("open(\"/proc/kpageflags\") requires root\n");
+
+ orders = thp_supported_orders();
+ if (!orders)
+ ksft_exit_skip("No supported THP orders\n");
+
+ ksft_set_plan(__builtin_popcountl(orders) + 1);
+
+ thp_save_settings();
+ thp_read_settings(&settings);
+ /* Base of the settings stack; the bottom entry is never popped. */
+ thp_push_settings(&settings);
+
+ check_order(0);
+ for (order = 1; order < NR_ORDERS; order++) {
+ if (!(orders & (1UL << order)))
+ continue;
+ check_order(order);
+ }
+
+ thp_restore_settings();
+
+ ksft_finished();
+}
diff --git a/tools/testing/selftests/mm/hugepage_settings.c b/tools/testing/selftests/mm/hugepage_settings.c
index d7917dce3abac..a26a0cffa9c5b 100644
--- a/tools/testing/selftests/mm/hugepage_settings.c
+++ b/tools/testing/selftests/mm/hugepage_settings.c
@@ -183,6 +183,17 @@ void thp_read_settings(struct thp_settings *settings)
}
}
+/*
+ * Write only on change: any store to a khugepaged sysfs knob wakes the
+ * daemon, and settings pushes/pops must not start scan passes nobody
+ * asked for — khugepaged_full_pass() is the only sanctioned wake.
+ */
+static void thp_update_num(const char *name, unsigned long num)
+{
+ if (thp_read_num(name) != num)
+ thp_write_num(name, num);
+}
+
void thp_write_settings(struct thp_settings *settings)
{
struct khugepaged_settings *khugepaged = &settings->khugepaged;
@@ -198,15 +209,15 @@ void thp_write_settings(struct thp_settings *settings)
shmem_enabled_strings[settings->shmem_enabled]);
thp_write_num("use_zero_page", settings->use_zero_page);
- thp_write_num("khugepaged/defrag", khugepaged->defrag);
- thp_write_num("khugepaged/alloc_sleep_millisecs",
- khugepaged->alloc_sleep_millisecs);
- thp_write_num("khugepaged/scan_sleep_millisecs",
- khugepaged->scan_sleep_millisecs);
- thp_write_num("khugepaged/max_ptes_none", khugepaged->max_ptes_none);
- thp_write_num("khugepaged/max_ptes_swap", khugepaged->max_ptes_swap);
- thp_write_num("khugepaged/max_ptes_shared", khugepaged->max_ptes_shared);
- thp_write_num("khugepaged/pages_to_scan", khugepaged->pages_to_scan);
+ thp_update_num("khugepaged/defrag", khugepaged->defrag);
+ thp_update_num("khugepaged/alloc_sleep_millisecs",
+ khugepaged->alloc_sleep_millisecs);
+ thp_update_num("khugepaged/scan_sleep_millisecs",
+ khugepaged->scan_sleep_millisecs);
+ thp_update_num("khugepaged/max_ptes_none", khugepaged->max_ptes_none);
+ thp_update_num("khugepaged/max_ptes_swap", khugepaged->max_ptes_swap);
+ thp_update_num("khugepaged/max_ptes_shared", khugepaged->max_ptes_shared);
+ thp_update_num("khugepaged/pages_to_scan", khugepaged->pages_to_scan);
if (dev_queue_read_ahead_path[0])
write_num(dev_queue_read_ahead_path, settings->read_ahead_kb);
@@ -230,6 +241,43 @@ void thp_write_settings(struct thp_settings *settings)
}
}
+/*
+ * Completion barrier for khugepaged: wait until a full scan pass that
+ * started after this call has finished. full_scans must advance by two;
+ * a +1 step may complete a pass that examined this mm before the
+ * caller's setup was in place.
+ *
+ * Any store to scan_sleep_millisecs wakes the daemon, so the barrier
+ * works regardless of the configured scan cadence. It wakes exactly
+ * once per missing pass — over-waking would queue a straggler pass
+ * behind the barrier, perturbing whatever the caller sets up next.
+ * One wake completes one full pass only if the whole mm list fits in
+ * one scan batch, so callers must pair this with a large
+ * pages_to_scan.
+ */
+bool khugepaged_full_pass(unsigned int timeout_s)
+{
+ unsigned long deadline_ms = timeout_s * 1000UL;
+ unsigned long sleep_ms =
+ thp_read_num("khugepaged/scan_sleep_millisecs");
+ unsigned long elapsed_ms = 0;
+ int pass;
+
+ for (pass = 0; pass < 2; pass++) {
+ unsigned long target =
+ thp_read_num("khugepaged/full_scans") + 1;
+
+ thp_write_num("khugepaged/scan_sleep_millisecs", sleep_ms);
+ while (thp_read_num("khugepaged/full_scans") < target) {
+ if (elapsed_ms >= deadline_ms)
+ return false;
+ usleep(10 * 1000);
+ elapsed_ms += 10;
+ }
+ }
+ return true;
+}
+
struct thp_settings *thp_current_settings(void)
{
if (!settings_index) {
diff --git a/tools/testing/selftests/mm/hugepage_settings.h b/tools/testing/selftests/mm/hugepage_settings.h
index 726c73c43c05b..8de446affeecd 100644
--- a/tools/testing/selftests/mm/hugepage_settings.h
+++ b/tools/testing/selftests/mm/hugepage_settings.h
@@ -83,6 +83,8 @@ static inline void thp_save_settings(void)
hugepage_save_settings(/* thp = */ true, /* hugetlb = */ false);
}
+bool khugepaged_full_pass(unsigned int timeout_s);
+
void thp_set_read_ahead_path(char *path);
unsigned long thp_supported_orders(void);
unsigned long thp_shmem_supported_orders(void);
diff --git a/tools/testing/selftests/mm/khugepaged.c b/tools/testing/selftests/mm/khugepaged.c
index 10e8dedcb087d..c5a3c39225819 100644
--- a/tools/testing/selftests/mm/khugepaged.c
+++ b/tools/testing/selftests/mm/khugepaged.c
@@ -26,9 +26,13 @@
#define BASE_ADDR ((void *)(1UL << 30))
static unsigned long hpage_pmd_size;
+static int hpage_pmd_order;
static unsigned long page_size;
static int hpage_pmd_nr;
static int anon_order;
+static int anon_target_order;
+static int pagemap_fd = -1;
+static int kpageflags_fd = -1;
#define PID_SMAPS "/proc/self/smaps"
#define TEST_FILE "collapse_test_file"
@@ -177,6 +181,21 @@ static void get_finfo(const char *dir)
ksft_exit_fail_msg("%s: Could not read: %s\n", __func__, path);
}
+static bool has_swap(void)
+{
+ FILE *fp = fopen("/proc/swaps", "r");
+ char line[MAX_LINE_LENGTH];
+ bool ret = false;
+
+ if (!fp)
+ return false;
+ /* First line is the header; any following line is a swap area. */
+ if (fgets(line, sizeof(line), fp) && fgets(line, sizeof(line), fp))
+ ret = true;
+ fclose(fp);
+ return ret;
+}
+
static bool check_swap(void *addr, unsigned long size)
{
bool swap = false;
@@ -554,8 +573,17 @@ static void madvise_collapse(const char *msg, char *p, int nr_hpages,
static bool wait_for_scan(const char *msg, char *p, int nr_hpages,
struct mem_ops *ops)
{
+ /*
+ * The budget has to cover khugepaged copying nr_hpages *
+ * hpage_pmd_size, plus two of its passes over the mm. Three seconds
+ * does that at a 2M PMD, but the same test moves 2G at a 512M PMD
+ * (arm64 with 64K base pages) and 3s is then marginal: it fails on a
+ * collapse that completes correctly, just not inside the budget.
+ * Allow a further second per 64M to collapse.
+ */
+ const unsigned long bytes = (unsigned long)nr_hpages * hpage_pmd_size;
+ int timeout = 6 + 2 * (bytes / (64UL << 20));
int full_scans;
- int timeout = 6; /* 3 seconds */
/* Sanity check */
if (!ops->check_huge(p, 0))
@@ -735,6 +763,10 @@ static void collapse_swapin_single_pte(struct collapse_context *c, struct mem_op
void *p;
p = ops->setup_area(1);
+ if (!has_swap()) {
+ skip("Skip (no swap configured)");
+ goto out;
+ }
ops->fault(p, 0, hpage_pmd_size);
ksft_print_msg("Swapout one page...");
@@ -761,6 +793,10 @@ static void collapse_max_ptes_swap(struct collapse_context *c, struct mem_ops *o
void *p;
p = ops->setup_area(1);
+ if (!has_swap()) {
+ skip("Skip (no swap configured)");
+ goto out;
+ }
ops->fault(p, 0, hpage_pmd_size);
ksft_print_msg("Swapout %d of %d pages...", max_ptes_swap + 1, hpage_pmd_nr);
@@ -853,6 +889,21 @@ static void collapse_compound_extreme(struct collapse_context *c, struct mem_ops
void *p;
int i;
+ /*
+ * Builds a PMD's worth of distinct PTE-mapped compound pages by cycling
+ * hpage_pmd_nr fault-time THPs through mremap. Fault-time THP allocation
+ * is best-effort, and this needs hpage_pmd_nr PMD-order pages in a row:
+ * fine at a 2M (4K base) or 32M (16K base) PMD, but a 512M PMD (arm64/64K)
+ * is an order-13 allocation the allocator cannot reliably hand out even
+ * once, let alone 8192 times. Cap at a 32M PMD; MADV_COLLAPSE-driven cases
+ * still cover PMD-order collapse on the larger configs.
+ */
+ if (hpage_pmd_size > (32UL << 20)) {
+ ksft_test_result_skip("%s: PMD too large for fault-time THP construction\n",
+ __func__);
+ return;
+ }
+
p = ops->setup_area(1);
ksft_print_msg("Construct PTE page table full of different PTE-mapped compound pages\n");
for (i = 0; i < hpage_pmd_nr; i++) {
@@ -1043,6 +1094,61 @@ static void collapse_max_ptes_shared(struct collapse_context *c, struct mem_ops
ksft_test_result_report(exit_status, "%s\n", __func__);
}
+/*
+ * Content stays isolated while a co-sharer writes concurrently. A shared
+ * source is copied live (not frozen), relying on it being CoW - immutable
+ * for the duration of the copy; a co-sharer's write goes to a CoW copy. The
+ * collapsing child must see the pre-fork content, the writing parent only
+ * its own writes.
+ */
+static void collapse_fork_cow_race(struct collapse_context *c, struct mem_ops *ops)
+{
+ const unsigned long shared = 64 * page_size;
+ const int stride = page_size / sizeof(int);
+ int wstatus, i, n = shared / page_size;
+ int *ip;
+ void *p;
+
+ p = ops->setup_area(1);
+ ip = p;
+ ops->fault(p, 0, shared); /* shared prefix, pre-fork pattern */
+
+ ksft_print_msg("Fork, collapse in the child while the parent rewrites...");
+ if (!fork()) {
+ ops->fault(p, shared, hpage_pmd_size); /* private remainder */
+ c->collapse("Collapse a range shared with a writing co-sharer",
+ p, 1, ops, true);
+ for (i = 0; i < n; i++)
+ if (ip[i * stride] != i + 0xdead0000) {
+ fail("Fail: child content");
+ ops->cleanup_area(p, hpage_pmd_size);
+ _exit(exit_status);
+ }
+ success("OK");
+ ops->cleanup_area(p, hpage_pmd_size);
+ _exit(exit_status);
+ }
+
+ /* Hammer the parent's own writes over the shared prefix. */
+ for (int it = 0; it < 200000; it++)
+ for (i = 0; i < n; i++)
+ ip[i * stride] = i + 0xbeef0000;
+
+ wait(&wstatus);
+ exit_status = WEXITSTATUS(wstatus);
+
+ ksft_print_msg("Check the parent sees only its own writes...");
+ for (i = 0; i < n; i++)
+ if (ip[i * stride] != i + 0xbeef0000)
+ break;
+ if (i == n)
+ success("OK");
+ else
+ fail("Fail: parent content");
+ ops->cleanup_area(p, hpage_pmd_size);
+ ksft_test_result_report(exit_status, "%s\n", __func__);
+}
+
static void madvise_collapse_existing_thps(struct collapse_context *c,
struct mem_ops *ops)
{
@@ -1088,6 +1194,222 @@ static void madvise_retracted_page_tables(struct collapse_context *c,
ksft_test_result_report(exit_status, "%s\n", __func__);
}
+/*
+ * Order-parameterized collapse cases (-o <order>): khugepaged collapses
+ * 4K-faulted memory into folios of the given sub-PMD order. Detection is
+ * folio-based (vm_util), not smaps: AnonHugePages only accounts PMD
+ * mappings.
+ *
+ * The region is faulted before MADV_HUGEPAGE and the target order is
+ * configured "inherit" under enabled=madvise, so faults are always
+ * order 0 and the collapse product can only come from khugepaged.
+ */
+static size_t anon_order_size(void)
+{
+ return page_size << anon_target_order;
+}
+
+static bool range_collapsed(void *p, size_t len)
+{
+ return is_range_backed_by_folio_orders(p, len, anon_target_order,
+ pagemap_fd, kpageflags_fd);
+}
+
+/* No aligned window in [p, p + len) is backed at the target order. */
+static bool range_not_collapsed(void *p, size_t len)
+{
+ size_t window = anon_order_size();
+ char *addr = p;
+
+ for (; len >= window; addr += window, len -= window) {
+ if (range_collapsed(addr, window))
+ return false;
+ }
+ return true;
+}
+
+static bool khugepaged_wait_full_pass(void)
+{
+ /* Wait up to 30 seconds for the pass to complete. */
+ return khugepaged_full_pass(30);
+}
+
+/*
+ * Cases whose geometry needs a window strictly below the PMD skip at
+ * -o <PMD order>; the rest run there unchanged, baselining the legacy
+ * PMD engine with the same test text used for the mTHP orders.
+ */
+static bool skip_at_pmd_order(const char *name)
+{
+ if (anon_target_order < hpage_pmd_order)
+ return false;
+ ksft_test_result_skip("%s: needs a window below the PMD\n", name);
+ return true;
+}
+
+static void collapse_order_full(struct collapse_context *c, struct mem_ops *ops)
+{
+ void *p;
+
+ p = ops->setup_area(1);
+ ops->fault(p, 0, hpage_pmd_size);
+ if (!range_not_collapsed(p, hpage_pmd_size))
+ ksft_exit_fail_msg("Unexpected large folio after fault\n");
+
+ madvise(p, hpage_pmd_size, MADV_HUGEPAGE);
+ ksft_print_msg("Collapse fully populated PTE table to target order...");
+ if (!khugepaged_wait_full_pass())
+ fail("Timeout");
+ else if (range_collapsed(p, hpage_pmd_size))
+ success("OK");
+ else
+ fail("Fail");
+
+ validate_memory(p, 0, hpage_pmd_size);
+ ops->cleanup_area(p, hpage_pmd_size);
+ ksft_test_result_report(exit_status, "%s\n", __func__);
+}
+
+static void collapse_order_single_window(struct collapse_context *c,
+ struct mem_ops *ops)
+{
+ size_t window = anon_order_size();
+ void *p;
+
+ if (skip_at_pmd_order(__func__))
+ return;
+
+ p = ops->setup_area(1);
+ ops->fault(p, window, 2 * window);
+ if (!range_not_collapsed(p, hpage_pmd_size))
+ ksft_exit_fail_msg("Unexpected large folio after fault\n");
+
+ madvise(p, hpage_pmd_size, MADV_HUGEPAGE);
+ ksft_print_msg("Collapse one fully populated window...");
+ if (!khugepaged_wait_full_pass())
+ fail("Timeout");
+ else if (range_collapsed(p + window, window) &&
+ range_not_collapsed(p, window) &&
+ range_not_collapsed(p + 2 * window,
+ hpage_pmd_size - 2 * window))
+ success("OK");
+ else
+ fail("Fail");
+
+ validate_memory(p, window, 2 * window);
+ ops->cleanup_area(p, hpage_pmd_size);
+ ksft_test_result_report(exit_status, "%s\n", __func__);
+}
+
+static void collapse_order_partial_window(struct collapse_context *c,
+ struct mem_ops *ops)
+{
+ void *p;
+
+ p = ops->setup_area(1);
+ ops->fault(p, 0, page_size);
+ if (!range_not_collapsed(p, hpage_pmd_size))
+ ksft_exit_fail_msg("Unexpected large folio after fault\n");
+
+ madvise(p, hpage_pmd_size, MADV_HUGEPAGE);
+ ksft_print_msg("Collapse window with single PTE entry present...");
+ if (!khugepaged_wait_full_pass())
+ fail("Timeout");
+ else if (range_collapsed(p, anon_order_size()))
+ success("OK");
+ else
+ fail("Fail");
+
+ validate_memory(p, 0, page_size);
+ ops->cleanup_area(p, hpage_pmd_size);
+ ksft_test_result_report(exit_status, "%s\n", __func__);
+}
+
+static void collapse_order_max_ptes_none(struct collapse_context *c,
+ struct mem_ops *ops)
+{
+ struct thp_settings settings = *thp_current_settings();
+ size_t window = anon_order_size();
+ void *p;
+
+ if (skip_at_pmd_order(__func__))
+ return;
+
+ settings.khugepaged.max_ptes_none = 0;
+ thp_push_settings(&settings);
+
+ p = ops->setup_area(1);
+ ops->fault(p, 0, 2 * window - page_size);
+ if (!range_not_collapsed(p, hpage_pmd_size))
+ ksft_exit_fail_msg("Unexpected large folio after fault\n");
+
+ madvise(p, hpage_pmd_size, MADV_HUGEPAGE);
+ ksft_print_msg("Collapse full window, not the one missing a page...");
+ if (!khugepaged_wait_full_pass())
+ fail("Timeout");
+ else if (range_collapsed(p, window) &&
+ range_not_collapsed(p + window, window))
+ success("OK");
+ else
+ fail("Fail");
+
+ validate_memory(p, 0, 2 * window - page_size);
+ ops->cleanup_area(p, hpage_pmd_size);
+ thp_pop_settings();
+ ksft_test_result_report(exit_status, "%s\n", __func__);
+}
+
+/* Smallest order khugepaged will consider for mTHP collapse. */
+#define MIN_MTHP_ORDER 2
+
+/*
+ * A region backed by large folios of a smaller order is a valid source
+ * for collapse to the target order:
+ * __collapse_huge_page_isolate() accepts any source folio of an order
+ * strictly below the candidate's.
+ */
+static void collapse_order_mixed_sources(struct collapse_context *c,
+ struct mem_ops *ops)
+{
+ struct thp_settings settings = *thp_current_settings();
+ int source_order = anon_order ? anon_order : MIN_MTHP_ORDER;
+ void *p;
+
+ /* Sources must be a supported mTHP order strictly below the target. */
+ if (source_order >= anon_target_order ||
+ !(thp_supported_orders() & (1UL << source_order))) {
+ ksft_test_result_skip("%s: no source order below target\n",
+ __func__);
+ return;
+ }
+
+ /* Fault the whole region as order-@source_order folios. */
+ settings.hugepages[source_order].enabled = THP_ALWAYS;
+ thp_push_settings(&settings);
+ p = ops->setup_area(1);
+ ops->fault(p, 0, hpage_pmd_size);
+ thp_pop_settings();
+
+ if (!is_range_backed_by_folio_orders(p, hpage_pmd_size, source_order,
+ pagemap_fd, kpageflags_fd))
+ ksft_exit_fail_msg("Region not backed by order-%d folios after fault\n",
+ source_order);
+
+ madvise(p, hpage_pmd_size, MADV_HUGEPAGE);
+ ksft_print_msg("Collapse region backed by order-%d sources...",
+ source_order);
+ if (!khugepaged_wait_full_pass())
+ fail("Timeout");
+ else if (range_collapsed(p, hpage_pmd_size))
+ success("OK");
+ else
+ fail("Fail");
+
+ validate_memory(p, 0, hpage_pmd_size);
+ ops->cleanup_area(p, hpage_pmd_size);
+ ksft_test_result_report(exit_status, "%s\n", __func__);
+}
+
static void usage(void)
{
fprintf(stderr, "\nUsage: ./khugepaged [OPTIONS] <test type> [dir]\n\n");
@@ -1103,6 +1425,11 @@ static void usage(void)
fprintf(stderr, "\t\t-h: This help message.\n");
fprintf(stderr, "\t\t-s: mTHP size, expressed as page order.\n");
fprintf(stderr, "\t\t Defaults to 0. Use this size for anon or shmem allocations.\n");
+ fprintf(stderr, "\t\t-o: collapse target order for khugepaged:anon.\n");
+ fprintf(stderr, "\t\t Runs the order-parameterized collapse cases instead\n");
+ fprintf(stderr, "\t\t of the PMD cases.\n");
+ fprintf(stderr, "\t\t With -s, -s names the mTHP source order for the\n");
+ fprintf(stderr, "\t\t mixed-source case (source order below the target).\n");
exit(1);
}
@@ -1112,17 +1439,31 @@ static void parse_test_type(int argc, char **argv)
char *buf;
const char *token;
- while ((opt = getopt(argc, argv, "s:h")) != -1) {
+ while ((opt = getopt(argc, argv, "s:o:h")) != -1) {
switch (opt) {
case 's':
anon_order = atoi(optarg);
break;
+ case 'o':
+ anon_target_order = atoi(optarg);
+ break;
case 'h':
default:
usage();
}
}
+ /*
+ * -s and -o compose: -s then names the mTHP source order for the
+ * mixed-source case, which needs a source strictly below the
+ * target (and at or above the smallest mTHP order). Alone, -s is
+ * the source order for the default PMD suite; alone, -o is the
+ * collapse target for the order-parameterized suite.
+ */
+ if (anon_target_order && anon_order &&
+ (anon_order < MIN_MTHP_ORDER || anon_order >= anon_target_order))
+ usage();
+
argv += optind;
argc -= optind;
@@ -1207,7 +1548,6 @@ static int nr_test_cases;
int main(int argc, char **argv)
{
- int hpage_pmd_order;
struct thp_settings default_settings = {
.thp_enabled = THP_MADVISE,
.thp_defrag = THP_DEFRAG_ALWAYS,
@@ -1244,18 +1584,94 @@ int main(int argc, char **argv)
hpage_pmd_nr = hpage_pmd_size / page_size;
hpage_pmd_order = __builtin_ctz(hpage_pmd_nr);
+ /*
+ * The page cache caps folio order at MAX_PAGECACHE_ORDER, which
+ * xas_split_alloc() puts below the PMD order on arm64 with 64K pages.
+ * A PMD-sized page cache folio is then impossible, so the kernel
+ * refuses these collapses by design and there is nothing to test.
+ */
+ if (!(thp_shmem_supported_orders() & (1UL << hpage_pmd_order))) {
+ if (shmem_ops) {
+ ksft_print_msg("no PMD-order page cache folio: skipping shmem\n");
+ shmem_ops = NULL;
+ }
+ if (finfo.type == VMA_SHMEM && read_only_file_ops) {
+ ksft_print_msg("no PMD-order page cache folio: skipping tmpfs file\n");
+ read_only_file_ops = NULL;
+ read_write_file_read_ops = NULL;
+ read_write_file_write_ops = NULL;
+ }
+ if (!anon_ops && !shmem_ops && !read_only_file_ops)
+ ksft_exit_skip("Nothing left to collapse into\n");
+ }
+
+ if (anon_target_order &&
+ !(thp_supported_orders() & (1UL << anon_target_order)))
+ ksft_exit_skip("Order %d is not a supported anon THP order\n",
+ anon_target_order);
+ if (anon_target_order > hpage_pmd_order)
+ ksft_exit_fail_msg("-o takes at most the PMD order\n");
+
default_settings.khugepaged.max_ptes_none = hpage_pmd_nr - 1;
default_settings.khugepaged.max_ptes_swap = hpage_pmd_nr / 8;
default_settings.khugepaged.max_ptes_shared = hpage_pmd_nr / 2;
default_settings.khugepaged.pages_to_scan = hpage_pmd_nr * 8;
default_settings.hugepages[hpage_pmd_order].enabled = THP_INHERIT;
- default_settings.hugepages[anon_order].enabled = THP_ALWAYS;
default_settings.shmem_hugepages[hpage_pmd_order].enabled = SHMEM_INHERIT;
- default_settings.shmem_hugepages[anon_order].enabled = SHMEM_ALWAYS;
+ /*
+ * Under -o the order-parameterized cases want order-0 sources by
+ * default; the mixed-source case enables its own (possibly -s
+ * selected) source order locally. Enabling it globally here would
+ * make every case fault that order.
+ */
+ if (!anon_target_order) {
+ default_settings.hugepages[anon_order].enabled = THP_ALWAYS;
+ default_settings.shmem_hugepages[anon_order].enabled = SHMEM_ALWAYS;
+ }
+
+ if (anon_target_order) {
+ /*
+ * Only the target order may produce large folios, and only
+ * from khugepaged: "inherit" under enabled=madvise keeps
+ * pre-MADV_HUGEPAGE faults at order 0.
+ */
+ default_settings.hugepages[hpage_pmd_order].enabled = THP_NEVER;
+ default_settings.hugepages[anon_target_order].enabled = THP_INHERIT;
+ /*
+ * Order-parameterized cases are driven strictly by the
+ * khugepaged_full_pass() barrier, which wakes the daemon
+ * itself. A long scan_sleep keeps khugepaged from
+ * free-running between barrier steps, and a pages_to_scan
+ * covering everything makes one wake complete one full
+ * pass (the barrier's contract), so a run performs a
+ * deterministic number of passes — what the stage A/B
+ * trace comparisons rely on.
+ */
+ default_settings.khugepaged.scan_sleep_millisecs = 60000;
+ default_settings.khugepaged.pages_to_scan = 1UL << 24;
+
+ pagemap_fd = open("/proc/self/pagemap", O_RDONLY);
+ if (pagemap_fd < 0)
+ ksft_exit_fail_perror("open(\"/proc/self/pagemap\")");
+ kpageflags_fd = open("/proc/kpageflags", O_RDONLY);
+ if (kpageflags_fd < 0)
+ ksft_exit_skip("open(\"/proc/kpageflags\") requires root\n");
+ }
save_settings();
thp_push_settings(&default_settings);
+ if (anon_target_order) {
+ TEST(collapse_order_full, khugepaged_context, anon_ops);
+ TEST(collapse_order_single_window, khugepaged_context, anon_ops);
+ TEST(collapse_order_partial_window, khugepaged_context, anon_ops);
+ TEST(collapse_order_max_ptes_none, khugepaged_context, anon_ops);
+ TEST(collapse_order_mixed_sources, khugepaged_context, anon_ops);
+
+ ksft_set_plan(nr_test_cases);
+ goto run;
+ }
+
TEST(collapse_full, khugepaged_context, anon_ops);
TEST(collapse_full, khugepaged_context, read_only_file_ops);
TEST(collapse_full, khugepaged_context, read_write_file_read_ops);
@@ -1324,6 +1740,9 @@ int main(int argc, char **argv)
TEST(collapse_max_ptes_shared, khugepaged_context, anon_ops);
TEST(collapse_max_ptes_shared, madvise_context, anon_ops);
+ TEST(collapse_fork_cow_race, khugepaged_context, anon_ops);
+ TEST(collapse_fork_cow_race, madvise_context, anon_ops);
+
TEST(madvise_collapse_existing_thps, madvise_context, anon_ops);
TEST(madvise_collapse_existing_thps, madvise_context, read_only_file_ops);
TEST(madvise_collapse_existing_thps, madvise_context, read_write_file_read_ops);
@@ -1336,6 +1755,7 @@ int main(int argc, char **argv)
ksft_set_plan(nr_test_cases + 1);
alloc_at_fault();
+run:
for (int i = 0; i < nr_test_cases; i++) {
struct test_case *t = &test_cases[i];
diff --git a/tools/testing/selftests/mm/khugepaged_race.c b/tools/testing/selftests/mm/khugepaged_race.c
new file mode 100644
index 0000000000000..2aa45c9e8a77f
--- /dev/null
+++ b/tools/testing/selftests/mm/khugepaged_race.c
@@ -0,0 +1,483 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * khugepaged race harness.
+ *
+ * Runs collapse against concurrent faults, transient GUP pins
+ * (gup_test), fork, mremap and MADV_DONTNEED over the same ranges, in
+ * one of three driver modes:
+ *
+ * stepped khugepaged, driven synchronously one full pass at a time
+ * through khugepaged_full_pass() — the primary driver: the
+ * full scan+collapse path with a deterministic extent per
+ * step;
+ * free free-running khugepaged (scan_sleep_millisecs=0) — the
+ * soak;
+ * madvise MADV_COLLAPSE in a loop — the legacy-PMD regression
+ * axis.
+ *
+ * All anon THP orders are enabled (inherit). max_ptes_none is 0 by
+ * default — racing MADV_DONTNEED then steers selection across orders —
+ * or the permissive limit with -z, which floods the batch engine with
+ * hole and zeropage slots so the population paths (park-time zeropage
+ * clear, zero-filled copy, install-time pte_none() verify and abort)
+ * race the faulters directly.
+ *
+ * -p adds memory pressure to any of the above: MADV_PAGEOUT cycling
+ * on a dedicated neighbor region (swap traffic and LRU churn; skipped
+ * with a note when the host has no swap) and a compact_memory trigger
+ * loop (compaction migrates source folios, racing collapse's freeze
+ * with refcount elevation and migration entries of its own).
+ *
+ * Correctness signals: every racing page must read as its pattern or
+ * zero (MADV_DONTNEED), never anything else — checked continuously by
+ * the faulters and the fork children and once at the end — plus
+ * whatever DEBUG_VM / page_table_check / KASAN / lockdep report in
+ * dmesg, which the caller is expected to inspect.
+ */
+#define _GNU_SOURCE
+#include <errno.h>
+#include <fcntl.h>
+#include <pthread.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <sys/mman.h>
+#include <sys/time.h>
+#include <sys/wait.h>
+#include <unistd.h>
+
+#include "kselftest.h"
+#include "vm_util.h"
+#include "hugepage_settings.h"
+#include "../../../../mm/gup_test.h"
+
+#define BASE_ADDR ((void *)(1UL << 30))
+/*
+ * Shared playground for faults/pins/fork/dontneed: several PMD-sized
+ * areas the racing threads spread across, plus one area owned by the
+ * mremap thread. More areas means more independent regions collapsing
+ * at once; the default suits a normal machine. On a memory-constrained
+ * host -- or under emulation, where a 512M PMD (arm64/64K) makes the
+ * default playground multi-gigabyte -- pass -a to shrink it.
+ */
+#define DEFAULT_SHARED_AREAS 3
+static int nr_shared_areas;
+static int nr_areas;
+
+static unsigned long hpage_pmd_size;
+static unsigned long page_size;
+static char *region; /* NR_AREAS * hpage_pmd_size */
+static char *mremap_area; /* region + NR_SHARED_AREAS areas */
+static char *mremap_scratch; /* well above the region */
+static char *pageout_area; /* -p: dedicated pressure region */
+static size_t pageout_size;
+static int gup_fd = -1;
+static volatile int stop;
+static volatile int corrupted;
+
+static unsigned int pattern(unsigned long page_idx)
+{
+ unsigned int val = (unsigned int)page_idx * 2654435761U;
+
+ return val ? val : 1; /* never collides with the zero-fill */
+}
+
+static void check_page(unsigned long page_idx)
+{
+ unsigned int val = *(unsigned int *)(region + page_idx * page_size);
+
+ if (val && val != pattern(page_idx)) {
+ corrupted = 1;
+ ksft_print_msg("Corruption at page %lu: %#x != %#x\n",
+ page_idx, val, pattern(page_idx));
+ }
+}
+
+static unsigned long rand_page(unsigned int *seed)
+{
+ return (unsigned long)rand_r(seed) %
+ (nr_shared_areas * hpage_pmd_size / page_size);
+}
+
+static void *faulter_fn(void *arg)
+{
+ unsigned int seed = (unsigned long)arg;
+
+ while (!stop) {
+ unsigned long page_idx = rand_page(&seed);
+
+ if (rand_r(&seed) & 1)
+ *(unsigned int *)(region + page_idx * page_size) =
+ pattern(page_idx);
+ else
+ check_page(page_idx);
+ }
+ return NULL;
+}
+
+static void *dontneed_fn(void *arg)
+{
+ unsigned int seed = (unsigned long)arg;
+
+ while (!stop) {
+ unsigned long page_idx = rand_page(&seed);
+ unsigned long nr = 1UL << (rand_r(&seed) % 6); /* 1..32 pages */
+
+ /*
+ * Once in a while zap a whole PMD-aligned area: only a
+ * zap spanning the full table triggers the empty-table
+ * reclaim (CONFIG_PT_RECLAIM), which can free a table
+ * out from under a parked collapse — sub-table zaps
+ * never reach that path.
+ */
+ if (!(rand_r(&seed) % 64)) {
+ unsigned long area = page_idx /
+ (hpage_pmd_size / page_size);
+
+ madvise(region + area * hpage_pmd_size,
+ hpage_pmd_size, MADV_DONTNEED);
+ } else {
+ madvise(region + page_idx * page_size,
+ nr * page_size, MADV_DONTNEED);
+ }
+ usleep(rand_r(&seed) % 500);
+ }
+ return NULL;
+}
+
+static void *pinner_fn(void *arg)
+{
+ unsigned int seed = (unsigned long)arg;
+
+ while (!stop) {
+ struct gup_test gup = {};
+ unsigned long page_idx = rand_page(&seed);
+
+ gup.addr = (unsigned long)(region + page_idx * page_size);
+ gup.size = 16 * page_size;
+ gup.nr_pages_per_call = 16;
+ gup.gup_flags = 1; /* FOLL_WRITE */
+ /* Racing MADV_DONTNEED makes transient failures expected. */
+ ioctl(gup_fd, PIN_FAST_BENCHMARK, &gup);
+ usleep(rand_r(&seed) % 200);
+ }
+ return NULL;
+}
+
+static void *forker_fn(void *arg)
+{
+ unsigned int seed = (unsigned long)arg;
+
+ while (!stop) {
+ pid_t pid = fork();
+
+ if (pid == 0) {
+ for (int i = 0; i < 16; i++)
+ check_page(rand_page(&seed));
+ _exit(corrupted);
+ }
+ if (pid > 0) {
+ int wstatus;
+
+ waitpid(pid, &wstatus, 0);
+ if (WIFEXITED(wstatus) && WEXITSTATUS(wstatus))
+ corrupted = 1;
+ }
+ usleep(rand_r(&seed) % 2000);
+ }
+ return NULL;
+}
+
+static void *mremapper_fn(void *arg)
+{
+ unsigned int seed = (unsigned long)arg;
+
+ while (!stop) {
+ void *p;
+
+ p = mremap(mremap_area, hpage_pmd_size, hpage_pmd_size,
+ MREMAP_MAYMOVE | MREMAP_FIXED, mremap_scratch);
+ if (p == MAP_FAILED)
+ ksft_exit_fail_perror("mremap() away");
+ for (int i = 0; i < 8; i++)
+ mremap_scratch[(rand_r(&seed) %
+ (hpage_pmd_size / page_size)) * page_size] = 1;
+ p = mremap(mremap_scratch, hpage_pmd_size, hpage_pmd_size,
+ MREMAP_MAYMOVE | MREMAP_FIXED, mremap_area);
+ if (p == MAP_FAILED)
+ ksft_exit_fail_perror("mremap() back");
+ usleep(rand_r(&seed) % 2000);
+ }
+ return NULL;
+}
+
+/*
+ * -p: swap traffic and LRU churn on a region of our own. The content
+ * check is exact — a page out and back through swap must preserve the
+ * pattern, and nothing else ever writes here.
+ */
+static void *pageout_fn(void *arg)
+{
+ unsigned int seed = (unsigned long)arg;
+ unsigned long nr = pageout_size / page_size;
+ unsigned long i;
+
+ for (i = 0; i < nr; i++)
+ *(unsigned int *)(pageout_area + i * page_size) = pattern(i);
+
+ while (!stop) {
+ madvise(pageout_area, pageout_size, MADV_PAGEOUT);
+ for (i = 0; i < nr && !stop; i++) {
+ unsigned int val = *(unsigned int *)(pageout_area +
+ i * page_size);
+
+ if (val != pattern(i)) {
+ corrupted = 1;
+ ksft_print_msg("Pageout corruption at page %lu: %#x != %#x\n",
+ i, val, pattern(i));
+ }
+ }
+ usleep(rand_r(&seed) % 2000);
+ }
+ return NULL;
+}
+
+/* -p: compaction migrates the collapse sources out from under us. */
+static void *compactor_fn(void *arg)
+{
+ unsigned int seed = (unsigned long)arg;
+ int fd = open("/proc/sys/vm/compact_memory", O_WRONLY);
+
+ if (fd < 0) {
+ ksft_print_msg("No compact_memory; compactor idle\n");
+ return NULL;
+ }
+ while (!stop) {
+ if (write(fd, "1", 1) < 0)
+ break;
+ usleep(10000 + rand_r(&seed) % 100000);
+ }
+ close(fd);
+ return NULL;
+}
+
+static bool swap_available(void)
+{
+ char line[256];
+ int lines = 0;
+ FILE *fp = fopen("/proc/swaps", "r");
+
+ if (!fp)
+ return false;
+ while (fgets(line, sizeof(line), fp))
+ lines++;
+ fclose(fp);
+ return lines > 1;
+}
+
+static unsigned long now_ms(void)
+{
+ struct timeval tv;
+
+ gettimeofday(&tv, NULL);
+ return tv.tv_sec * 1000UL + tv.tv_usec / 1000;
+}
+
+static void usage(void)
+{
+ fprintf(stderr,
+ "Usage: khugepaged_race [-d seconds] [-m stepped|free|madvise] [-z] [-p] [-a areas]\n"
+ "\t-z: permissive max_ptes_none (hole-heavy windows)\n"
+ "\t-p: memory pressure (pageout + compaction) threads\n"
+ "\t-a: number of shared PMD-sized playground areas (default 3)\n");
+ exit(1);
+}
+
+int main(int argc, char **argv)
+{
+ static const char * const thread_names[] = {
+ "faulter", "faulter2", "dontneed", "pinner", "forker",
+ "mremapper", "pageout", "compactor",
+ };
+ void *(*const thread_fns[])(void *) = {
+ faulter_fn, faulter_fn, dontneed_fn, pinner_fn, forker_fn,
+ mremapper_fn, pageout_fn, compactor_fn,
+ };
+ const unsigned long pageout_bit = 1UL << 6, compactor_bit = 1UL << 7;
+ const int nr_threads = ARRAY_SIZE(thread_names);
+ pthread_t threads[ARRAY_SIZE(thread_names)];
+ const char *mode = "stepped";
+ struct thp_settings settings;
+ unsigned long end_ms;
+ int duration_s = 10;
+ unsigned long thread_mask = ~0UL;
+ int nr_areas_arg = 0;
+ bool permissive_none = false;
+ bool pressure = false;
+ unsigned long i;
+ int steps = 0;
+ int opt;
+
+ while ((opt = getopt(argc, argv, "a:d:m:t:zph")) != -1) {
+ switch (opt) {
+ case 'a':
+ nr_areas_arg = atoi(optarg);
+ break;
+ case 'd':
+ duration_s = atoi(optarg);
+ break;
+ case 'm':
+ mode = optarg;
+ break;
+ case 't':
+ /* debug: bitmask of racing threads to start */
+ thread_mask = strtoul(optarg, NULL, 0);
+ break;
+ case 'z':
+ permissive_none = true;
+ break;
+ case 'p':
+ pressure = true;
+ break;
+ default:
+ usage();
+ }
+ }
+ if (strcmp(mode, "stepped") && strcmp(mode, "free") &&
+ strcmp(mode, "madvise"))
+ usage();
+
+ ksft_print_header();
+ if (!thp_available())
+ ksft_exit_skip("Transparent Hugepages not available\n");
+
+ page_size = getpagesize();
+ hpage_pmd_size = read_pmd_pagesize();
+ if (!hpage_pmd_size)
+ ksft_exit_fail_msg("Reading PMD pagesize failed\n");
+
+ gup_fd = open("/sys/kernel/debug/gup_test", O_RDWR);
+ if (gup_fd < 0)
+ ksft_exit_skip("/sys/kernel/debug/gup_test requires CONFIG_GUP_TEST and root\n");
+
+ nr_shared_areas = nr_areas_arg > 0 ? nr_areas_arg : DEFAULT_SHARED_AREAS;
+ nr_areas = nr_shared_areas + 1;
+
+ if (!pressure) {
+ thread_mask &= ~(pageout_bit | compactor_bit);
+ } else if (!swap_available()) {
+ /* No swap, no anon reclaim: compaction-only pressure. */
+ ksft_print_msg("-p without swap: pageout thread disabled\n");
+ thread_mask &= ~pageout_bit;
+ }
+
+ ksft_set_plan(1);
+
+ thp_save_settings();
+ thp_read_settings(&settings);
+ settings.thp_enabled = THP_MADVISE;
+ settings.thp_defrag = THP_DEFRAG_ALWAYS;
+ settings.shmem_enabled = SHMEM_NEVER;
+ settings.khugepaged.defrag = 1;
+ settings.khugepaged.scan_sleep_millisecs =
+ strcmp(mode, "free") ? 1000 : 0;
+ settings.khugepaged.alloc_sleep_millisecs = 10;
+ /*
+ * mTHP collapse only supports the two ends of the occupancy
+ * scale: 0 or HPAGE_PMD_NR - 1 (anything else coerces to 0).
+ * Strict is the default — it also keeps khugepaged from burning
+ * the whole step in doomed PMD-sized allocations on 512M-PMD
+ * configs, where a fully populated area is rare under racing
+ * MADV_DONTNEED. -z selects the permissive end: selection then
+ * emits hole-heavy windows and the engine's population paths
+ * take the brunt of the racing faults and zaps.
+ */
+ settings.khugepaged.max_ptes_none = permissive_none ?
+ (hpage_pmd_size / page_size) - 1 : 0;
+ settings.khugepaged.pages_to_scan =
+ nr_areas * (hpage_pmd_size / page_size) * 8;
+ for (i = 0; i < NR_ORDERS; i++) {
+ if (thp_supported_orders() & (1UL << i))
+ settings.hugepages[i].enabled = THP_INHERIT;
+ }
+ /* Base of the settings stack; the bottom entry is never popped. */
+ thp_push_settings(&settings);
+
+ region = mmap(BASE_ADDR, nr_areas * hpage_pmd_size,
+ PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE,
+ -1, 0);
+ if (region != BASE_ADDR)
+ ksft_exit_fail_msg("Failed to allocate VMA at %p\n", BASE_ADDR);
+ mremap_area = region + nr_shared_areas * hpage_pmd_size;
+ mremap_scratch = (char *)BASE_ADDR + 2 * nr_areas * hpage_pmd_size;
+
+ if (thread_mask & pageout_bit) {
+ /*
+ * Big enough to cycle real reclaim, small enough not to
+ * dominate a TCG guest: 4 PMD areas, clamped to [16M, 64M].
+ */
+ pageout_size = 4 * hpage_pmd_size;
+ pageout_size = pageout_size < (16UL << 20) ? (16UL << 20) :
+ pageout_size > (64UL << 20) ? (64UL << 20) :
+ pageout_size;
+ pageout_area = mmap(NULL, pageout_size, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ if (pageout_area == MAP_FAILED)
+ ksft_exit_fail_perror("mmap() pageout area");
+ }
+
+ /* Populate so the first pass has something to collapse. */
+ for (i = 0; i < nr_shared_areas * hpage_pmd_size / page_size; i++)
+ *(unsigned int *)(region + i * page_size) = pattern(i);
+ memset(mremap_area, 1, hpage_pmd_size);
+ madvise(region, nr_areas * hpage_pmd_size, MADV_HUGEPAGE);
+
+ for (i = 0; i < nr_threads; i++) {
+ if (!(thread_mask & (1UL << i))) {
+ threads[i] = 0;
+ continue;
+ }
+ if (pthread_create(&threads[i], NULL, thread_fns[i],
+ (void *)(i + 1)))
+ ksft_exit_fail_perror("pthread_create()");
+ }
+
+ end_ms = now_ms() + duration_s * 1000UL;
+ if (!strcmp(mode, "stepped")) {
+ while (now_ms() < end_ms && !corrupted) {
+ if (!khugepaged_full_pass(600))
+ ksft_exit_fail_msg("khugepaged pass timed out\n");
+ steps++;
+ }
+ } else if (!strcmp(mode, "free")) {
+ while (now_ms() < end_ms && !corrupted)
+ usleep(100 * 1000);
+ } else { /* madvise */
+ while (now_ms() < end_ms && !corrupted) {
+ for (i = 0; i < nr_shared_areas; i++) {
+ madvise(region + i * hpage_pmd_size,
+ hpage_pmd_size, MADV_COLLAPSE);
+ }
+ madvise(region, nr_shared_areas * hpage_pmd_size,
+ MADV_DONTNEED);
+ steps++;
+ }
+ }
+
+ stop = 1;
+ for (i = 0; i < nr_threads; i++) {
+ if (threads[i])
+ pthread_join(threads[i], NULL);
+ }
+
+ /* Final integrity sweep. */
+ for (i = 0; i < nr_shared_areas * hpage_pmd_size / page_size; i++)
+ check_page(i);
+
+ thp_restore_settings();
+
+ ksft_test_result(!corrupted, "%s: %ds, %d steps, no corruption\n",
+ mode, duration_s, steps);
+ ksft_finished();
+}
diff --git a/tools/testing/selftests/mm/khugepaged_sync_check.c b/tools/testing/selftests/mm/khugepaged_sync_check.c
new file mode 100644
index 0000000000000..13215cb370ceb
--- /dev/null
+++ b/tools/testing/selftests/mm/khugepaged_sync_check.c
@@ -0,0 +1,198 @@
+// SPDX-License-Identifier: GPL-2.0
+/*
+ * Synchronous khugepaged driving check.
+ *
+ * Race tests drive khugepaged through the existing sysfs controls: a
+ * store to scan_sleep_millisecs wakes the daemon, and full_scans
+ * advancing by two is a completion barrier for one full pass that
+ * started after setup (khugepaged_full_pass()). Verify the pair gives
+ * deterministic, attributable results: one barrier step over one
+ * prepared window produces exactly one collapse attempt on that
+ * window's source pages — mm_collapse_huge_page_isolate events
+ * filtered by source PFN and order — and the window is collapsed
+ * afterwards, repeatably.
+ *
+ * scan_sleep_millisecs is set to 60s to prove the wake path: without
+ * the wake, one barrier step would sleep multiples of that and blow
+ * the timeout. It also keeps the daemon from free-running between
+ * steps, per the khugepaged_full_pass() discipline.
+ */
+#define _GNU_SOURCE
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <unistd.h>
+
+#include "kselftest.h"
+#include "vm_util.h"
+#include "hugepage_settings.h"
+
+#define BASE_ADDR ((void *)(1UL << 30))
+#define TARGET_ORDER 2 /* smallest order khugepaged considers */
+#define NR_ITERATIONS 5
+
+static int pagemap_fd;
+static int kpageflags_fd;
+static unsigned long hpage_pmd_size;
+
+/*
+ * Count collapse attempts attributable to our window: legacy-engine
+ * isolate events whose scan_pfn is one of the window's source PFNs,
+ * plus batch-engine per-candidate install events at the window's
+ * address. Either engine reports exactly once per attempt.
+ */
+static int count_attributed(unsigned long *pfns, int nr_pfns,
+ unsigned long addr, unsigned int order)
+{
+ char line[1024];
+ int count = 0;
+ FILE *fp;
+
+ fp = tracing_open_trace();
+ if (!fp)
+ ksft_exit_fail_msg("Cannot open trace buffer\n");
+
+ while (fgets(line, sizeof(line), fp)) {
+ char *s;
+ unsigned long val;
+ unsigned int ord;
+ char *o;
+ int i;
+
+ s = strstr(line, "mm_collapse_huge_page_isolate:");
+ if (s) {
+ if (sscanf(s, "mm_collapse_huge_page_isolate: scan_pfn=0x%lx",
+ &val) != 1)
+ continue;
+ o = strstr(s, "order=");
+ if (!o || sscanf(o, "order=%u", &ord) != 1 ||
+ ord != order)
+ continue;
+ for (i = 0; i < nr_pfns; i++) {
+ if (val == pfns[i]) {
+ count++;
+ break;
+ }
+ }
+ continue;
+ }
+
+ s = strstr(line, "mm_collapse_candidate:");
+ if (s) {
+ if (!strstr(s, "pass=install") ||
+ !strstr(s, "result=succeeded"))
+ continue;
+ o = strstr(s, "addr=");
+ if (!o || sscanf(o, "addr=0x%lx", &val) != 1 ||
+ val != addr)
+ continue;
+ o = strstr(s, "order=");
+ if (!o || sscanf(o, "order=%u", &ord) != 1 ||
+ ord != order)
+ continue;
+ count++;
+ }
+ }
+ fclose(fp);
+ return count;
+}
+
+static void one_step(int iteration)
+{
+ const size_t window = getpagesize() << TARGET_ORDER;
+ const int nr_pages = 1 << TARGET_ORDER;
+ unsigned long pfns[1 << TARGET_ORDER];
+ bool collapsed;
+ int attributed;
+ char *p;
+ int i;
+
+ p = mmap(BASE_ADDR, hpage_pmd_size, PROT_READ | PROT_WRITE,
+ MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ if (p != BASE_ADDR)
+ ksft_exit_fail_msg("Failed to allocate VMA at %p\n",
+ BASE_ADDR);
+
+ /* Prepare one window; record its source PFNs. */
+ for (i = 0; i < nr_pages; i++) {
+ p[i * getpagesize()] = i + 1;
+ pfns[i] = pagemap_get_pfn(pagemap_fd, p + i * getpagesize());
+ if (pfns[i] == -1UL)
+ ksft_exit_fail_msg("Source page not present\n");
+ }
+
+ if (tracing_events_start("huge_memory"))
+ ksft_exit_fail_msg("Cannot enable huge_memory events\n");
+
+ madvise(p, hpage_pmd_size, MADV_HUGEPAGE);
+ /* Wait up to 120 seconds for the pass to complete. */
+ if (!khugepaged_full_pass(120))
+ ksft_exit_fail_msg("khugepaged did not complete a full pass\n");
+
+ tracing_events_stop("huge_memory");
+
+ collapsed = is_range_backed_by_folio_orders(p, window, TARGET_ORDER,
+ pagemap_fd, kpageflags_fd);
+ attributed = count_attributed(pfns, nr_pages, (unsigned long)p,
+ TARGET_ORDER);
+
+ ksft_test_result(collapsed && attributed == 1,
+ "step %d: window collapsed, %d attributed result(s)\n",
+ iteration, attributed);
+
+ munmap(p, hpage_pmd_size);
+}
+
+int main(void)
+{
+ struct thp_settings settings;
+ int i;
+
+ ksft_print_header();
+
+ if (!thp_available())
+ ksft_exit_skip("Transparent Hugepages not available\n");
+ if (!(thp_supported_orders() & (1UL << TARGET_ORDER)))
+ ksft_exit_skip("Order %d is not a supported anon THP order\n",
+ TARGET_ORDER);
+
+ hpage_pmd_size = read_pmd_pagesize();
+ if (!hpage_pmd_size)
+ ksft_exit_fail_msg("Reading PMD pagesize failed\n");
+ pagemap_fd = open("/proc/self/pagemap", O_RDONLY);
+ if (pagemap_fd < 0)
+ ksft_exit_fail_perror("open(\"/proc/self/pagemap\")");
+ kpageflags_fd = open("/proc/kpageflags", O_RDONLY);
+ if (kpageflags_fd < 0)
+ ksft_exit_skip("open(\"/proc/kpageflags\") requires root\n");
+ if (tracing_events_start("huge_memory"))
+ ksft_exit_skip("tracefs unavailable\n");
+ tracing_events_stop("huge_memory");
+
+ ksft_set_plan(NR_ITERATIONS);
+
+ thp_save_settings();
+ thp_read_settings(&settings);
+ settings.thp_enabled = THP_MADVISE;
+ settings.thp_defrag = THP_DEFRAG_ALWAYS;
+ settings.khugepaged.defrag = 1;
+ settings.khugepaged.scan_sleep_millisecs = 60000;
+ settings.khugepaged.alloc_sleep_millisecs = 60000;
+ settings.khugepaged.max_ptes_none = (hpage_pmd_size / getpagesize()) - 1;
+ /* One wake must complete one full pass; see khugepaged_full_pass(). */
+ settings.khugepaged.pages_to_scan = 1UL << 24;
+ for (i = 0; i < NR_ORDERS; i++)
+ settings.hugepages[i].enabled = THP_NEVER;
+ settings.hugepages[TARGET_ORDER].enabled = THP_INHERIT;
+ /* Base of the settings stack; the bottom entry is never popped. */
+ thp_push_settings(&settings);
+
+ for (i = 0; i < NR_ITERATIONS; i++)
+ one_step(i);
+
+ thp_restore_settings();
+
+ ksft_finished();
+}
diff --git a/tools/testing/selftests/mm/run_vmtests.sh b/tools/testing/selftests/mm/run_vmtests.sh
index 687d115e3bd80..f826cf940c3d4 100755
--- a/tools/testing/selftests/mm/run_vmtests.sh
+++ b/tools/testing/selftests/mm/run_vmtests.sh
@@ -402,10 +402,27 @@ CATEGORY="pfnmap" run_test ./pfnmap
# COW tests
CATEGORY="cow" run_test ./cow
+CATEGORY="thp" run_test ./folio_order_check
+
+
+CATEGORY="thp" run_test ./khugepaged_sync_check
+
+CATEGORY="thp" run_test ./khugepaged_race -d 5 -m stepped
+
+CATEGORY="thp" run_test ./khugepaged_race -d 5 -m free
+
+CATEGORY="thp" run_test ./khugepaged_race -d 5 -m madvise
+
+CATEGORY="thp" run_test ./khugepaged_race -d 5 -m stepped -z
+
+CATEGORY="thp" run_test ./khugepaged_race -d 5 -m stepped -p
+
CATEGORY="thp" run_test ./khugepaged
CATEGORY="thp" run_test ./khugepaged -s 2
+CATEGORY="thp" run_test ./khugepaged -o 2 khugepaged:anon
+
CATEGORY="thp" run_test ./khugepaged all:shmem
CATEGORY="thp" run_test ./khugepaged -s 4 all:shmem
diff --git a/tools/testing/selftests/mm/split_huge_page_test.c b/tools/testing/selftests/mm/split_huge_page_test.c
index 32b991472f744..9b3885bd001be 100644
--- a/tools/testing/selftests/mm/split_huge_page_test.c
+++ b/tools/testing/selftests/mm/split_huge_page_test.c
@@ -42,68 +42,6 @@ const char *kpageflags_proc = "/proc/kpageflags";
int pagemap_fd;
int kpageflags_fd;
-static bool is_backed_by_folio(char *vaddr, int order, int pagemap_fd,
- int kpageflags_fd)
-{
- const uint64_t folio_head_flags = KPF_THP | KPF_COMPOUND_HEAD;
- const uint64_t folio_tail_flags = KPF_THP | KPF_COMPOUND_TAIL;
- const unsigned long nr_pages = 1UL << order;
- unsigned long pfn_head;
- uint64_t pfn_flags;
- unsigned long pfn;
- unsigned long i;
-
- pfn = pagemap_get_pfn(pagemap_fd, vaddr);
-
- /* non present page */
- if (pfn == -1UL)
- return false;
-
- if (pageflags_get(pfn, kpageflags_fd, &pfn_flags))
- goto fail;
-
- /* check for order-0 pages */
- if (!order) {
- if (pfn_flags & (folio_head_flags | folio_tail_flags))
- return false;
- return true;
- }
-
- /* non THP folio */
- if (!(pfn_flags & KPF_THP))
- return false;
-
- pfn_head = pfn & ~(nr_pages - 1);
-
- if (pageflags_get(pfn_head, kpageflags_fd, &pfn_flags))
- goto fail;
-
- /* head PFN has no compound_head flag set */
- if ((pfn_flags & folio_head_flags) != folio_head_flags)
- return false;
-
- /* check all tail PFN flags */
- for (i = 1; i < nr_pages; i++) {
- if (pageflags_get(pfn_head + i, kpageflags_fd, &pfn_flags))
- goto fail;
- if ((pfn_flags & folio_tail_flags) != folio_tail_flags)
- return false;
- }
-
- /*
- * check the PFN after this folio, but if its flags cannot be obtained,
- * assume this folio has the expected order
- */
- if (pageflags_get(pfn_head + nr_pages, kpageflags_fd, &pfn_flags))
- return true;
-
- /* If we find another tail page, then the folio is larger. */
- return (pfn_flags & folio_tail_flags) != folio_tail_flags;
-fail:
- ksft_exit_fail_msg("Failed to get folio info\n");
- return false;
-}
-
static int vaddr_pageflags_get(char *vaddr, int pagemap_fd, int kpageflags_fd,
uint64_t *flags)
{
diff --git a/tools/testing/selftests/mm/vm_util.c b/tools/testing/selftests/mm/vm_util.c
index ef1ea11981a74..886fb3de9c011 100644
--- a/tools/testing/selftests/mm/vm_util.c
+++ b/tools/testing/selftests/mm/vm_util.c
@@ -303,6 +303,163 @@ int pageflags_get(unsigned long pfn, int kpageflags_fd, uint64_t *flags)
return 0;
}
+bool is_backed_by_folio(char *vaddr, int order, int pagemap_fd,
+ int kpageflags_fd)
+{
+ const uint64_t folio_head_flags = KPF_THP | KPF_COMPOUND_HEAD;
+ const uint64_t folio_tail_flags = KPF_THP | KPF_COMPOUND_TAIL;
+ const unsigned long nr_pages = 1UL << order;
+ unsigned long pfn_head;
+ uint64_t pfn_flags;
+ unsigned long pfn;
+ unsigned long i;
+
+ pfn = pagemap_get_pfn(pagemap_fd, vaddr);
+
+ /* non present page */
+ if (pfn == -1UL)
+ return false;
+
+ if (pageflags_get(pfn, kpageflags_fd, &pfn_flags))
+ goto fail;
+
+ /* check for order-0 pages */
+ if (!order) {
+ if (pfn_flags & (folio_head_flags | folio_tail_flags))
+ return false;
+ return true;
+ }
+
+ /* non THP folio */
+ if (!(pfn_flags & KPF_THP))
+ return false;
+
+ pfn_head = pfn & ~(nr_pages - 1);
+
+ if (pageflags_get(pfn_head, kpageflags_fd, &pfn_flags))
+ goto fail;
+
+ /* head PFN has no compound_head flag set */
+ if ((pfn_flags & folio_head_flags) != folio_head_flags)
+ return false;
+
+ /* check all tail PFN flags */
+ for (i = 1; i < nr_pages; i++) {
+ if (pageflags_get(pfn_head + i, kpageflags_fd, &pfn_flags))
+ goto fail;
+ if ((pfn_flags & folio_tail_flags) != folio_tail_flags)
+ return false;
+ }
+
+ /*
+ * check the PFN after this folio, but if its flags cannot be obtained,
+ * assume this folio has the expected order
+ */
+ if (pageflags_get(pfn_head + nr_pages, kpageflags_fd, &pfn_flags))
+ return true;
+
+ /* If we find another tail page, then the folio is larger. */
+ return (pfn_flags & folio_tail_flags) != folio_tail_flags;
+fail:
+ ksft_exit_fail_msg("Failed to get folio info\n");
+ return false;
+}
+
+/*
+ * Check whether the range [start, start + len) is backed by folios of
+ * exactly @order, mapped at their natural alignment.
+ *
+ * is_backed_by_folio() classifies the folio backing one page; here we
+ * additionally require that each order-aligned window of the range maps
+ * one such folio head-to-tail: the VA range must be naturally aligned,
+ * each window's PFN run must be contiguous, and the first PFN must be
+ * the (naturally aligned) folio head.
+ *
+ * This is the check "did this range collapse into order-@order folios":
+ * a window assembled from parts of several folios, or mapping a folio
+ * shifted from its natural position, fails.
+ */
+bool is_range_backed_by_folio_orders(char *start, size_t len, int order,
+ int pagemap_fd, int kpageflags_fd)
+{
+ const unsigned long nr_pages = 1UL << order;
+ const size_t window = nr_pages * psize();
+ char *vaddr;
+
+ if ((uintptr_t)start % window || len % window)
+ return false;
+
+ for (vaddr = start; vaddr < start + len; vaddr += window) {
+ unsigned long pfn = pagemap_get_pfn(pagemap_fd, vaddr);
+ unsigned long i;
+
+ /* Not present, or not mapping the folio head. */
+ if (pfn == -1UL || pfn % nr_pages)
+ return false;
+
+ for (i = 1; i < nr_pages; i++) {
+ if (pagemap_get_pfn(pagemap_fd, vaddr + i * psize()) !=
+ pfn + i)
+ return false;
+ }
+
+ if (!is_backed_by_folio(vaddr, order, pagemap_fd,
+ kpageflags_fd))
+ return false;
+ }
+
+ return true;
+}
+
+#define TRACEFS_ROOT "/sys/kernel/tracing"
+
+static int tracing_events_write(const char *subsys, const char *val)
+{
+ char path[256];
+ int fd;
+
+ snprintf(path, sizeof(path), TRACEFS_ROOT "/events/%s/enable",
+ subsys);
+ fd = open(path, O_WRONLY);
+ if (fd < 0)
+ return -1;
+ if (write(fd, val, 1) != 1) {
+ close(fd);
+ return -1;
+ }
+ close(fd);
+ return 0;
+}
+
+/*
+ * Enable one ftrace event subsystem (e.g. "huge_memory") and clear the
+ * trace buffer. Returns -1 if tracefs is unavailable; parse the results
+ * via tracing_open_trace() after tracing_events_stop().
+ */
+int tracing_events_start(const char *subsys)
+{
+ int fd;
+
+ if (tracing_events_write(subsys, "1"))
+ return -1;
+
+ fd = open(TRACEFS_ROOT "/trace", O_WRONLY | O_TRUNC);
+ if (fd < 0)
+ return -1;
+ close(fd);
+ return 0;
+}
+
+int tracing_events_stop(const char *subsys)
+{
+ return tracing_events_write(subsys, "0");
+}
+
+FILE *tracing_open_trace(void)
+{
+ return fopen(TRACEFS_ROOT "/trace", "r");
+}
+
/* If `ioctls' non-NULL, the allowed ioctls will be returned into the var */
int uffd_register_with_ioctls(int uffd, void *addr, uint64_t len,
bool miss, bool wp, bool minor, uint64_t *ioctls)
diff --git a/tools/testing/selftests/mm/vm_util.h b/tools/testing/selftests/mm/vm_util.h
index 7799154b67eed..4ff5a1c5ab8ed 100644
--- a/tools/testing/selftests/mm/vm_util.h
+++ b/tools/testing/selftests/mm/vm_util.h
@@ -95,6 +95,10 @@ bool check_huge_file(void *addr, int nr_hpages, uint64_t hpage_size);
bool check_huge_shmem(void *addr, int nr_hpages, uint64_t hpage_size);
int64_t allocate_transhuge(void *ptr, int pagemap_fd);
int pageflags_get(unsigned long pfn, int kpageflags_fd, uint64_t *flags);
+bool is_backed_by_folio(char *vaddr, int order, int pagemap_fd,
+ int kpageflags_fd);
+bool is_range_backed_by_folio_orders(char *start, size_t len, int order,
+ int pagemap_fd, int kpageflags_fd);
int uffd_register(int uffd, void *addr, uint64_t len,
bool miss, bool wp, bool minor);
@@ -111,6 +115,9 @@ int close_procmap(struct procmap_fd *procmap);
int write_sysfs(const char *file_path, unsigned long val);
int read_sysfs(const char *file_path, unsigned long *val);
bool softdirty_supported(void);
+int tracing_events_start(const char *subsys);
+int tracing_events_stop(const char *subsys);
+FILE *tracing_open_trace(void);
static inline int open_self_procmap(struct procmap_fd *procmap_out)
{
|
| 3/2 | 2026/08/03 01:03 | llm | patch-evaluator |
0mModel:gemini-3.1-pro-preview Args: null Results: null Tokens: input: 24835 output: 64 thoughts: 699 Thoughts: **WorthFuzzing=false: A Quick Review** Okay, so I'm looking at this patch series, and it's all about modifying stuff within `tools/testing/selftests/mm/`. Right off the bat, that screams *not kernel code* to me, but I need to be thorough. These are userspace tests. I always triple-check. The instructions are pretty clear: modifications to selftests alone shouldn't trigger fuzzing. The question is: do the instructions capture this? Let me quickly scan the diff again. Nope, just double-checking, it's just `tools/testing/selftests/mm/`. The specific files are: `.gitignore`, `Makefile`, `folio_order_check.c`, `hugepage_settings.c` and `.h`, `khugepaged.c` and `_race.c` and `_sync_check.c`, `run_vmtests.sh`, `split_huge_page_test.c`, `vm_util.c` and `.h`. All contained within the `tools/testing/selftests/mm/` directory. Okay, so there's no kernel code being touched. No functional changes to the kernel, period. The prompt is crystal clear: I'm reviewing patches to see if they functionally change the kernel in a way that warrants fuzzing. Since this is *only* modifying userspace selftests, the answer is a resounding *no*. I'm returning `WorthFuzzing=false`. |
| 4/2 | 2026/08/03 01:03 | tool | set-results |
0mArgs:{
"EnableConfigs": [],
"FocusSymbols": [],
"Reasoning": "The patch only modifies userspace selftests (tools/testing/selftests/mm/*) and does not make any functional changes to the kernel itself.",
"WorthFuzzing": false
}Results: {
"EnableConfigs": null,
"FocusSymbols": [],
"Reasoning": "The patch only modifies userspace selftests (tools/testing/selftests/mm/*) and does not make any functional changes to the kernel itself.",
"WorthFuzzing": false
} |
| Total Calls | Total Tokens | Avg Tokens | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|
| Total Calls | Total Duration (Seconds) | Avg Duration (Seconds) |
|---|