AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/09/20 07:11 flow patch-triage
3m Args:
null

Results:
{
  "EnableConfigs": [
    "TRANSPARENT_HUGEPAGE",
    "SHMEM"
  ],
  "FocusSymbols": [
    "collapse_file",
    "collapse_scan_file",
    "mthp_collapse",
    "collapse_run_pmd",
    "collapse_scan_pmd",
    "collapse_possible_orders",
    "shmem_hpage_enabled",
    "shmem_parse_huge"
  ],
  "KMSANReasoning": "The patch series extends khugepaged to support collapsing multi-size Transparent Huge Pages (mTHP) for shmem and file-backed mappings. The changes include generalizing collapse_file() to arbitrary THP orders, scanning file mappings to build eligible PTE bitmaps, adjusting sysfs/boot parsing for shmem huge page policies, and inlining hugepage_madvise() into madvise_vma_behavior().\n\nKMSAN vs KASAN Applicability Analysis:\n1. Uninitialized Memory: No new uninitialized stack or heap variables are introduced. In collapse_scan_file(), all local variables and scan state are explicitly initialized or cleared via collapse_scan_reset() (which calls bitmap_zero() and memset()). Newly allocated collapse folios have unpopulated pages zeroed with clear_highpage() and valid pages copied from uptodate folios.\n2. Userspace Info-leaks: The changes do not introduce or modify copy_to_user(), put_user(), netlink attributes, socket options, or BPF buffers that could leak uninitialized kernel memory to user space.\n3. Bug Profile: Potential bugs in this area are locking issues, folio refcounting discrepancies, page table synchronization races, or out-of-bounds page indexing. These are detected by KASAN, LOCKDEP, and CONFIG_DEBUG_VM/CONFIG_DEBUG_PAGEALLOC, not KMSAN.\n\nTherefore, a dedicated KMSAN fuzzing session is not warranted for this patch series.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch extends khugepaged to support multi-size Transparent Huge Pages (mTHP) for file and shmem mappings. It modifies core MM collapse routines (collapse_file, collapse_scan_file, mthp_collapse, collapse_run_pmd) to handle non-PMD folio orders, adjusts page cache insertion and LRU accounting, and adds runtime assertions (such as VM_WARN_ON_ONCE(!file)). These changes touch core memory management code reachable from userspace via madvise(MADV_COLLAPSE) and background khugepaged scanning.",
  "WorthFuzzing": true
}

1/1 2026/09/20 07:11 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit e0ea9a9e1bc3968fefab125ca103ef9197c81d03\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Sun Sep 20 07:11:47 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/admin-guide/mm/transhuge.rst b/Documentation/admin-guide/mm/transhuge.rst\nindex b187d618452f4..0a8265d1cb553 100644\n--- a/Documentation/admin-guide/mm/transhuge.rst\n+++ b/Documentation/admin-guide/mm/transhuge.rst\n@@ -389,8 +389,8 @@ is not defined within a valid ``thp_anon``, its policy will default to\n Similarly to ``transparent_hugepage``, you can control the hugepage\n allocation policy for the internal shmem mount by using the kernel parameter\n ``transparent_hugepage_shmem=\u003cpolicy\u003e``, where ``\u003cpolicy\u003e`` is one of the\n-seven valid policies for shmem (``always``, ``within_size``, ``advise``,\n-``never``, ``deny``, and ``force``).\n+four valid policies for shmem (``always``, ``within_size``, ``advise``,\n+``never``).\n \n Similarly to ``transparent_hugepage_shmem``, you can control the default\n hugepage allocation policy for the tmpfs mount by using the kernel parameter\ndiff --git a/include/linux/huge_mm.h b/include/linux/huge_mm.h\nindex 8ca0fa3be2acb..334c387ad9976 100644\n--- a/include/linux/huge_mm.h\n+++ b/include/linux/huge_mm.h\n@@ -508,8 +508,6 @@ change_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,\n \t\t\t__split_huge_pud(__vma, __pud, __address);\t\\\n \t}  while (0)\n \n-int hugepage_madvise(struct vm_area_struct *vma, vm_flags_t *vm_flags,\n-\t\t     int advice);\n void vma_adjust_trans_huge(struct vm_area_struct *vma, unsigned long start,\n \t\t\t   unsigned long end, struct vm_area_struct *next);\n spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma);\n@@ -707,12 +705,6 @@ static inline bool unmap_huge_pmd_locked(struct vm_area_struct *vma,\n #define split_huge_pud(__vma, __pmd, __address)\t\\\n \tdo { } while (0)\n \n-static inline int hugepage_madvise(struct vm_area_struct *vma,\n-\t\t\t\t   vm_flags_t *vm_flags, int advice)\n-{\n-\treturn -EINVAL;\n-}\n-\n static inline void vma_adjust_trans_huge(struct vm_area_struct *vma,\n \t\t\t\t\t unsigned long start,\n \t\t\t\t\t unsigned long end,\ndiff --git a/include/linux/shmem_fs.h b/include/linux/shmem_fs.h\nindex a7c7a96a7cbf9..9f2036f58bb8f 100644\n--- a/include/linux/shmem_fs.h\n+++ b/include/linux/shmem_fs.h\n@@ -135,7 +135,7 @@ int shmem_unuse(unsigned int type);\n unsigned long shmem_allowable_huge_orders(struct inode *inode,\n \t\t\t\tstruct vm_area_struct *vma, pgoff_t index,\n \t\t\t\tloff_t write_end, bool shmem_huge_force);\n-bool shmem_hpage_pmd_enabled(void);\n+bool shmem_hpage_enabled(void);\n #else\n static inline unsigned long shmem_allowable_huge_orders(struct inode *inode,\n \t\t\t\tstruct vm_area_struct *vma, pgoff_t index,\n@@ -144,7 +144,7 @@ static inline unsigned long shmem_allowable_huge_orders(struct inode *inode,\n \treturn 0;\n }\n \n-static inline bool shmem_hpage_pmd_enabled(void)\n+static inline bool shmem_hpage_enabled(void)\n {\n \treturn false;\n }\ndiff --git a/mm/collapse.h b/mm/collapse.h\nindex e529699652623..d2fff6b5e1ec4 100644\n--- a/mm/collapse.h\n+++ b/mm/collapse.h\n@@ -8,7 +8,8 @@\n #include \u003clinux/types.h\u003e\n \n #define COLLAPSE_MAX_PTES_LIMIT\t\t(HPAGE_PMD_NR - 1)\n-#define COLLAPSE_MIN_MTHP_ORDER\t\t2\n+#define COLLAPSE_MIN_ANON_MTHP_ORDER\t\t2\n+#define COLLAPSE_MIN_FILE_MTHP_ORDER\t\t1\n \n enum scan_result {\n \tSCAN_FAIL,\ndiff --git a/mm/khugepaged.c b/mm/khugepaged.c\nindex a3a9e4d93b461..4b5e1f8ddf87a 100644\n--- a/mm/khugepaged.c\n+++ b/mm/khugepaged.c\n@@ -84,6 +84,10 @@ static struct khugepaged_scan khugepaged_scan = {\n \t.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),\n };\n \n+static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n+\t\tstruct file *file, pgoff_t start,\n+\t\tstruct collapse_control *cc, int order);\n+\n #ifdef CONFIG_SYSFS\n static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,\n \t\t\t\t\t struct kobj_attribute *attr,\n@@ -302,6 +306,14 @@ static bool pte_none_or_zero(pte_t pte)\n \treturn pte_present(pte) \u0026\u0026 is_zero_pfn(pte_pfn(pte));\n }\n \n+static unsigned int collapse_min_mthp_order(struct file *file)\n+{\n+\tif (file)\n+\t\treturn COLLAPSE_MIN_FILE_MTHP_ORDER;\n+\n+\treturn COLLAPSE_MIN_ANON_MTHP_ORDER;\n+}\n+\n /**\n  * collapse_max_ptes_none - Calculate maximum allowed empty PTEs or PTEs mapping\n  * the shared zeropage for the given collapse operation.\n@@ -380,28 +392,6 @@ static unsigned int collapse_max_ptes_swap(struct collapse_control *cc,\n \treturn cc-\u003epolicy.max_ptes_swap;\n }\n \n-int hugepage_madvise(struct vm_area_struct *vma,\n-\t\t     vm_flags_t *vm_flags, int advice)\n-{\n-\tswitch (advice) {\n-\tcase MADV_HUGEPAGE:\n-\t\t*vm_flags \u0026= ~VM_NOHUGEPAGE;\n-\t\t*vm_flags |= VM_HUGEPAGE;\n-\t\tbreak;\n-\tcase MADV_NOHUGEPAGE:\n-\t\t*vm_flags \u0026= ~VM_HUGEPAGE;\n-\t\t*vm_flags |= VM_NOHUGEPAGE;\n-\t\t/*\n-\t\t * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning\n-\t\t * this vma even if we leave the mm registered in khugepaged if\n-\t\t * it got registered before VM_NOHUGEPAGE was set.\n-\t\t */\n-\t\tbreak;\n-\t}\n-\n-\treturn 0;\n-}\n-\n int __init khugepaged_init(void)\n {\n \tmm_slot_cache = KMEM_CACHE(mm_slot, 0);\n@@ -457,7 +447,7 @@ static bool hugepage_enabled(void)\n \t\treturn true;\n \tif (anon_hpage_enabled())\n \t\treturn true;\n-\tif (shmem_hpage_pmd_enabled())\n+\tif (shmem_hpage_enabled())\n \t\treturn true;\n \treturn false;\n }\n@@ -503,9 +493,14 @@ unsigned long collapse_possible_orders(struct vm_area_struct *vma,\n {\n \tunsigned long orders;\n \n-\t/* If khugepaged is scanning an anonymous vma, allow mTHP collapse */\n+\t/*\n+\t * If khugepaged is scanning an anonymous or shmem vma,\n+\t * allow mTHP collapse.\n+\t */\n \tif ((tva_flags == TVA_KHUGEPAGED) \u0026\u0026 vma_is_anonymous(vma))\n \t\torders = THP_ORDERS_ALL_ANON;\n+\telse if ((tva_flags == TVA_KHUGEPAGED) \u0026\u0026 vma_is_shmem(vma))\n+\t\torders = THP_ORDERS_ALL_FILE_DEFAULT;\n \telse\n \t\torders = BIT(HPAGE_PMD_ORDER);\n \n@@ -1466,7 +1461,11 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long addres\n \t\t\tenum scan_result ret;\n \n \t\t\tcollapse_address = address + offset * PAGE_SIZE;\n-\t\t\tret = collapse_huge_page(mm, collapse_address, cc, order);\n+\t\t\tif (cc-\u003escan_file)\n+\t\t\t\tret = collapse_file(mm, collapse_address, cc-\u003escan_file,\n+\t\t\t\t\t\tcc-\u003escan_pgoff + offset, cc, order);\n+\t\t\telse\n+\t\t\t\tret = collapse_huge_page(mm, collapse_address, cc, order);\n \n \t\t\tswitch (ret) {\n \t\t\t/* Cases where we continue to next collapse candidate */\n@@ -1474,6 +1473,13 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long addres\n \t\t\t\tcollapsed += nr_ptes;\n \t\t\t\tfallthrough;\n \t\t\tcase SCAN_PTE_MAPPED_HUGEPAGE:\n+\t\t\t\t/*\n+\t\t\t\t * Return SCAN_PTE_MAPPED_HUGEPAGE to call\n+\t\t\t\t * collapse_pte_mapped_thp() if the page cache\n+\t\t\t\t * already holds the PMD folio.\n+\t\t\t\t */\n+\t\t\t\tif (order == HPAGE_PMD_ORDER)\n+\t\t\t\t\tlast_result = ret;\n \t\t\t\tgoto next_offset;\n \t\t\t/* Cases where lower orders might still succeed */\n \t\t\tcase SCAN_ALLOC_HUGE_PAGE_FAIL:\n@@ -1507,7 +1513,7 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long addres\n \t\t * any smaller order enabled. When at the smallest order\n \t\t * we must always move to the next offset.\n \t\t */\n-\t\tif (order \u003e COLLAPSE_MIN_MTHP_ORDER \u0026\u0026\n+\t\tif (order \u003e collapse_min_mthp_order(cc-\u003escan_file) \u0026\u0026\n \t\t    (cc-\u003escan_orders \u0026 GENMASK(order - 1, 0))) {\n \t\t\torder--;\n \t\t\tcontinue;\n@@ -2160,6 +2166,7 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)\n  * @file: file that collapse on\n  * @start: collapse start address\n  * @cc: collapse context and scratchpad\n+ * @order: folio order being collapsed to\n  *\n  * Basic scheme is simple, details are more complex:\n  *  - allocate and lock a new huge page;\n@@ -2178,29 +2185,29 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)\n  *    + unlock and free huge page;\n  */\n static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n-\t\tstruct file *file, pgoff_t start, struct collapse_control *cc)\n+\t\tstruct file *file, pgoff_t start, struct collapse_control *cc,\n+\t\tint order)\n {\n+\tconst unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, order);\n \tstruct address_space *mapping = file-\u003ef_mapping;\n+\tconst unsigned long nr_pages = 1UL \u003c\u003c order;\n \tstruct page *dst;\n \tstruct folio *folio, *tmp, *new_folio;\n \tunsigned long new_pfn = -1;\n-\tpgoff_t index = 0, end = start + HPAGE_PMD_NR;\n+\tpgoff_t index = 0, end = start + nr_pages;\n \tLIST_HEAD(pagelist);\n-\tXA_STATE_ORDER(xas, \u0026mapping-\u003ei_pages, start, HPAGE_PMD_ORDER);\n+\tXA_STATE_ORDER(xas, \u0026mapping-\u003ei_pages, start, order);\n \tenum scan_result result = SCAN_SUCCEED;\n \tint nr_none = 0;\n \tbool is_shmem = shmem_file(file);\n \n \t/*\n-\t * MADV_COLLAPSE ignores shmem huge config, so do not check shmem\n-\t *\n-\t * TODO: once shmem always calls mapping_set_large_folios() on its\n-\t * mapping, the shmem check can be removed.\n+\t * MADV_COLLAPSE ignores shmem huge config, so do not check shmem.\n \t */\n-\tVM_WARN_ON_ONCE(!is_shmem \u0026\u0026 !mapping_pmd_folio_support(mapping));\n-\tVM_WARN_ON_ONCE(start \u0026 (HPAGE_PMD_NR - 1));\n+\tVM_WARN_ON_ONCE(!mapping_pmd_folio_support(mapping));\n+\tVM_WARN_ON_ONCE(start \u0026 (nr_pages - 1));\n \n-\tresult = alloc_charge_folio(\u0026new_folio, mm, cc, HPAGE_PMD_ORDER);\n+\tresult = alloc_charge_folio(\u0026new_folio, mm, cc, order);\n \tif (result != SCAN_SUCCEED)\n \t\tgoto out;\n \tnew_pfn = folio_pfn(new_folio);\n@@ -2247,13 +2254,33 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n \t\t\t\t\t\tgoto xa_locked;\n \t\t\t\t\t}\n \t\t\t\t}\n-\t\t\t\tnr_none++;\n+\n+\t\t\t\tif (++nr_none \u003e max_ptes_none) {\n+\t\t\t\t\tresult = SCAN_EXCEED_NONE_PTE;\n+\t\t\t\t\tcount_collapse_event(order, THP_SCAN_EXCEED_NONE_PTE,\n+\t\t\t\t\t\t\tMTHP_STAT_COLLAPSE_EXCEED_NONE);\n+\t\t\t\t\tgoto xa_locked;\n+\t\t\t\t}\n+\n \t\t\t\tindex++;\n \t\t\t\tcontinue;\n \t\t\t}\n \n \t\t\tif (xa_is_value(folio) || !folio_test_uptodate(folio)) {\n \t\t\t\txas_unlock_irq(\u0026xas);\n+\n+\t\t\t\t/*\n+\t\t\t\t * TODO: Support swapin without leading to further mTHP\n+\t\t\t\t * collapses. Currently bringing in new pages via swapin may\n+\t\t\t\t * cause a future higher order collapse on a rescan of the same\n+\t\t\t\t * range.\n+\t\t\t\t */\n+\t\t\t\tif (!is_pmd_order(order)) {\n+\t\t\t\t\tcount_mthp_stat(order, MTHP_STAT_COLLAPSE_EXCEED_SWAP);\n+\t\t\t\t\tresult = SCAN_EXCEED_SWAP_PTE;\n+\t\t\t\t\tgoto xa_unlocked;\n+\t\t\t\t}\n+\n \t\t\t\t/* swap in or instantiate fallocated page */\n \t\t\t\tif (shmem_get_folio(mapping-\u003ehost, index, 0,\n \t\t\t\t\t\t\u0026folio, SGP_NOALLOC)) {\n@@ -2337,6 +2364,15 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n \t\t\tgoto out_unlock;\n \t\t}\n \n+\t\t/*\n+\t\t * If the folio order is greater than the collapse order, there is\n+\t\t * no need to continue attempting to collapse.\n+\t\t */\n+\t\tif (folio_order(folio) \u003e= order) {\n+\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n+\t\t\tgoto out_unlock;\n+\t\t}\n+\n \t\tif (folio_mapping(folio) != mapping) {\n \t\t\tresult = SCAN_TRUNCATED;\n \t\t\tgoto out_unlock;\n@@ -2532,12 +2568,13 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n \t}\n \n \tif (is_shmem) {\n-\t\tlruvec_stat_mod_folio(new_folio, NR_SHMEM, HPAGE_PMD_NR);\n-\t\tlruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);\n-\t} else {\n+\t\tlruvec_stat_mod_folio(new_folio, NR_SHMEM, nr_pages);\n+\t\tif (is_pmd_order(order))\n+\t\t\tlruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);\n+\t} else if (is_pmd_order(order)) {\n \t\tlruvec_stat_mod_folio(new_folio, NR_FILE_THPS, HPAGE_PMD_NR);\n \t}\n-\tlruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, HPAGE_PMD_NR);\n+\tlruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, nr_pages);\n \n \t/*\n \t * Mark new_folio as uptodate before inserting it into the\n@@ -2545,23 +2582,24 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n \t * unwritten page.\n \t */\n \tfolio_mark_uptodate(new_folio);\n-\tfolio_ref_add(new_folio, HPAGE_PMD_NR - 1);\n+\tfolio_ref_add(new_folio, nr_pages - 1);\n \n \tif (is_shmem)\n \t\tfolio_mark_dirty(new_folio);\n \tfolio_add_lru(new_folio);\n \n \t/* Join all the small entries into a single multi-index entry. */\n-\txas_set_order(\u0026xas, start, HPAGE_PMD_ORDER);\n+\txas_set_order(\u0026xas, start, order);\n \txas_store(\u0026xas, new_folio);\n \tWARN_ON_ONCE(xas_error(\u0026xas));\n \txas_unlock_irq(\u0026xas);\n \n \t/*\n-\t * Remove pte page tables, so we can re-fault the page as huge.  A\n-\t * caller that wants the PMD mapped now is told to go and do that.\n+\t * Remove pte page tables for PMD-sized THP collapse, so we can\n+\t * re-fault the page as huge.\n \t */\n-\tretract_page_tables(mapping, start);\n+\tif (is_pmd_order(order))\n+\t\tretract_page_tables(mapping, start);\n \tif (cc-\u003epolicy.install_pmd)\n \t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n \tfolio_unlock(new_folio);\n@@ -2607,27 +2645,38 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n \tfolio_put(new_folio);\n out:\n \tVM_BUG_ON(!list_empty(\u0026pagelist));\n-\ttrace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, HPAGE_PMD_NR, result);\n+\ttrace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, nr_pages, result);\n \treturn result;\n }\n \n-static enum scan_result collapse_scan_file(struct mm_struct *mm,\n-\t\tunsigned long addr, struct file *file, pgoff_t start,\n-\t\tstruct collapse_control *cc)\n+static enum scan_result collapse_scan_file(struct vm_area_struct *vma,\n+\t\tunsigned long addr, struct collapse_control *cc,\n+\t\tunsigned long enabled_orders)\n {\n-\tconst unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, HPAGE_PMD_ORDER);\n \tconst unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);\n+\tunsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, HPAGE_PMD_ORDER);\n+\tstruct file *file = vma-\u003evm_file;\n \tstruct folio *folio = NULL;\n \tstruct address_space *mapping = file-\u003ef_mapping;\n+\tpgoff_t start = linear_page_index(vma, addr);\n \tXA_STATE(xas, \u0026mapping-\u003ei_pages, start);\n \tint present, swap;\n \tint node = NUMA_NO_NODE;\n \tenum scan_result result = SCAN_SUCCEED;\n \tunsigned long failed_pfn = -1;\n+\tunsigned long nr_pages;\n+\tpgoff_t pgoff;\n \n \tpresent = 0;\n \tswap = 0;\n \tcollapse_scan_reset(cc);\n+\t/*\n+\t * If PMD is the only enabled order, enforce max_ptes_none, otherwise\n+\t * scan all pages to populate the bitmap for mTHP collapse.\n+\t */\n+\tif (enabled_orders != BIT(HPAGE_PMD_ORDER))\n+\t\tmax_ptes_none = COLLAPSE_MAX_PTES_LIMIT;\n+\n \trcu_read_lock();\n \txas_for_each(\u0026xas, folio, start + HPAGE_PMD_NR - 1) {\n \t\tif (xas_retry(\u0026xas, folio))\n@@ -2695,7 +2744,17 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,\n \t\t * is just too costly...\n \t\t */\n \n-\t\tpresent += folio_nr_pages(folio);\n+\t\tnr_pages = folio_nr_pages(folio);\n+\t\tpresent += nr_pages;\n+\n+\t\t/*\n+\t\t * If there are folios present, keep track of it in the bitmap\n+\t\t * for file/shmem mTHP collapse.\n+\t\t */\n+\t\tpgoff = max_t(pgoff_t, start, folio-\u003eindex) - start;\n+\t\tnr_pages = min_t(int, HPAGE_PMD_NR - pgoff, nr_pages);\n+\t\tbitmap_set(cc-\u003eeligible_ptes, pgoff, nr_pages);\n+\n \t\tfolio_put(folio);\n \n \t\tif (need_resched()) {\n@@ -2711,10 +2770,27 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,\n \n \tif (result == SCAN_SUCCEED \u0026\u0026 present \u003c HPAGE_PMD_NR - max_ptes_none) {\n \t\tresult = SCAN_EXCEED_NONE_PTE;\n-\t\tcount_vm_event(THP_SCAN_EXCEED_NONE_PTE);\n+\t\tcount_collapse_event(HPAGE_PMD_ORDER, THP_SCAN_EXCEED_NONE_PTE,\n+\t\t\t\tMTHP_STAT_COLLAPSE_EXCEED_NONE);\n+\t}\n+\n+\t/*\n+\t * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds\n+\t * the PMD folio, and retracting the PTE table is the run's job.\n+\t */\n+\tif (result == SCAN_SUCCEED || result == SCAN_PTE_MAPPED_HUGEPAGE) {\n+\t\t/*\n+\t\t * A file collapse works on the page cache and never sees a\n+\t\t * VMA, so take what it needs from this one while it is still\n+\t\t * here.\n+\t\t */\n+\t\tcc-\u003escan_file = get_file(file);\n+\t\tcc-\u003escan_pgoff = start;\n+\t\tcc-\u003escan_orders = enabled_orders;\n+\t\tcc-\u003escan_unmapped = swap;\n \t}\n \n-\ttrace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap,\n+\ttrace_mm_khugepaged_scan_file(vma-\u003evm_mm, failed_pfn, file, present, swap,\n \t\t\t\t      result);\n \treturn result;\n }\n@@ -2762,9 +2838,6 @@ enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n \t\tunsigned long addr, struct collapse_control *cc,\n \t\tunsigned long orders)\n {\n-\tenum scan_result result;\n-\tpgoff_t pgoff;\n-\n \tmmap_assert_locked(vma-\u003evm_mm);\n \t/* Whatever the last scan found has to have been run by now */\n \tcollapse_put_scan_file(cc);\n@@ -2772,22 +2845,7 @@ enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n \tif (vma_is_anonymous(vma))\n \t\treturn collapse_scan_anon_pmd(vma, addr, cc, orders);\n \n-\tpgoff = linear_page_index(vma, addr);\n-\tresult = collapse_scan_file(vma-\u003evm_mm, addr, vma-\u003evm_file, pgoff, cc);\n-\t/*\n-\t * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds\n-\t * the PMD folio, and retracting the PTE table is the run's job.\n-\t */\n-\tif (result != SCAN_SUCCEED \u0026\u0026 result != SCAN_PTE_MAPPED_HUGEPAGE)\n-\t\treturn result;\n-\n-\t/*\n-\t * A file collapse works on the page cache and never sees a VMA, so take\n-\t * what it needs from this one while it is still here.\n-\t */\n-\tcc-\u003escan_file = get_file(vma-\u003evm_file);\n-\tcc-\u003escan_pgoff = pgoff;\n-\treturn result;\n+\treturn collapse_scan_file(vma, addr, cc, orders);\n }\n \n /*\n@@ -2805,23 +2863,21 @@ enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,\n {\n \tstruct file *file = cc-\u003escan_file;\n \tbool triggered_wb = false;\n-\tpgoff_t pgoff;\n-\n-\tif (!file)\n-\t\treturn mthp_collapse(mm, addr, cc);\n-\n-\tcc-\u003escan_file = NULL;\n-\tpgoff = cc-\u003escan_pgoff;\n \n \t/* The scan found the PMD folio in place: nothing to collapse */\n \tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\n \t\tgoto retract;\n+\n retry:\n-\tresult = collapse_file(mm, addr, file, pgoff, cc);\n+\tresult = mthp_collapse(mm, addr, cc);\n+\t/* Just return the results for anonymous folio collapse. */\n+\tif (!file)\n+\t\treturn result;\n \n \t/* Dirty pages are worth a writeback and one more try, if asked for */\n \tif (cc-\u003epolicy.writeback_dirty \u0026\u0026 result == SCAN_PAGE_DIRTY_OR_WRITEBACK \u0026\u0026\n \t    !triggered_wb \u0026\u0026 mapping_can_writeback(file-\u003ef_mapping)) {\n+\t\tpgoff_t pgoff = cc-\u003escan_pgoff;\n \t\tconst loff_t lstart = (loff_t)pgoff \u003c\u003c PAGE_SHIFT;\n \t\tconst loff_t lend = lstart + HPAGE_PMD_SIZE - 1;\n \n@@ -2830,6 +2886,8 @@ enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,\n \t\tgoto retry;\n \t}\n retract:\n+\tcc-\u003escan_file = NULL;\n+\tVM_WARN_ON_ONCE(!file);\n \tfput(file);\n \n \t/*\ndiff --git a/mm/madvise.c b/mm/madvise.c\nindex eb491fa88325d..4150f6a8cf64c 100644\n--- a/mm/madvise.c\n+++ b/mm/madvise.c\n@@ -1598,10 +1598,12 @@ static int madvise_vma_behavior(struct madvise_behavior *madv_behavior)\n \t\t\tgoto out;\n \t\tbreak;\n \tcase MADV_HUGEPAGE:\n+\t\tnew_flags \u0026= ~VM_NOHUGEPAGE;\n+\t\tnew_flags |= VM_HUGEPAGE;\n+\t\tbreak;\n \tcase MADV_NOHUGEPAGE:\n-\t\terror = hugepage_madvise(vma, \u0026new_flags, behavior);\n-\t\tif (error)\n-\t\t\tgoto out;\n+\t\tnew_flags \u0026= ~VM_HUGEPAGE;\n+\t\tnew_flags |= VM_NOHUGEPAGE;\n \t\tbreak;\n \tcase __MADV_SET_ANON_VMA_NAME:\n \t\t/* Only anonymous mappings can be named */\ndiff --git a/mm/shmem.c b/mm/shmem.c\nindex b572c60f2af85..6567bd4cdc07b 100644\n--- a/mm/shmem.c\n+++ b/mm/shmem.c\n@@ -668,7 +668,7 @@ static unsigned int shmem_huge_global_enabled(struct inode *inode, pgoff_t index\n \t}\n }\n \n-static int shmem_parse_huge(const char *str)\n+static int shmem_parse_huge(const char *str, bool skip_deny_force)\n {\n \tint huge;\n \n@@ -683,9 +683,9 @@ static int shmem_parse_huge(const char *str)\n \t\thuge = SHMEM_HUGE_WITHIN_SIZE;\n \telse if (!strcmp(str, \"advise\"))\n \t\thuge = SHMEM_HUGE_ADVISE;\n-\telse if (!strcmp(str, \"deny\"))\n+\telse if (!strcmp(str, \"deny\") \u0026\u0026 !skip_deny_force)\n \t\thuge = SHMEM_HUGE_DENY;\n-\telse if (!strcmp(str, \"force\"))\n+\telse if (!strcmp(str, \"force\") \u0026\u0026 !skip_deny_force)\n \t\thuge = SHMEM_HUGE_FORCE;\n \telse\n \t\treturn -EINVAL;\n@@ -2018,17 +2018,17 @@ static struct folio *shmem_swapin_cluster(swp_entry_t swap, gfp_t gfp,\n }\n \n #ifdef CONFIG_TRANSPARENT_HUGEPAGE\n-bool shmem_hpage_pmd_enabled(void)\n+bool shmem_hpage_enabled(void)\n {\n \tif (shmem_huge == SHMEM_HUGE_DENY)\n \t\treturn false;\n-\tif (test_bit(HPAGE_PMD_ORDER, \u0026huge_shmem_orders_always))\n+\tif (READ_ONCE(huge_shmem_orders_always))\n \t\treturn true;\n-\tif (test_bit(HPAGE_PMD_ORDER, \u0026huge_shmem_orders_madvise))\n+\tif (READ_ONCE(huge_shmem_orders_madvise))\n \t\treturn true;\n-\tif (test_bit(HPAGE_PMD_ORDER, \u0026huge_shmem_orders_within_size))\n+\tif (READ_ONCE(huge_shmem_orders_within_size))\n \t\treturn true;\n-\tif (test_bit(HPAGE_PMD_ORDER, \u0026huge_shmem_orders_inherit) \u0026\u0026\n+\tif (READ_ONCE(huge_shmem_orders_inherit) \u0026\u0026\n \t    shmem_huge != SHMEM_HUGE_NEVER)\n \t\treturn true;\n \n@@ -5680,7 +5680,7 @@ static ssize_t shmem_enabled_store(struct kobject *kobj,\n \tif (count \u0026\u0026 tmp[count - 1] == '\\n')\n \t\ttmp[count - 1] = '\\0';\n \n-\thuge = shmem_parse_huge(tmp);\n+\thuge = shmem_parse_huge(tmp, /*skip_deny_force=*/false);\n \tif (huge == -EINVAL)\n \t\treturn huge;\n \n@@ -5807,7 +5807,7 @@ static int __init setup_transparent_hugepage_shmem(char *str)\n {\n \tint huge;\n \n-\thuge = shmem_parse_huge(str);\n+\thuge = shmem_parse_huge(str, /*skip_deny_force=*/true);\n \tif (huge == -EINVAL) {\n \t\tpr_warn(\"transparent_hugepage_shmem= cannot parse, ignored\\n\");\n \t\treturn huge;\n@@ -5822,7 +5822,7 @@ static int __init setup_transparent_hugepage_tmpfs(char *str)\n {\n \tint huge;\n \n-\thuge = shmem_parse_huge(str);\n+\thuge = shmem_parse_huge(str, /*skip_deny_force=*/true);\n \tif (huge \u003c 0) {\n \t\tpr_warn(\"transparent_hugepage_tmpfs= cannot parse, ignored\\n\");\n \t\treturn huge;\ndiff --git a/tools/testing/selftests/mm/khugepaged.c b/tools/testing/selftests/mm/khugepaged.c\nindex f82673f5f6b47..a205b7afbc855 100644\n--- a/tools/testing/selftests/mm/khugepaged.c\n+++ b/tools/testing/selftests/mm/khugepaged.c\n@@ -627,6 +627,9 @@ static void mthp_khugepaged_collapse(const char *msg, char *p, int nr_hpages,\n \tif (ops == \u0026__anon_ops) {\n \t\tsettings.thp_enabled = THP_NEVER;\n \t\tsettings.hugepages[collapse_order].enabled = THP_MADVISE;\n+\t} else if (ops == \u0026__shmem_ops) {\n+\t\tsettings.shmem_enabled = SHMEM_NEVER;\n+\t\tsettings.shmem_hugepages[collapse_order].enabled = SHMEM_ADVISE;\n \t}\n \n \tthp_push_settings(\u0026settings);\n@@ -1260,8 +1263,6 @@ static void parse_test_type(int argc, char **argv)\n \t\t\tusage();\n \t} else if (!strcmp(buf, \"shmem\")) {\n \t\tshmem_ops = \u0026__shmem_ops;\n-\t\tif (mthp_khugepaged_context)\n-\t\t\tusage();\n \t} else {\n \t\tusage();\n \t}\n@@ -1358,6 +1359,7 @@ int main(int argc, char **argv)\n \tTEST(collapse_full, khugepaged_context, read_write_file_write_ops);\n \tTEST(collapse_full, khugepaged_context, shmem_ops);\n \tTEST(collapse_full, mthp_khugepaged_context, anon_ops);\n+\tTEST(collapse_full, mthp_khugepaged_context, shmem_ops);\n \tTEST(collapse_full, madvise_context, anon_ops);\n \tTEST(collapse_full, madvise_context, read_only_file_ops);\n \tTEST(collapse_full, madvise_context, read_write_file_read_ops);\n@@ -1369,6 +1371,7 @@ int main(int argc, char **argv)\n \tTEST(collapse_empty, madvise_context, anon_ops);\n \n \tTEST(collapse_single_mthp, mthp_khugepaged_context, anon_ops);\n+\tTEST(collapse_single_mthp, mthp_khugepaged_context, shmem_ops);\n \n \tTEST(collapse_single_pte_entry, khugepaged_context, anon_ops);\n \tTEST(collapse_single_pte_entry, khugepaged_context, read_only_file_ops);\ndiff --git a/tools/testing/selftests/mm/run_vmtests.sh b/tools/testing/selftests/mm/run_vmtests.sh\nindex 19755fb4edb94..e1e404a612ccf 100755\n--- a/tools/testing/selftests/mm/run_vmtests.sh\n+++ b/tools/testing/selftests/mm/run_vmtests.sh\n@@ -427,6 +427,8 @@ CATEGORY=\"thp\" run_test ./khugepaged -s 4 all:shmem\n \n CATEGORY=\"thp\" run_test ./khugepaged -c 4 mthp_khugepaged:anon\n \n+CATEGORY=\"thp\" run_test ./khugepaged -c 4 mthp_khugepaged:shmem\n+\n # Try to create XFS if not provided\n if [ -z \"${SPLIT_HUGE_PAGE_TEST_XFS_PATH}\" ]; then\n     if test_selected \"thp\"; then\n"
}

2/1 2026/09/20 07:11 agent patch-evaluator
1m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "TRANSPARENT_HUGEPAGE",
    "SHMEM"
  ],
  "FocusSymbols": [
    "collapse_file",
    "collapse_scan_file",
    "mthp_collapse",
    "collapse_run_pmd",
    "collapse_scan_pmd",
    "collapse_possible_orders",
    "shmem_hpage_enabled",
    "shmem_parse_huge"
  ],
  "Reasoning": "The patch extends khugepaged to support multi-size Transparent Huge Pages (mTHP) for file and shmem mappings. It modifies core MM collapse routines (collapse_file, collapse_scan_file, mthp_collapse, collapse_run_pmd) to handle non-PMD folio orders, adjusts page cache insertion and LRU accounting, and adds runtime assertions (such as VM_WARN_ON_ONCE(!file)). These changes touch core memory management code reachable from userspace via madvise(MADV_COLLAPSE) and background khugepaged scanning.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer and security engineer.
Your job is to review a provided patch series and evaluate whether it warrants fuzzing with syzkaller.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on internal assumptions. You must actively use your code access
tools to inspect the actual source code, callers, and surrounding context.

================================================================================
1. CORE TRIAGE PHILOSOPHY
================================================================================
The goal of patch fuzzing is to discover crashes, regressions, exposed latent bugs,
and newly triggered assertions introduced by the patch series.

- REACHABILITY IS THE PRIMARY GATE:
  Fuzzing can only discover bugs in code that can actually execute in standard virtualized
  environments (GCE or QEMU, utilizing software-emulated devices like USB gadgets, netdev, tun/tap).
  If the modified code is structurally unreachable (see Section 2), it MUST NOT be fuzzed,
  regardless of whether it adds assertions or complex logic.

- DO NOT BLINDLY TRUST "NO FUNCTIONAL CHANGE" (NFCI) OR "REFACTORING" CLAIMS:
  Patch authors routinely label changes as "cleanups", "refactorings", or state
  "No functional change intended". Do NOT take these claims at face value.
  Code refactorings that rearrange logic, introduce helper functions, or alter state management
  in core subsystems frequently introduce subtle semantic shifts or uncover latent kernel bugs.
  If reachable executable code is modified or refactored, it MUST be fuzzed.

- NEW OR MODIFIED ASSERTIONS IN REACHABLE CODE MUST BE FUZZED:
  When a patch introduces or modifies runtime checks or assertions (e.g., WARN_ON*, VM_WARN_ON*,
  BUG_ON*, lockdep_assert*) in reachable code paths, it enforces new or stricter invariants.
  Even if the author believes the invariant always holds, fuzzing is essential to verify whether
  an unusual sequence of operations can violate it.

================================================================================
2. WHEN TO RETURN WorthFuzzing=false (NEGATIVE CRITERIA)
================================================================================
Return WorthFuzzing=false ONLY IF all modified code falls strictly into one or more of these categories:

- Non-kernel and non-executable changes:
  * Modifications to Documentation/, comments, or spelling fixes.
  * User-space directories, self-tests, samples, or scripts (e.g., tools/, samples/, scripts/, usr/)
    that do not affect the compiled kernel image (vmlinux) or kernel modules.
  * Purely decorative logging (e.g., message strings in pr_err, printk, dev_info) or tracepoints
    that do not alter control flow or data structures.
  * Build system or Kconfig changes that do not alter compiled C logic.
- Structurally unreachable hardware:
  * Vendor-specific PCIe switches, SmartNICs, or GPU drivers (e.g., mlxsw, pds_core, qed,
    ionic, amdgpu) requiring physical ASIC/PCIe cards not emulated in standard QEMU.
- Unreachable execution paths:
  * Driver teardown callbacks (.remove, .shutdown, pci_unregister_driver) executed only during
    physical PCI hot-unplug or manual sysfs driver unbinding.
  * Code paths exclusive to architectures other than the target architecture.

================================================================================
3. WHEN TO RETURN WorthFuzzing=true (POSITIVE CRITERIA)
================================================================================
Return WorthFuzzing=true whenever the patch touches reachable executable code, including:
- Core Subsystems:
  * Any logic modifications in memory management (mm/), synchronization/locking (kernel/locking/),
    BPF, scheduler, core networking, VFS, or syscall handling.
- Refactorings and Code Cleanups:
  * Any restructuring of reachable data structures, helper abstractions, or algorithm flows.
- Runtime Assertions and Defensive Checks:
  * Any introduction or alteration of assertions (WARN_ON*, VM_WARN_ON*, BUG_ON*, etc.) in reachable paths.
- Reachable Drivers and Protocols:
  * Drivers accessible via virtual buses (virtio, USB gadget, loopback, netlink, binder, sockets, etc.).

================================================================================
4. EXTRACTING FocusSymbols (PREVENTING DILUTION)
================================================================================
When WorthFuzzing=true, you must extract specific kernel functions into FocusSymbols to guide the fuzzer:

- AVOID UBIQUITOUS LIFECYCLE HOT-PATHS:
  Do NOT list generic, ubiquitous functions called by almost every program in the corpus
  (including, but not limited to: general memory allocators and deallocators, page fault
  and trap handlers, or core synchronization primitives; this is not an exhaustive list).
  Listing ubiquitous functions causes the fuzzer to classify thousands of unrelated tests as "focused",
  which severely dilutes fuzzing effort away from the actual changes.

- TARGET SPECIFIC FEATURE LOGIC AND ENTRYPOINTS:
  List functions that specifically implement the logic being added or altered, or direct API entrypoints
  for the subsystem feature under review.

- HANDLING STATIC INLINE FUNCTIONS IN HEADERS (.h):
  Compiler-inlined static functions (such as static inlines in mm/*.h or include/linux/*.h) lack
  distinct symbol addresses in vmlinux and cannot be targeted directly by symbol coverage filters.
  If the changes are primarily in static inline helpers, identify non-static, feature-specific caller
  functions in .c files that exercise them (avoiding ubiquitous lifecycle wrappers).

================================================================================
5. IDENTIFYING EnableConfigs
================================================================================
Identify any specific CONFIG_ options required to properly compile and reach the modified code:
- Inspect Kconfig files and #ifdef guards; do not make assumptions.
- Check "depends on" lines in Kconfig to include any non-standard parent subsystem configs needed.
- Strip any '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:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit e0ea9a9e1bc3968fefab125ca103ef9197c81d03
Author: syz-cluster <triage@syzkaller.com>
Date:   Sun Sep 20 07:11:47 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/admin-guide/mm/transhuge.rst b/Documentation/admin-guide/mm/transhuge.rst
index b187d618452f4..0a8265d1cb553 100644
--- a/Documentation/admin-guide/mm/transhuge.rst
+++ b/Documentation/admin-guide/mm/transhuge.rst
@@ -389,8 +389,8 @@ is not defined within a valid ``thp_anon``, its policy will default to
 Similarly to ``transparent_hugepage``, you can control the hugepage
 allocation policy for the internal shmem mount by using the kernel parameter
 ``transparent_hugepage_shmem=<policy>``, where ``<policy>`` is one of the
-seven valid policies for shmem (``always``, ``within_size``, ``advise``,
-``never``, ``deny``, and ``force``).
+four valid policies for shmem (``always``, ``within_size``, ``advise``,
+``never``).
 
 Similarly to ``transparent_hugepage_shmem``, you can control the default
 hugepage allocation policy for the tmpfs mount by using the kernel parameter
diff --git a/include/linux/huge_mm.h b/include/linux/huge_mm.h
index 8ca0fa3be2acb..334c387ad9976 100644
--- a/include/linux/huge_mm.h
+++ b/include/linux/huge_mm.h
@@ -508,8 +508,6 @@ change_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
 			__split_huge_pud(__vma, __pud, __address);	\
 	}  while (0)
 
-int hugepage_madvise(struct vm_area_struct *vma, vm_flags_t *vm_flags,
-		     int advice);
 void vma_adjust_trans_huge(struct vm_area_struct *vma, unsigned long start,
 			   unsigned long end, struct vm_area_struct *next);
 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma);
@@ -707,12 +705,6 @@ static inline bool unmap_huge_pmd_locked(struct vm_area_struct *vma,
 #define split_huge_pud(__vma, __pmd, __address)	\
 	do { } while (0)
 
-static inline int hugepage_madvise(struct vm_area_struct *vma,
-				   vm_flags_t *vm_flags, int advice)
-{
-	return -EINVAL;
-}
-
 static inline void vma_adjust_trans_huge(struct vm_area_struct *vma,
 					 unsigned long start,
 					 unsigned long end,
diff --git a/include/linux/shmem_fs.h b/include/linux/shmem_fs.h
index a7c7a96a7cbf9..9f2036f58bb8f 100644
--- a/include/linux/shmem_fs.h
+++ b/include/linux/shmem_fs.h
@@ -135,7 +135,7 @@ int shmem_unuse(unsigned int type);
 unsigned long shmem_allowable_huge_orders(struct inode *inode,
 				struct vm_area_struct *vma, pgoff_t index,
 				loff_t write_end, bool shmem_huge_force);
-bool shmem_hpage_pmd_enabled(void);
+bool shmem_hpage_enabled(void);
 #else
 static inline unsigned long shmem_allowable_huge_orders(struct inode *inode,
 				struct vm_area_struct *vma, pgoff_t index,
@@ -144,7 +144,7 @@ static inline unsigned long shmem_allowable_huge_orders(struct inode *inode,
 	return 0;
 }
 
-static inline bool shmem_hpage_pmd_enabled(void)
+static inline bool shmem_hpage_enabled(void)
 {
 	return false;
 }
diff --git a/mm/collapse.h b/mm/collapse.h
index e529699652623..d2fff6b5e1ec4 100644
--- a/mm/collapse.h
+++ b/mm/collapse.h
@@ -8,7 +8,8 @@
 #include <linux/types.h>
 
 #define COLLAPSE_MAX_PTES_LIMIT		(HPAGE_PMD_NR - 1)
-#define COLLAPSE_MIN_MTHP_ORDER		2
+#define COLLAPSE_MIN_ANON_MTHP_ORDER		2
+#define COLLAPSE_MIN_FILE_MTHP_ORDER		1
 
 enum scan_result {
 	SCAN_FAIL,
diff --git a/mm/khugepaged.c b/mm/khugepaged.c
index a3a9e4d93b461..4b5e1f8ddf87a 100644
--- a/mm/khugepaged.c
+++ b/mm/khugepaged.c
@@ -84,6 +84,10 @@ static struct khugepaged_scan khugepaged_scan = {
 	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
 };
 
+static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
+		struct file *file, pgoff_t start,
+		struct collapse_control *cc, int order);
+
 #ifdef CONFIG_SYSFS
 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
 					 struct kobj_attribute *attr,
@@ -302,6 +306,14 @@ static bool pte_none_or_zero(pte_t pte)
 	return pte_present(pte) && is_zero_pfn(pte_pfn(pte));
 }
 
+static unsigned int collapse_min_mthp_order(struct file *file)
+{
+	if (file)
+		return COLLAPSE_MIN_FILE_MTHP_ORDER;
+
+	return COLLAPSE_MIN_ANON_MTHP_ORDER;
+}
+
 /**
  * collapse_max_ptes_none - Calculate maximum allowed empty PTEs or PTEs mapping
  * the shared zeropage for the given collapse operation.
@@ -380,28 +392,6 @@ static unsigned int collapse_max_ptes_swap(struct collapse_control *cc,
 	return cc->policy.max_ptes_swap;
 }
 
-int hugepage_madvise(struct vm_area_struct *vma,
-		     vm_flags_t *vm_flags, int advice)
-{
-	switch (advice) {
-	case MADV_HUGEPAGE:
-		*vm_flags &= ~VM_NOHUGEPAGE;
-		*vm_flags |= VM_HUGEPAGE;
-		break;
-	case MADV_NOHUGEPAGE:
-		*vm_flags &= ~VM_HUGEPAGE;
-		*vm_flags |= VM_NOHUGEPAGE;
-		/*
-		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
-		 * this vma even if we leave the mm registered in khugepaged if
-		 * it got registered before VM_NOHUGEPAGE was set.
-		 */
-		break;
-	}
-
-	return 0;
-}
-
 int __init khugepaged_init(void)
 {
 	mm_slot_cache = KMEM_CACHE(mm_slot, 0);
@@ -457,7 +447,7 @@ static bool hugepage_enabled(void)
 		return true;
 	if (anon_hpage_enabled())
 		return true;
-	if (shmem_hpage_pmd_enabled())
+	if (shmem_hpage_enabled())
 		return true;
 	return false;
 }
@@ -503,9 +493,14 @@ unsigned long collapse_possible_orders(struct vm_area_struct *vma,
 {
 	unsigned long orders;
 
-	/* If khugepaged is scanning an anonymous vma, allow mTHP collapse */
+	/*
+	 * If khugepaged is scanning an anonymous or shmem vma,
+	 * allow mTHP collapse.
+	 */
 	if ((tva_flags == TVA_KHUGEPAGED) && vma_is_anonymous(vma))
 		orders = THP_ORDERS_ALL_ANON;
+	else if ((tva_flags == TVA_KHUGEPAGED) && vma_is_shmem(vma))
+		orders = THP_ORDERS_ALL_FILE_DEFAULT;
 	else
 		orders = BIT(HPAGE_PMD_ORDER);
 
@@ -1466,7 +1461,11 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long addres
 			enum scan_result ret;
 
 			collapse_address = address + offset * PAGE_SIZE;
-			ret = collapse_huge_page(mm, collapse_address, cc, order);
+			if (cc->scan_file)
+				ret = collapse_file(mm, collapse_address, cc->scan_file,
+						cc->scan_pgoff + offset, cc, order);
+			else
+				ret = collapse_huge_page(mm, collapse_address, cc, order);
 
 			switch (ret) {
 			/* Cases where we continue to next collapse candidate */
@@ -1474,6 +1473,13 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long addres
 				collapsed += nr_ptes;
 				fallthrough;
 			case SCAN_PTE_MAPPED_HUGEPAGE:
+				/*
+				 * Return SCAN_PTE_MAPPED_HUGEPAGE to call
+				 * collapse_pte_mapped_thp() if the page cache
+				 * already holds the PMD folio.
+				 */
+				if (order == HPAGE_PMD_ORDER)
+					last_result = ret;
 				goto next_offset;
 			/* Cases where lower orders might still succeed */
 			case SCAN_ALLOC_HUGE_PAGE_FAIL:
@@ -1507,7 +1513,7 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long addres
 		 * any smaller order enabled. When at the smallest order
 		 * we must always move to the next offset.
 		 */
-		if (order > COLLAPSE_MIN_MTHP_ORDER &&
+		if (order > collapse_min_mthp_order(cc->scan_file) &&
 		    (cc->scan_orders & GENMASK(order - 1, 0))) {
 			order--;
 			continue;
@@ -2160,6 +2166,7 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
  * @file: file that collapse on
  * @start: collapse start address
  * @cc: collapse context and scratchpad
+ * @order: folio order being collapsed to
  *
  * Basic scheme is simple, details are more complex:
  *  - allocate and lock a new huge page;
@@ -2178,29 +2185,29 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
  *    + unlock and free huge page;
  */
 static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
-		struct file *file, pgoff_t start, struct collapse_control *cc)
+		struct file *file, pgoff_t start, struct collapse_control *cc,
+		int order)
 {
+	const unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, order);
 	struct address_space *mapping = file->f_mapping;
+	const unsigned long nr_pages = 1UL << order;
 	struct page *dst;
 	struct folio *folio, *tmp, *new_folio;
 	unsigned long new_pfn = -1;
-	pgoff_t index = 0, end = start + HPAGE_PMD_NR;
+	pgoff_t index = 0, end = start + nr_pages;
 	LIST_HEAD(pagelist);
-	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
+	XA_STATE_ORDER(xas, &mapping->i_pages, start, order);
 	enum scan_result result = SCAN_SUCCEED;
 	int nr_none = 0;
 	bool is_shmem = shmem_file(file);
 
 	/*
-	 * MADV_COLLAPSE ignores shmem huge config, so do not check shmem
-	 *
-	 * TODO: once shmem always calls mapping_set_large_folios() on its
-	 * mapping, the shmem check can be removed.
+	 * MADV_COLLAPSE ignores shmem huge config, so do not check shmem.
 	 */
-	VM_WARN_ON_ONCE(!is_shmem && !mapping_pmd_folio_support(mapping));
-	VM_WARN_ON_ONCE(start & (HPAGE_PMD_NR - 1));
+	VM_WARN_ON_ONCE(!mapping_pmd_folio_support(mapping));
+	VM_WARN_ON_ONCE(start & (nr_pages - 1));
 
-	result = alloc_charge_folio(&new_folio, mm, cc, HPAGE_PMD_ORDER);
+	result = alloc_charge_folio(&new_folio, mm, cc, order);
 	if (result != SCAN_SUCCEED)
 		goto out;
 	new_pfn = folio_pfn(new_folio);
@@ -2247,13 +2254,33 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 						goto xa_locked;
 					}
 				}
-				nr_none++;
+
+				if (++nr_none > max_ptes_none) {
+					result = SCAN_EXCEED_NONE_PTE;
+					count_collapse_event(order, THP_SCAN_EXCEED_NONE_PTE,
+							MTHP_STAT_COLLAPSE_EXCEED_NONE);
+					goto xa_locked;
+				}
+
 				index++;
 				continue;
 			}
 
 			if (xa_is_value(folio) || !folio_test_uptodate(folio)) {
 				xas_unlock_irq(&xas);
+
+				/*
+				 * TODO: Support swapin without leading to further mTHP
+				 * collapses. Currently bringing in new pages via swapin may
+				 * cause a future higher order collapse on a rescan of the same
+				 * range.
+				 */
+				if (!is_pmd_order(order)) {
+					count_mthp_stat(order, MTHP_STAT_COLLAPSE_EXCEED_SWAP);
+					result = SCAN_EXCEED_SWAP_PTE;
+					goto xa_unlocked;
+				}
+
 				/* swap in or instantiate fallocated page */
 				if (shmem_get_folio(mapping->host, index, 0,
 						&folio, SGP_NOALLOC)) {
@@ -2337,6 +2364,15 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 			goto out_unlock;
 		}
 
+		/*
+		 * If the folio order is greater than the collapse order, there is
+		 * no need to continue attempting to collapse.
+		 */
+		if (folio_order(folio) >= order) {
+			result = SCAN_PTE_MAPPED_HUGEPAGE;
+			goto out_unlock;
+		}
+
 		if (folio_mapping(folio) != mapping) {
 			result = SCAN_TRUNCATED;
 			goto out_unlock;
@@ -2532,12 +2568,13 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	}
 
 	if (is_shmem) {
-		lruvec_stat_mod_folio(new_folio, NR_SHMEM, HPAGE_PMD_NR);
-		lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);
-	} else {
+		lruvec_stat_mod_folio(new_folio, NR_SHMEM, nr_pages);
+		if (is_pmd_order(order))
+			lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);
+	} else if (is_pmd_order(order)) {
 		lruvec_stat_mod_folio(new_folio, NR_FILE_THPS, HPAGE_PMD_NR);
 	}
-	lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, HPAGE_PMD_NR);
+	lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, nr_pages);
 
 	/*
 	 * Mark new_folio as uptodate before inserting it into the
@@ -2545,23 +2582,24 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	 * unwritten page.
 	 */
 	folio_mark_uptodate(new_folio);
-	folio_ref_add(new_folio, HPAGE_PMD_NR - 1);
+	folio_ref_add(new_folio, nr_pages - 1);
 
 	if (is_shmem)
 		folio_mark_dirty(new_folio);
 	folio_add_lru(new_folio);
 
 	/* Join all the small entries into a single multi-index entry. */
-	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
+	xas_set_order(&xas, start, order);
 	xas_store(&xas, new_folio);
 	WARN_ON_ONCE(xas_error(&xas));
 	xas_unlock_irq(&xas);
 
 	/*
-	 * Remove pte page tables, so we can re-fault the page as huge.  A
-	 * caller that wants the PMD mapped now is told to go and do that.
+	 * Remove pte page tables for PMD-sized THP collapse, so we can
+	 * re-fault the page as huge.
 	 */
-	retract_page_tables(mapping, start);
+	if (is_pmd_order(order))
+		retract_page_tables(mapping, start);
 	if (cc->policy.install_pmd)
 		result = SCAN_PTE_MAPPED_HUGEPAGE;
 	folio_unlock(new_folio);
@@ -2607,27 +2645,38 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	folio_put(new_folio);
 out:
 	VM_BUG_ON(!list_empty(&pagelist));
-	trace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
+	trace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, nr_pages, result);
 	return result;
 }
 
-static enum scan_result collapse_scan_file(struct mm_struct *mm,
-		unsigned long addr, struct file *file, pgoff_t start,
-		struct collapse_control *cc)
+static enum scan_result collapse_scan_file(struct vm_area_struct *vma,
+		unsigned long addr, struct collapse_control *cc,
+		unsigned long enabled_orders)
 {
-	const unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, HPAGE_PMD_ORDER);
 	const unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);
+	unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, HPAGE_PMD_ORDER);
+	struct file *file = vma->vm_file;
 	struct folio *folio = NULL;
 	struct address_space *mapping = file->f_mapping;
+	pgoff_t start = linear_page_index(vma, addr);
 	XA_STATE(xas, &mapping->i_pages, start);
 	int present, swap;
 	int node = NUMA_NO_NODE;
 	enum scan_result result = SCAN_SUCCEED;
 	unsigned long failed_pfn = -1;
+	unsigned long nr_pages;
+	pgoff_t pgoff;
 
 	present = 0;
 	swap = 0;
 	collapse_scan_reset(cc);
+	/*
+	 * If PMD is the only enabled order, enforce max_ptes_none, otherwise
+	 * scan all pages to populate the bitmap for mTHP collapse.
+	 */
+	if (enabled_orders != BIT(HPAGE_PMD_ORDER))
+		max_ptes_none = COLLAPSE_MAX_PTES_LIMIT;
+
 	rcu_read_lock();
 	xas_for_each(&xas, folio, start + HPAGE_PMD_NR - 1) {
 		if (xas_retry(&xas, folio))
@@ -2695,7 +2744,17 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,
 		 * is just too costly...
 		 */
 
-		present += folio_nr_pages(folio);
+		nr_pages = folio_nr_pages(folio);
+		present += nr_pages;
+
+		/*
+		 * If there are folios present, keep track of it in the bitmap
+		 * for file/shmem mTHP collapse.
+		 */
+		pgoff = max_t(pgoff_t, start, folio->index) - start;
+		nr_pages = min_t(int, HPAGE_PMD_NR - pgoff, nr_pages);
+		bitmap_set(cc->eligible_ptes, pgoff, nr_pages);
+
 		folio_put(folio);
 
 		if (need_resched()) {
@@ -2711,10 +2770,27 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,
 
 	if (result == SCAN_SUCCEED && present < HPAGE_PMD_NR - max_ptes_none) {
 		result = SCAN_EXCEED_NONE_PTE;
-		count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
+		count_collapse_event(HPAGE_PMD_ORDER, THP_SCAN_EXCEED_NONE_PTE,
+				MTHP_STAT_COLLAPSE_EXCEED_NONE);
+	}
+
+	/*
+	 * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds
+	 * the PMD folio, and retracting the PTE table is the run's job.
+	 */
+	if (result == SCAN_SUCCEED || result == SCAN_PTE_MAPPED_HUGEPAGE) {
+		/*
+		 * A file collapse works on the page cache and never sees a
+		 * VMA, so take what it needs from this one while it is still
+		 * here.
+		 */
+		cc->scan_file = get_file(file);
+		cc->scan_pgoff = start;
+		cc->scan_orders = enabled_orders;
+		cc->scan_unmapped = swap;
 	}
 
-	trace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap,
+	trace_mm_khugepaged_scan_file(vma->vm_mm, failed_pfn, file, present, swap,
 				      result);
 	return result;
 }
@@ -2762,9 +2838,6 @@ enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,
 		unsigned long addr, struct collapse_control *cc,
 		unsigned long orders)
 {
-	enum scan_result result;
-	pgoff_t pgoff;
-
 	mmap_assert_locked(vma->vm_mm);
 	/* Whatever the last scan found has to have been run by now */
 	collapse_put_scan_file(cc);
@@ -2772,22 +2845,7 @@ enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,
 	if (vma_is_anonymous(vma))
 		return collapse_scan_anon_pmd(vma, addr, cc, orders);
 
-	pgoff = linear_page_index(vma, addr);
-	result = collapse_scan_file(vma->vm_mm, addr, vma->vm_file, pgoff, cc);
-	/*
-	 * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds
-	 * the PMD folio, and retracting the PTE table is the run's job.
-	 */
-	if (result != SCAN_SUCCEED && result != SCAN_PTE_MAPPED_HUGEPAGE)
-		return result;
-
-	/*
-	 * A file collapse works on the page cache and never sees a VMA, so take
-	 * what it needs from this one while it is still here.
-	 */
-	cc->scan_file = get_file(vma->vm_file);
-	cc->scan_pgoff = pgoff;
-	return result;
+	return collapse_scan_file(vma, addr, cc, orders);
 }
 
 /*
@@ -2805,23 +2863,21 @@ enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,
 {
 	struct file *file = cc->scan_file;
 	bool triggered_wb = false;
-	pgoff_t pgoff;
-
-	if (!file)
-		return mthp_collapse(mm, addr, cc);
-
-	cc->scan_file = NULL;
-	pgoff = cc->scan_pgoff;
 
 	/* The scan found the PMD folio in place: nothing to collapse */
 	if (result == SCAN_PTE_MAPPED_HUGEPAGE)
 		goto retract;
+
 retry:
-	result = collapse_file(mm, addr, file, pgoff, cc);
+	result = mthp_collapse(mm, addr, cc);
+	/* Just return the results for anonymous folio collapse. */
+	if (!file)
+		return result;
 
 	/* Dirty pages are worth a writeback and one more try, if asked for */
 	if (cc->policy.writeback_dirty && result == SCAN_PAGE_DIRTY_OR_WRITEBACK &&
 	    !triggered_wb && mapping_can_writeback(file->f_mapping)) {
+		pgoff_t pgoff = cc->scan_pgoff;
 		const loff_t lstart = (loff_t)pgoff << PAGE_SHIFT;
 		const loff_t lend = lstart + HPAGE_PMD_SIZE - 1;
 
@@ -2830,6 +2886,8 @@ enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,
 		goto retry;
 	}
 retract:
+	cc->scan_file = NULL;
+	VM_WARN_ON_ONCE(!file);
 	fput(file);
 
 	/*
diff --git a/mm/madvise.c b/mm/madvise.c
index eb491fa88325d..4150f6a8cf64c 100644
--- a/mm/madvise.c
+++ b/mm/madvise.c
@@ -1598,10 +1598,12 @@ static int madvise_vma_behavior(struct madvise_behavior *madv_behavior)
 			goto out;
 		break;
 	case MADV_HUGEPAGE:
+		new_flags &= ~VM_NOHUGEPAGE;
+		new_flags |= VM_HUGEPAGE;
+		break;
 	case MADV_NOHUGEPAGE:
-		error = hugepage_madvise(vma, &new_flags, behavior);
-		if (error)
-			goto out;
+		new_flags &= ~VM_HUGEPAGE;
+		new_flags |= VM_NOHUGEPAGE;
 		break;
 	case __MADV_SET_ANON_VMA_NAME:
 		/* Only anonymous mappings can be named */
diff --git a/mm/shmem.c b/mm/shmem.c
index b572c60f2af85..6567bd4cdc07b 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -668,7 +668,7 @@ static unsigned int shmem_huge_global_enabled(struct inode *inode, pgoff_t index
 	}
 }
 
-static int shmem_parse_huge(const char *str)
+static int shmem_parse_huge(const char *str, bool skip_deny_force)
 {
 	int huge;
 
@@ -683,9 +683,9 @@ static int shmem_parse_huge(const char *str)
 		huge = SHMEM_HUGE_WITHIN_SIZE;
 	else if (!strcmp(str, "advise"))
 		huge = SHMEM_HUGE_ADVISE;
-	else if (!strcmp(str, "deny"))
+	else if (!strcmp(str, "deny") && !skip_deny_force)
 		huge = SHMEM_HUGE_DENY;
-	else if (!strcmp(str, "force"))
+	else if (!strcmp(str, "force") && !skip_deny_force)
 		huge = SHMEM_HUGE_FORCE;
 	else
 		return -EINVAL;
@@ -2018,17 +2018,17 @@ static struct folio *shmem_swapin_cluster(swp_entry_t swap, gfp_t gfp,
 }
 
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
-bool shmem_hpage_pmd_enabled(void)
+bool shmem_hpage_enabled(void)
 {
 	if (shmem_huge == SHMEM_HUGE_DENY)
 		return false;
-	if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_always))
+	if (READ_ONCE(huge_shmem_orders_always))
 		return true;
-	if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_madvise))
+	if (READ_ONCE(huge_shmem_orders_madvise))
 		return true;
-	if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_within_size))
+	if (READ_ONCE(huge_shmem_orders_within_size))
 		return true;
-	if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_inherit) &&
+	if (READ_ONCE(huge_shmem_orders_inherit) &&
 	    shmem_huge != SHMEM_HUGE_NEVER)
 		return true;
 
@@ -5680,7 +5680,7 @@ static ssize_t shmem_enabled_store(struct kobject *kobj,
 	if (count && tmp[count - 1] == '\n')
 		tmp[count - 1] = '\0';
 
-	huge = shmem_parse_huge(tmp);
+	huge = shmem_parse_huge(tmp, /*skip_deny_force=*/false);
 	if (huge == -EINVAL)
 		return huge;
 
@@ -5807,7 +5807,7 @@ static int __init setup_transparent_hugepage_shmem(char *str)
 {
 	int huge;
 
-	huge = shmem_parse_huge(str);
+	huge = shmem_parse_huge(str, /*skip_deny_force=*/true);
 	if (huge == -EINVAL) {
 		pr_warn("transparent_hugepage_shmem= cannot parse, ignored\n");
 		return huge;
@@ -5822,7 +5822,7 @@ static int __init setup_transparent_hugepage_tmpfs(char *str)
 {
 	int huge;
 
-	huge = shmem_parse_huge(str);
+	huge = shmem_parse_huge(str, /*skip_deny_force=*/true);
 	if (huge < 0) {
 		pr_warn("transparent_hugepage_tmpfs= cannot parse, ignored\n");
 		return huge;
diff --git a/tools/testing/selftests/mm/khugepaged.c b/tools/testing/selftests/mm/khugepaged.c
index f82673f5f6b47..a205b7afbc855 100644
--- a/tools/testing/selftests/mm/khugepaged.c
+++ b/tools/testing/selftests/mm/khugepaged.c
@@ -627,6 +627,9 @@ static void mthp_khugepaged_collapse(const char *msg, char *p, int nr_hpages,
 	if (ops == &__anon_ops) {
 		settings.thp_enabled = THP_NEVER;
 		settings.hugepages[collapse_order].enabled = THP_MADVISE;
+	} else if (ops == &__shmem_ops) {
+		settings.shmem_enabled = SHMEM_NEVER;
+		settings.shmem_hugepages[collapse_order].enabled = SHMEM_ADVISE;
 	}
 
 	thp_push_settings(&settings);
@@ -1260,8 +1263,6 @@ static void parse_test_type(int argc, char **argv)
 			usage();
 	} else if (!strcmp(buf, "shmem")) {
 		shmem_ops = &__shmem_ops;
-		if (mthp_khugepaged_context)
-			usage();
 	} else {
 		usage();
 	}
@@ -1358,6 +1359,7 @@ int main(int argc, char **argv)
 	TEST(collapse_full, khugepaged_context, read_write_file_write_ops);
 	TEST(collapse_full, khugepaged_context, shmem_ops);
 	TEST(collapse_full, mthp_khugepaged_context, anon_ops);
+	TEST(collapse_full, mthp_khugepaged_context, shmem_ops);
 	TEST(collapse_full, madvise_context, anon_ops);
 	TEST(collapse_full, madvise_context, read_only_file_ops);
 	TEST(collapse_full, madvise_context, read_write_file_read_ops);
@@ -1369,6 +1371,7 @@ int main(int argc, char **argv)
 	TEST(collapse_empty, madvise_context, anon_ops);
 
 	TEST(collapse_single_mthp, mthp_khugepaged_context, anon_ops);
+	TEST(collapse_single_mthp, mthp_khugepaged_context, shmem_ops);
 
 	TEST(collapse_single_pte_entry, khugepaged_context, anon_ops);
 	TEST(collapse_single_pte_entry, khugepaged_context, read_only_file_ops);
diff --git a/tools/testing/selftests/mm/run_vmtests.sh b/tools/testing/selftests/mm/run_vmtests.sh
index 19755fb4edb94..e1e404a612ccf 100755
--- a/tools/testing/selftests/mm/run_vmtests.sh
+++ b/tools/testing/selftests/mm/run_vmtests.sh
@@ -427,6 +427,8 @@ CATEGORY="thp" run_test ./khugepaged -s 4 all:shmem
 
 CATEGORY="thp" run_test ./khugepaged -c 4 mthp_khugepaged:anon
 
+CATEGORY="thp" run_test ./khugepaged -c 4 mthp_khugepaged:shmem
+
 # Try to create XFS if not provided
 if [ -z "${SPLIT_HUGE_PAGE_TEST_XFS_PATH}" ]; then
     if test_selected "thp"; then

3/2 2026/09/20 07:11 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 12151
							output: 30
							thoughts: 704
						

Thoughts:
**Analyzing a Linux Kernel Patch Series for Fuzzing Suitability**

Okay, so I need to assess this patch series committed to HEAD on amd64. My initial reaction is that this is definitely something worth digging into. The user wants me to determine if this is suitable for fuzzing. Let's see...

First, let's look at the files touched. Okay, we have: `Documentation/admin-guide/mm/transhuge.rst`, a few header files: `include/linux/huge_mm.h`, `include/linux/shmem_fs.h`, and then some core MM code: `mm/collapse.h`, `mm/khugepaged.c`, `mm/madvise.c`, `mm/shmem.c`. Then some test infrastructure: `tools/testing/selftests/mm/khugepaged.c`, `tools/testing/selftests/mm/run_vmtests.sh`. Right off the bat, that screams *memory management*.

Now, let's break down the code changes. `mm/khugepaged.c` seems to be the heart of it. It looks like it's adding multi-size THP support to file and shmem collapse. It’s modifying `collapse_file` to handle different orders, calculates page counts based on these orders, incorporates `max_ptes_none`, handles swap and value folios, updates LRUvec stats, and includes order checks during page table retraction. Also, they're updating `collapse_scan_file` and `collapse_run_pmd`. The changes in `mthp_collapse` specifically seem focused on file collapse logic, along with modifications to `hugepage_enabled()` and `collapse_possible_orders()`. `mm/madvise.c` is inlining `hugepage_madvise`, which I suspect is for optimization or simplification. Finally, `mm/shmem.c` updates `shmem_parse_huge` and `shmem_hpage_enabled`.

This definitely touches some core MM code. We're looking at Transparent Huge Pages (THP), multi-size THP (mTHP), khugepaged, shmem/file collapse, and madvise. I know that these are all critical memory management subsystems. This is the kind of area where subtle bugs can have massive consequences.

Let me think back to our fuzzing guidance. Section 3 specifically mentions "Core Subsystems" as a trigger: "...Any logic modifications in memory management (mm/)...". Bingo! This is absolutely a candidate for fuzzing. Therefore, WorthFuzzing = true.

Next, I should probably check if there are any special configurations required for this to be enabled. I’ll need to look at Kconfig, probably around the `khugepaged` and `transparent hugepage` options to see if there are any dependencies or specific configurations. I'll use `grepper` or `read-file` to do that. That will give me the information to make sure the fuzzing setup will properly exercise the code being modified in this patch.



4/2 2026/09/20 07:11 tool grepper
0m Args:
{
  "Expression": "TRANSPARENT_HUGEPAGE",
  "PathPrefix": "mm/"
}

Results:
{
  "Output": "\nFull output is too long, showing 500 out of 921 lines.\nUse more precise expression if possible.\n\nmm/Kconfig=815=config PERSISTENT_HUGE_ZERO_FOLIO\nmm/Kconfig-816-\tbool \"Allocate a PMD sized folio for zeroing\"\nmm/Kconfig:817:\tdepends on TRANSPARENT_HUGEPAGE\nmm/Kconfig-818-\thelp\n--\nmm/Kconfig=831=config MM_ID\n--\nmm/Kconfig-833-\nmm/Kconfig:834:menuconfig TRANSPARENT_HUGEPAGE\nmm/Kconfig-835-\tbool \"Transparent Hugepage Support\"\nmm/Kconfig:836:\tdepends on HAVE_ARCH_TRANSPARENT_HUGEPAGE \u0026\u0026 !PREEMPT_RT\nmm/Kconfig-837-\tselect COMPACTION\n--\nmm/Kconfig-849-\nmm/Kconfig:850:if TRANSPARENT_HUGEPAGE\nmm/Kconfig-851-\nmm/Kconfig=852=choice\nmm/Kconfig-853-\tprompt \"Transparent Hugepage Support sysfs defaults\"\nmm/Kconfig:854:\tdefault TRANSPARENT_HUGEPAGE_ALWAYS\nmm/Kconfig-855-\thelp\n--\nmm/Kconfig-857-\nmm/Kconfig:858:\tconfig TRANSPARENT_HUGEPAGE_ALWAYS\nmm/Kconfig-859-\t\tbool \"always\"\n--\nmm/Kconfig-864-\nmm/Kconfig:865:\tconfig TRANSPARENT_HUGEPAGE_MADVISE\nmm/Kconfig-866-\t\tbool \"madvise\"\n--\nmm/Kconfig-873-\nmm/Kconfig:874:\tconfig TRANSPARENT_HUGEPAGE_NEVER\nmm/Kconfig-875-\t\tbool \"never\"\n--\nmm/Kconfig=881=choice\nmm/Kconfig-882-\tprompt \"Shmem hugepage allocation defaults\"\nmm/Kconfig:883:\tdefault TRANSPARENT_HUGEPAGE_SHMEM_HUGE_NEVER\nmm/Kconfig-884-\thelp\n--\nmm/Kconfig-890-\nmm/Kconfig:891:\tconfig TRANSPARENT_HUGEPAGE_SHMEM_HUGE_NEVER\nmm/Kconfig-892-\t\tbool \"never\"\n--\nmm/Kconfig-900-\nmm/Kconfig:901:\tconfig TRANSPARENT_HUGEPAGE_SHMEM_HUGE_ALWAYS\nmm/Kconfig-902-\t\tbool \"always\"\n--\nmm/Kconfig-908-\nmm/Kconfig:909:\tconfig TRANSPARENT_HUGEPAGE_SHMEM_HUGE_WITHIN_SIZE\nmm/Kconfig-910-\t\tbool \"within_size\"\n--\nmm/Kconfig-916-\nmm/Kconfig:917:\tconfig TRANSPARENT_HUGEPAGE_SHMEM_HUGE_ADVISE\nmm/Kconfig-918-\t\tbool \"advise\"\n--\nmm/Kconfig=926=choice\nmm/Kconfig-927-\tprompt \"Tmpfs hugepage allocation defaults\"\nmm/Kconfig:928:\tdefault TRANSPARENT_HUGEPAGE_TMPFS_HUGE_NEVER\nmm/Kconfig-929-\thelp\n--\nmm/Kconfig-935-\nmm/Kconfig:936:\tconfig TRANSPARENT_HUGEPAGE_TMPFS_HUGE_NEVER\nmm/Kconfig-937-\t\tbool \"never\"\n--\nmm/Kconfig-944-\nmm/Kconfig:945:\tconfig TRANSPARENT_HUGEPAGE_TMPFS_HUGE_ALWAYS\nmm/Kconfig-946-\t\tbool \"always\"\n--\nmm/Kconfig-952-\nmm/Kconfig:953:\tconfig TRANSPARENT_HUGEPAGE_TMPFS_HUGE_WITHIN_SIZE\nmm/Kconfig-954-\t\tbool \"within_size\"\n--\nmm/Kconfig-960-\nmm/Kconfig:961:\tconfig TRANSPARENT_HUGEPAGE_TMPFS_HUGE_ADVISE\nmm/Kconfig-962-\t\tbool \"advise\"\n--\nmm/Kconfig=980=config NO_PAGE_MAPCOUNT\n--\nmm/Kconfig-992-\nmm/Kconfig:993:endif # TRANSPARENT_HUGEPAGE\nmm/Kconfig-994-\n--\nmm/Kconfig=1002=config PGTABLE_HAS_HUGE_LEAVES\nmm/Kconfig:1003:\tdef_bool TRANSPARENT_HUGEPAGE || HUGETLB_PAGE\nmm/Kconfig-1004-\n--\nmm/Kconfig=1008=config HAVE_GIGANTIC_FOLIOS\nmm/Kconfig-1009-\tdef_bool (HUGETLB_PAGE \u0026\u0026 ARCH_HAS_GIGANTIC_PAGE) || \\\nmm/Kconfig:1010:\t\t (ZONE_DEVICE \u0026\u0026 HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)\nmm/Kconfig-1011-\n--\nmm/Kconfig=1016=config ARCH_SUPPORTS_HUGE_PFNMAP\nmm/Kconfig-1017-\tdef_bool n\nmm/Kconfig:1018:\tdepends on TRANSPARENT_HUGEPAGE\nmm/Kconfig-1019-\nmm/Kconfig=1020=config ARCH_SUPPORTS_PMD_PFNMAP\nmm/Kconfig-1021-\tdef_bool y\nmm/Kconfig:1022:\tdepends on ARCH_SUPPORTS_HUGE_PFNMAP \u0026\u0026 HAVE_ARCH_TRANSPARENT_HUGEPAGE\nmm/Kconfig-1023-\nmm/Kconfig=1024=config ARCH_SUPPORTS_PUD_PFNMAP\nmm/Kconfig-1025-\tdef_bool y\nmm/Kconfig:1026:\tdepends on ARCH_SUPPORTS_HUGE_PFNMAP \u0026\u0026 HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/Kconfig-1027-\n--\nmm/Makefile=101=obj-$(CONFIG_DEVICE_MIGRATION) += migrate_device.o\nmm/Makefile:102:obj-$(CONFIG_TRANSPARENT_HUGEPAGE) += huge_memory.o khugepaged.o\nmm/Makefile-103-obj-$(CONFIG_PAGE_COUNTER) += page_counter.o\n--\nmm/char-mem.c=523=static unsigned long get_unmapped_area_zero(struct file *file,\n--\nmm/char-mem.c-542-\t */\nmm/char-mem.c:543:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/char-mem.c-544-\treturn thp_get_unmapped_area(file, addr, len, pgoff, flags);\n--\nmm/compaction.c=60=static inline bool is_via_compact_memory(int order) { return false; }\n--\nmm/compaction.c-75- */\nmm/compaction.c:76:#if defined CONFIG_TRANSPARENT_HUGEPAGE\nmm/compaction.c-77-#define COMPACTION_HPAGE_ORDER\tHPAGE_PMD_ORDER\n--\nmm/damon/ops-common.c=96=void damon_pmdp_mkold(pmd_t *pmd, struct vm_area_struct *vma, unsigned long addr)\nmm/damon/ops-common.c-97-{\nmm/damon/ops-common.c:98:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/ops-common.c-99-\tpmd_t pmdval = pmdp_get(pmd);\n--\nmm/damon/ops-common.c-120-\tfolio_put(folio);\nmm/damon/ops-common.c:121:#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/ops-common.c-122-}\n--\nmm/damon/ops-common.c=291=static bool damon_folio_young_one(struct folio *folio,\n--\nmm/damon/ops-common.c-307-\t\t} else {\nmm/damon/ops-common.c:308:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/ops-common.c-309-\t\t\tpmd_t pmd = pmdp_get(pvmw.pmd);\n--\nmm/damon/ops-common.c-315-\t\t\tWARN_ON_ONCE(1);\nmm/damon/ops-common.c:316:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/ops-common.c-317-\t\t}\n--\nmm/damon/vaddr.c=352=static int damon_young_pmd_entry(pmd_t *pmd, unsigned long addr,\n--\nmm/damon/vaddr.c-360-\nmm/damon/vaddr.c:361:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/vaddr.c-362-\tptl = pmd_trans_huge_lock(pmd, walk-\u003evma);\n--\nmm/damon/vaddr.c-378-\t}\nmm/damon/vaddr.c:379:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/vaddr.c-380-\n--\nmm/damon/vaddr.c=603=static int damon_va_probe_pmd_entry(pmd_t *pmd, unsigned long addr,\n--\nmm/damon/vaddr.c-611-\nmm/damon/vaddr.c:612:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/vaddr.c-613-\tptl = pmd_trans_huge_lock(pmd, walk-\u003evma);\n--\nmm/damon/vaddr.c-628-\t}\nmm/damon/vaddr.c:629:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/vaddr.c-630-\n--\nmm/damon/vaddr.c=835=static int damos_va_migrate_pmd_entry(pmd_t *pmd, unsigned long addr,\n--\nmm/damon/vaddr.c-846-\nmm/damon/vaddr.c:847:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/vaddr.c-848-\tptl = pmd_trans_huge_lock(pmd, walk-\u003evma);\n--\nmm/damon/vaddr.c-864-\t}\nmm/damon/vaddr.c:865:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/damon/vaddr.c-866-\n--\nmm/damon/vaddr.c=998=static int damos_va_stat_pmd_entry(pmd_t *pmd, unsigned long addr,\n--\nmm/damon/vaddr.c-1009-\nmm/damon/vaddr.c:1010:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/damon/vaddr.c-1011-\tptl = pmd_trans_huge_lock(pmd, vma);\n--\nmm/debug_vm_pgtable.c=114=static void __init pte_advanced_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-172-\nmm/debug_vm_pgtable.c:173:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/debug_vm_pgtable.c-174-static void __init pmd_basic_tests(struct pgtable_debug_args *args, int idx)\n--\nmm/debug_vm_pgtable.c=282=static void __init pmd_leaf_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-298-\nmm/debug_vm_pgtable.c:299:#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/debug_vm_pgtable.c-300-static void __init pud_basic_tests(struct pgtable_debug_args *args, int idx)\n--\nmm/debug_vm_pgtable.c=405=static void __init pud_leaf_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-419-}\nmm/debug_vm_pgtable.c:420:#else  /* !CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */\nmm/debug_vm_pgtable.c-421-static void __init pud_basic_tests(struct pgtable_debug_args *args, int idx) { }\n--\nmm/debug_vm_pgtable.c=423=static void __init pud_leaf_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c:424:#endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */\nmm/debug_vm_pgtable.c:425:#else  /* !CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-426-static void __init pmd_basic_tests(struct pgtable_debug_args *args, int idx) { }\n--\nmm/debug_vm_pgtable.c=431=static void __init pud_leaf_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c:432:#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-433-\n--\nmm/debug_vm_pgtable.c=671=static void __init pte_protnone_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-682-\nmm/debug_vm_pgtable.c:683:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/debug_vm_pgtable.c-684-static void __init pmd_protnone_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-698-}\nmm/debug_vm_pgtable.c:699:#else  /* !CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-700-static void __init pmd_protnone_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c:701:#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-702-\n--\nmm/debug_vm_pgtable.c=715=static void __init pte_swap_soft_dirty_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-731-\nmm/debug_vm_pgtable.c:732:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/debug_vm_pgtable.c-733-static void __init pmd_soft_dirty_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c=749=static void __init pmd_leaf_soft_dirty_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-767-}\nmm/debug_vm_pgtable.c:768:#else  /* !CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-769-static void __init pmd_soft_dirty_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c=770=static void __init pmd_leaf_soft_dirty_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c:771:#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-772-\n--\nmm/debug_vm_pgtable.c=901=static void __init hugetlb_basic_tests(struct pgtable_debug_args *args) { }\n--\nmm/debug_vm_pgtable.c-903-\nmm/debug_vm_pgtable.c:904:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/debug_vm_pgtable.c-905-static void __init pmd_thp_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-933-\nmm/debug_vm_pgtable.c:934:#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/debug_vm_pgtable.c-935-static void __init pud_thp_tests(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-953-}\nmm/debug_vm_pgtable.c:954:#else  /* !CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */\nmm/debug_vm_pgtable.c-955-static void __init pud_thp_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c:956:#endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */\nmm/debug_vm_pgtable.c:957:#else  /* !CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-958-static void __init pmd_thp_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c=959=static void __init pud_thp_tests(struct pgtable_debug_args *args) { }\nmm/debug_vm_pgtable.c:960:#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/debug_vm_pgtable.c-961-\n--\nmm/debug_vm_pgtable.c=987=static void __init destroy_args(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-989-\t/* Free (huge) page */\nmm/debug_vm_pgtable.c:990:\tif (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) \u0026\u0026\nmm/debug_vm_pgtable.c-991-\t    has_transparent_pud_hugepage() \u0026\u0026\n--\nmm/debug_vm_pgtable.c-998-\nmm/debug_vm_pgtable.c:999:\tif (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) \u0026\u0026\nmm/debug_vm_pgtable.c-1000-\t    has_transparent_hugepage() \u0026\u0026\n--\nmm/debug_vm_pgtable.c=1143=static int __init init_args(struct pgtable_debug_args *args)\n--\nmm/debug_vm_pgtable.c-1239-\t */\nmm/debug_vm_pgtable.c:1240:\tif (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) \u0026\u0026\nmm/debug_vm_pgtable.c-1241-\t    has_transparent_pud_hugepage()) {\n--\nmm/debug_vm_pgtable.c-1250-\nmm/debug_vm_pgtable.c:1251:\tif (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) \u0026\u0026\nmm/debug_vm_pgtable.c-1252-\t    has_transparent_hugepage()) {\n--\nmm/filemap.c=3329=static struct file *do_sync_mmap_readahead(struct vm_fault *vmf)\n--\nmm/filemap.c-3341-\t/* Use the readahead code, even if readahead is disabled */\nmm/filemap.c:3342:\tif (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) \u0026\u0026 (vm_flags \u0026 VM_HUGEPAGE)) {\nmm/filemap.c-3343-\t\t/*\n--\nmm/gup.c=701=static struct page *follow_huge_pmd(struct vm_area_struct *vma,\n--\nmm/gup.c-734-\nmm/gup.c:735:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/gup.c-736-\tif (pmd_trans_huge(pmdval) \u0026\u0026 (flags \u0026 FOLL_TOUCH))\nmm/gup.c-737-\t\ttouch_pmd(vma, addr, pmd, flags \u0026 FOLL_WRITE);\nmm/gup.c:738:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/gup.c-739-\n--\nmm/hmm.c=188=static inline unsigned long hmm_pfn_flags_order(unsigned long order)\n--\nmm/hmm.c-192-\nmm/hmm.c:193:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/hmm.c-194-static inline unsigned long pmd_to_hmm_pfn_flags(struct hmm_range *range,\n--\nmm/hmm.c=204=static int hmm_vma_handle_pmd(struct mm_walk *walk, unsigned long addr,\n--\nmm/hmm.c-227-}\nmm/hmm.c:228:#else /* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/hmm.c-229-/* stub to allow the code below to compile */\nmm/hmm.c=230=int hmm_vma_handle_pmd(struct mm_walk *walk, unsigned long addr,\nmm/hmm.c-231-\t\tunsigned long end, unsigned long hmm_pfns[], pmd_t pmd);\nmm/hmm.c:232:#endif /* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/hmm.c-233-\n--\nmm/hmm.c=403=static int hmm_vma_walk_pmd(pmd_t *pmdp,\n--\nmm/hmm.c-479-\nmm/hmm.c:480:#if defined(CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD)\nmm/hmm.c-481-static inline unsigned long pud_to_hmm_pfn_flags(struct hmm_range *range,\n--\nmm/huge_memory.c=61=unsigned long transparent_hugepage_flags __read_mostly =\nmm/huge_memory.c:62:#ifdef CONFIG_TRANSPARENT_HUGEPAGE_ALWAYS\nmm/huge_memory.c:63:\t(1\u003c\u003cTRANSPARENT_HUGEPAGE_FLAG)|\nmm/huge_memory.c-64-#endif\nmm/huge_memory.c:65:#ifdef CONFIG_TRANSPARENT_HUGEPAGE_MADVISE\nmm/huge_memory.c:66:\t(1\u003c\u003cTRANSPARENT_HUGEPAGE_REQ_MADV_FLAG)|\nmm/huge_memory.c-67-#endif\nmm/huge_memory.c:68:\t(1\u003c\u003cTRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG)|\nmm/huge_memory.c:69:\t(1\u003c\u003cTRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG)|\nmm/huge_memory.c:70:\t(1\u003c\u003cTRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);\nmm/huge_memory.c-71-\n--\nmm/huge_memory.c=419=static ssize_t enabled_show(struct kobject *kobj,\n--\nmm/huge_memory.c-423-\nmm/huge_memory.c:424:\tif (test_bit(TRANSPARENT_HUGEPAGE_FLAG, \u0026transparent_hugepage_flags))\nmm/huge_memory.c-425-\t\toutput = \"[always] madvise never\";\nmm/huge_memory.c:426:\telse if (test_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,\nmm/huge_memory.c-427-\t\t\t  \u0026transparent_hugepage_flags))\n--\nmm/huge_memory.c=461=static bool set_global_enabled_mode(enum global_enabled_mode mode)\n--\nmm/huge_memory.c-463-\tstatic const unsigned long thp_flags[] = {\nmm/huge_memory.c:464:\t\tTRANSPARENT_HUGEPAGE_FLAG,\nmm/huge_memory.c:465:\t\tTRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,\nmm/huge_memory.c-466-\t};\n--\nmm/huge_memory.c=556=static const enum transparent_hugepage_flag defrag_flags[] = {\nmm/huge_memory.c:557:\t[DEFRAG_ALWAYS]\t\t= TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG,\nmm/huge_memory.c:558:\t[DEFRAG_DEFER]\t\t= TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG,\nmm/huge_memory.c:559:\t[DEFRAG_DEFER_MADVISE]\t= TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG,\nmm/huge_memory.c:560:\t[DEFRAG_MADVISE]\t= TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG,\nmm/huge_memory.c-561-};\n--\nmm/huge_memory.c=613=static ssize_t use_zero_page_show(struct kobject *kobj,\n--\nmm/huge_memory.c-616-\treturn single_hugepage_flag_show(kobj, attr, buf,\nmm/huge_memory.c:617:\t\t\t\t\t TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);\nmm/huge_memory.c-618-}\nmm/huge_memory.c=619=static ssize_t use_zero_page_store(struct kobject *kobj,\n--\nmm/huge_memory.c-622-\treturn single_hugepage_flag_store(kobj, attr, buf, count,\nmm/huge_memory.c:623:\t\t\t\t TRANSPARENT_HUGEPAGE_USE_ZERO_PAGE_FLAG);\nmm/huge_memory.c-624-}\n--\nmm/huge_memory.c=1089=static int __init hugepage_init(void)\n--\nmm/huge_memory.c-1094-\tif (!has_transparent_hugepage()) {\nmm/huge_memory.c:1095:\t\ttransparent_hugepage_flags = 1 \u003c\u003c TRANSPARENT_HUGEPAGE_UNSUPPORTED;\nmm/huge_memory.c-1096-\t\treturn -EINVAL;\n--\nmm/huge_memory.c=1142=static int __init setup_transparent_hugepage(char *str)\n--\nmm/huge_memory.c-1148-\tif (!strcmp(str, \"always\")) {\nmm/huge_memory.c:1149:\t\tset_bit(TRANSPARENT_HUGEPAGE_FLAG,\nmm/huge_memory.c-1150-\t\t\t\u0026transparent_hugepage_flags);\nmm/huge_memory.c:1151:\t\tclear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,\nmm/huge_memory.c-1152-\t\t\t  \u0026transparent_hugepage_flags);\n--\nmm/huge_memory.c-1154-\t} else if (!strcmp(str, \"madvise\")) {\nmm/huge_memory.c:1155:\t\tclear_bit(TRANSPARENT_HUGEPAGE_FLAG,\nmm/huge_memory.c-1156-\t\t\t  \u0026transparent_hugepage_flags);\nmm/huge_memory.c:1157:\t\tset_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,\nmm/huge_memory.c-1158-\t\t\t\u0026transparent_hugepage_flags);\n--\nmm/huge_memory.c-1160-\t} else if (!strcmp(str, \"never\")) {\nmm/huge_memory.c:1161:\t\tclear_bit(TRANSPARENT_HUGEPAGE_FLAG,\nmm/huge_memory.c-1162-\t\t\t  \u0026transparent_hugepage_flags);\nmm/huge_memory.c:1163:\t\tclear_bit(TRANSPARENT_HUGEPAGE_REQ_MADV_FLAG,\nmm/huge_memory.c-1164-\t\t\t  \u0026transparent_hugepage_flags);\n--\nmm/huge_memory.c=1520=gfp_t vma_thp_gfp_mask(struct vm_area_struct *vma)\n--\nmm/huge_memory.c-1524-\t/* Always do synchronous compaction */\nmm/huge_memory.c:1525:\tif (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_DIRECT_FLAG, \u0026transparent_hugepage_flags))\nmm/huge_memory.c-1526-\t\treturn GFP_TRANSHUGE | (vma_madvised ? 0 : __GFP_NORETRY);\n--\nmm/huge_memory.c-1528-\t/* Kick kcompactd and fail quickly */\nmm/huge_memory.c:1529:\tif (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_FLAG, \u0026transparent_hugepage_flags))\nmm/huge_memory.c-1530-\t\treturn GFP_TRANSHUGE_LIGHT | __GFP_KSWAPD_RECLAIM;\n--\nmm/huge_memory.c-1532-\t/* Synchronous compaction if madvised, otherwise kick kcompactd */\nmm/huge_memory.c:1533:\tif (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_KSWAPD_OR_MADV_FLAG, \u0026transparent_hugepage_flags))\nmm/huge_memory.c-1534-\t\treturn GFP_TRANSHUGE_LIGHT |\n--\nmm/huge_memory.c-1538-\t/* Only do synchronous compaction if madvised */\nmm/huge_memory.c:1539:\tif (test_bit(TRANSPARENT_HUGEPAGE_DEFRAG_REQ_MADV_FLAG, \u0026transparent_hugepage_flags))\nmm/huge_memory.c-1540-\t\treturn GFP_TRANSHUGE_LIGHT |\n--\nmm/huge_memory.c=1747=EXPORT_SYMBOL_GPL(vmf_insert_folio_pmd);\nmm/huge_memory.c-1748-\nmm/huge_memory.c:1749:#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/huge_memory.c-1750-static pud_t maybe_pud_mkwrite(pud_t pud, struct vm_area_struct *vma)\n--\nmm/huge_memory.c=1863=EXPORT_SYMBOL_GPL(vmf_insert_folio_pud);\nmm/huge_memory.c:1864:#endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */\nmm/huge_memory.c-1865-\n--\nmm/huge_memory.c=1948=int copy_huge_pmd(struct mm_struct *dst_mm, struct mm_struct *src_mm,\n--\nmm/huge_memory.c-2059-\nmm/huge_memory.c:2060:#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/huge_memory.c-2061-void touch_pud(struct vm_area_struct *vma, unsigned long addr,\n--\nmm/huge_memory.c=2109=void huge_pud_set_accessed(struct vm_fault *vmf, pud_t orig_pud)\n--\nmm/huge_memory.c-2120-}\nmm/huge_memory.c:2121:#endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */\nmm/huge_memory.c-2122-\n--\nmm/huge_memory.c=2725=int change_huge_pmd(struct mmu_gather *tlb, struct vm_area_struct *vma,\n--\nmm/huge_memory.c-2832- */\nmm/huge_memory.c:2833:#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/huge_memory.c-2834-int change_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,\n--\nmm/huge_memory.c=3024=spinlock_t *__pud_trans_huge_lock(pud_t *pud, struct vm_area_struct *vma)\n--\nmm/huge_memory.c-3034-\nmm/huge_memory.c:3035:#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/huge_memory.c-3036-int zap_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,\n--\nmm/huge_memory.c=3123=void __split_huge_pud(struct vm_area_struct *vma, pud_t *pud,\n--\nmm/huge_memory.c-3126-}\nmm/huge_memory.c:3127:#endif /* CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD */\nmm/huge_memory.c-3128-\n--\nmm/khugepaged.c=183=static ssize_t defrag_show(struct kobject *kobj,\n--\nmm/khugepaged.c-186-\treturn single_hugepage_flag_show(kobj, attr, buf,\nmm/khugepaged.c:187:\t\t\t\t\t TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);\nmm/khugepaged.c-188-}\nmm/khugepaged.c=189=static ssize_t defrag_store(struct kobject *kobj,\n--\nmm/khugepaged.c-193-\treturn single_hugepage_flag_store(kobj, attr, buf, count,\nmm/khugepaged.c:194:\t\t\t\t TRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG);\nmm/khugepaged.c-195-}\n--\nmm/khugepaged.c=918=static bool collapse_scan_abort(int nid, struct collapse_control *cc)\n--\nmm/khugepaged.c-943-\t(transparent_hugepage_flags \u0026\t\t\t\t\\\nmm/khugepaged.c:944:\t (1\u003c\u003cTRANSPARENT_HUGEPAGE_DEFRAG_KHUGEPAGED_FLAG))\nmm/khugepaged.c-945-\n--\nmm/ksm.c=2526=static int ksm_next_page_pmd_entry(pmd_t *pmdp, unsigned long addr, unsigned long end,\n--\nmm/ksm.c-2546-\nmm/ksm.c:2547:\tif (IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) \u0026\u0026 pmd_leaf(pmd)) {\nmm/ksm.c-2548-\t\tptl = pmd_lock(mm, pmdp);\n--\nmm/madvise.c=364=static int madvise_cold_or_pageout_pte_range(pmd_t *pmd,\n--\nmm/madvise.c-386-\nmm/madvise.c:387:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/madvise.c-388-\tif (pmd_trans_huge(*pmd)) {\n--\nmm/madvise.c=879=bool madvise_dontneed_free_valid_vma(struct madvise_behavior *madv_behavior)\n--\nmm/madvise.c-909-\nmm/madvise.c:910:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/madvise.c-911-\n--\nmm/madvise.c=959=static int madvise_collapse(struct madvise_behavior *madv_behavior)\n--\nmm/madvise.c-1065-\nmm/madvise.c:1066:#else\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/madvise.c-1067-\nmm/madvise.c=1068=static int madvise_collapse(struct madvise_behavior *madv_behavior)\n--\nmm/madvise.c-1072-\nmm/madvise.c:1073:#endif\t/* CONFIG_TRANSPARENT_HUGEPAGE */\nmm/madvise.c-1074-\n--\nmm/madvise.c=1704=madvise_behavior_valid(int behavior)\n--\nmm/madvise.c-1724-#endif\nmm/madvise.c:1725:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/madvise.c-1726-\tcase MADV_HUGEPAGE:\n--\nmm/mapping_dirty_helpers.c=148=static int wp_clean_pud_entry(pud_t *pud, unsigned long addr, unsigned long end,\n--\nmm/mapping_dirty_helpers.c-150-{\nmm/mapping_dirty_helpers.c:151:#ifdef CONFIG_HAVE_ARCH_TRANSPARENT_HUGEPAGE_PUD\nmm/mapping_dirty_helpers.c-152-\tpud_t pudval = pudp_get(pud);\n--\nmm/memcontrol-v1.c=1826=static const unsigned int memcg1_stats[] = {\n--\nmm/memcontrol-v1.c-1828-\tNR_ANON_MAPPED,\nmm/memcontrol-v1.c:1829:#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/memcontrol-v1.c-1830-\tNR_ANON_THPS,\n--\nmm/memcontrol-v1.c=1844=static const char *const memcg1_stat_names[] = {\n--\nmm/memcontrol-v1.c-1846-\t\"rss\",\n\n"
}

5/2 2026/09/20 07:11 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23420
							output: 25
							thoughts: 101
						

Thoughts:
**Investigating the Interplay of THP and SHMEM**

Okay, let's break this down. First, I see a clear link in the `mm/Makefile`: if `CONFIG_TRANSPARENT_HUGEPAGE` is enabled, the `huge_memory.o` and `khugepaged.o` object files get included. That's our starting point. Then, I notice that in `shmem.c`, we've got an `#ifdef CONFIG_TRANSPARENT_HUGEPAGE` conditional guarding `shmem_hpage_enabled`. So, it's pretty obvious that Transparent Huge Pages (THP) have some influence on shared memory (SHMEM). And since `SHMEM` is relevant, I should check `CONFIG_SHMEM` in Kconfig to understand the relationship between the configurations.



6/2 2026/09/20 07:11 tool grepper
0m Args:
{
  "Expression": "config SHMEM",
  "PathPrefix": "init/"
}

Results:
{
  "Output": "init/Kconfig=1932=config EVENTFD\n--\ninit/Kconfig-1940-\ninit/Kconfig:1941:config SHMEM\ninit/Kconfig-1942-\tbool \"Use full shmem filesystem\" if EXPERT\n"
}

7/2 2026/09/20 07:11 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 23800
							output: 33
							thoughts: 107
						

Thoughts:
**Kernel Configuration Exploration**

Okay, so `CONFIG_SHMEM` defaults to 'y', that's fine. But I'm curious about the interaction with `CONFIG_TRANSPARENT_HUGEPAGE`. Time to bring up `menuconfig` and check out the `TRANSPARENT_HUGEPAGE` option directly.

Right, `TRANSPARENT_HUGEPAGE` depends on `HAVE_ARCH_TRANSPARENT_HUGEPAGE` and it's excluding `PREEMPT_RT`. Not surprising, but let me just double-check, is that the *only* dependency? Gotta be sure.

Let's dig a bit deeper. I should look in `init/Kconfig` or `mm/Kconfig` around the `TRANSPARENT_HUGEPAGE` setting itself. Need to understand the full picture here to be certain.



8/2 2026/09/20 07:11 tool grepper
0m Args:
{
  "Expression": "menuconfig TRANSPARENT_HUGEPAGE",
  "PathPrefix": "mm/Kconfig"
}

Results:
{
  "Output": "mm/Kconfig=831=config MM_ID\n--\nmm/Kconfig-833-\nmm/Kconfig:834:menuconfig TRANSPARENT_HUGEPAGE\nmm/Kconfig-835-\tbool \"Transparent Hugepage Support\"\n"
}

9/2 2026/09/20 07:11 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24203
							output: 32
							thoughts: 20
						

Thoughts:
Here's my summary, as though I'm reading and processing the `mm/Kconfig` section:

**Diving into `mm/Kconfig` - Lines 830-850**

Okay, let's zero in on lines 830 to 850 within the `mm/Kconfig` file. Given my background, I'm expecting this section to deal with memory management configuration options, specifically kernel configuration. I'm keen to see if it's related to some of the issues I've been wrestling with in the NUMA implementation lately.

Immediately, I'm trying to deduce the level of abstraction these lines are working at. Is this about low-level hardware interaction or higher-level memory allocation strategies? Are these options about enabling/disabling certain memory management features, or are we configuring parameters related to those features? My experience tells me that these types of files are often a mix of both. I am looking for keywords related to NUMA configurations or options that might influence performance, related to how the kernel uses the hardware.

I'll be looking for any clues that suggest potential conflicts or dependencies between these options and other kernel features. My mind is already primed to identify possible interactions with slab allocators, page migration, or the specific hardware models I'm focusing on. It's likely that these lines will offer some critical insight, especially if I can connect them to the specific performance bottlenecks I've been investigating.



10/2 2026/09/20 07:12 tool read-file
0m Args:
{
  "File": "mm/Kconfig",
  "FirstLine": 830,
  "LineCount": 25
}

Results:
{
  "Contents": " 830:\t\n 831:\tconfig MM_ID\n 832:\t\tdef_bool n\n 833:\t\n 834:\tmenuconfig TRANSPARENT_HUGEPAGE\n 835:\t\tbool \"Transparent Hugepage Support\"\n 836:\t\tdepends on HAVE_ARCH_TRANSPARENT_HUGEPAGE \u0026\u0026 !PREEMPT_RT\n 837:\t\tselect COMPACTION\n 838:\t\tselect XARRAY_MULTI\n 839:\t\tselect MM_ID\n 840:\t\thelp\n 841:\t\t  Transparent Hugepages allows the kernel to use huge pages and\n 842:\t\t  huge tlb transparently to the applications whenever possible.\n 843:\t\t  This feature can improve computing performance to certain\n 844:\t\t  applications by speeding up page faults during memory\n 845:\t\t  allocation, by reducing the number of tlb misses and by speeding\n 846:\t\t  up the pagetable walking.\n 847:\t\n 848:\t\t  If memory constrained on embedded, you may want to say N.\n 849:\t\n 850:\tif TRANSPARENT_HUGEPAGE\n 851:\t\n 852:\tchoice\n 853:\t\tprompt \"Transparent Hugepage Support sysfs defaults\"\n 854:\t\tdefault TRANSPARENT_HUGEPAGE_ALWAYS\n"
}

11/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24913
							output: 37
							thoughts: 305
						

Thoughts:
**Analyzing the Patch for Transparent Huge Pages and Shared Memory**

Alright, so the focus is clearly on `TRANSPARENT_HUGEPAGE` and how it interacts with `SHMEM`. I need to get a good understanding of what's changing here.

First, I need to see exactly where the code's being touched, what functions are modified or involved. Diving into the details, it looks like a lot of the changes are concentrated in `mm/khugepaged.c` and `mm/shmem.c`, with a minor touch in `mm/madvise.c`.

Specifically, in `mm/khugepaged.c`, the patch seems to be modifying functions like `collapse_file`, `collapse_scan_file`, `collapse_scan_pmd`, `collapse_run_pmd`, `mthp_collapse`, and the helper `collapse_min_mthp_order`. Plus, there are obviously a few key functions to review like `hugepage_enabled` and `collapse_possible_orders`. These functions are central to how khugepaged collapses pages, and any change there needs to be understood.

Then, there's `mm/shmem.c`. The functions modified here are: `shmem_parse_huge`, `shmem_hpage_enabled`, `shmem_enabled_store`, `setup_transparent_hugepage_shmem`, and `setup_transparent_hugepage_tmpfs`. Clearly, this is where the integration between transparent huge pages and shared memory is happening. I need to fully understand how these functions are interacting with each other.

Finally, in `mm/madvise.c`, the patch touches `madvise_vma_behavior`. This probably impacts how we advise the kernel on memory usage, which in turn would influence the behavior of the huge pages.

To truly grasp the impact of this, I need to go in and read `mm/khugepaged.c` in detail. I'll need to look closely at functions like `mthp_collapse` and the collapse related files (`collapse_file`, `collapse_scan_file`, `collapse_run_pmd`) to see exactly how these changes affect the overall behavior.



12/2 2026/09/20 07:12 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1460,
  "LineCount": 60
}

Results:
{
  "Contents": "1460:\t\t\tif (nr_eligible_ptes \u003e= nr_ptes - max_ptes_none) {\n1461:\t\t\t\tenum scan_result ret;\n1462:\t\n1463:\t\t\t\tcollapse_address = address + offset * PAGE_SIZE;\n1464:\t\t\t\tif (cc-\u003escan_file)\n1465:\t\t\t\t\tret = collapse_file(mm, collapse_address, cc-\u003escan_file,\n1466:\t\t\t\t\t\t\tcc-\u003escan_pgoff + offset, cc, order);\n1467:\t\t\t\telse\n1468:\t\t\t\t\tret = collapse_huge_page(mm, collapse_address, cc, order);\n1469:\t\n1470:\t\t\t\tswitch (ret) {\n1471:\t\t\t\t/* Cases where we continue to next collapse candidate */\n1472:\t\t\t\tcase SCAN_SUCCEED:\n1473:\t\t\t\t\tcollapsed += nr_ptes;\n1474:\t\t\t\t\tfallthrough;\n1475:\t\t\t\tcase SCAN_PTE_MAPPED_HUGEPAGE:\n1476:\t\t\t\t\t/*\n1477:\t\t\t\t\t * Return SCAN_PTE_MAPPED_HUGEPAGE to call\n1478:\t\t\t\t\t * collapse_pte_mapped_thp() if the page cache\n1479:\t\t\t\t\t * already holds the PMD folio.\n1480:\t\t\t\t\t */\n1481:\t\t\t\t\tif (order == HPAGE_PMD_ORDER)\n1482:\t\t\t\t\t\tlast_result = ret;\n1483:\t\t\t\t\tgoto next_offset;\n1484:\t\t\t\t/* Cases where lower orders might still succeed */\n1485:\t\t\t\tcase SCAN_ALLOC_HUGE_PAGE_FAIL:\n1486:\t\t\t\t\talloc_failed = true;\n1487:\t\t\t\t\tfallthrough;\n1488:\t\t\t\tcase SCAN_LACK_REFERENCED_PAGE:\n1489:\t\t\t\tcase SCAN_EXCEED_NONE_PTE:\n1490:\t\t\t\tcase SCAN_EXCEED_SWAP_PTE:\n1491:\t\t\t\tcase SCAN_EXCEED_SHARED_PTE:\n1492:\t\t\t\tcase SCAN_PAGE_LOCK:\n1493:\t\t\t\tcase SCAN_PAGE_COUNT:\n1494:\t\t\t\tcase SCAN_PAGE_NULL:\n1495:\t\t\t\tcase SCAN_DEL_PAGE_LRU:\n1496:\t\t\t\tcase SCAN_PTE_NON_PRESENT:\n1497:\t\t\t\tcase SCAN_PTE_UFFD:\n1498:\t\t\t\tcase SCAN_PAGE_LAZYFREE:\n1499:\t\t\t\t\tlast_result = ret;\n1500:\t\t\t\t\tgoto next_order;\n1501:\t\t\t\t/* Cases where no further collapse is possible */\n1502:\t\t\t\tcase SCAN_PMD_MAPPED:\n1503:\t\t\t\t\tfallthrough;\n1504:\t\t\t\tdefault:\n1505:\t\t\t\t\tlast_result = ret;\n1506:\t\t\t\t\tgoto done;\n1507:\t\t\t\t}\n1508:\t\t\t}\n1509:\t\n1510:\tnext_order:\n1511:\t\t\t/*\n1512:\t\t\t * Continue with the next smaller order if there is still\n1513:\t\t\t * any smaller order enabled. When at the smallest order\n1514:\t\t\t * we must always move to the next offset.\n1515:\t\t\t */\n1516:\t\t\tif (order \u003e collapse_min_mthp_order(cc-\u003escan_file) \u0026\u0026\n1517:\t\t\t    (cc-\u003escan_orders \u0026 GENMASK(order - 1, 0))) {\n1518:\t\t\t\torder--;\n1519:\t\t\t\tcontinue;\n"
}

13/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 26633
							output: 37
							thoughts: 75
						

Thoughts:
Here's my take on those code segments and what they suggest we're dealing with:

**Analyzing Collapse Functions**

Okay, so I'm looking at these "collapse" functions – `collapse_scan_pmd`, `collapse_run_pmd`, `mthp_collapse`, and `collapse_file`, `collapse_scan_file`. From the naming conventions, it looks like they're designed to handle data reduction or aggregation. The "collapse" suggests we're compressing or summarizing some kind of dataset. The suffixes hint at the data source or context: "scan," "run," and "file." "PMD" is likely referencing a specific data format or processing methodology, perhaps Particle Matter Data, or something similar, maybe a proprietary internal format.

I'll specifically focus on `collapse_scan_pmd` and `collapse_run_pmd` around lines 2835-2900. I'll need to dig into the implementation, I need to understand what's being collapsed and why. Are we reducing the dimensionality of a scan result? Are we aggregating run data over time or some other parameter? Are there specific criteria involved, such as thresholds, error conditions, or statistical measures? Based on the naming, it seems likely that `collapse_scan_pmd` deals with the collapsing of scanned data, and `collapse_run_pmd` deals with the collapsing of the collected run data. This is an important distinction to understand how the data is being represented during processing, and how it is ultimately going to be used and/or stored. Knowing the details of these functions will be key to understanding the data flow and how it's being represented in the program as a whole.



14/2 2026/09/20 07:12 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 2835,
  "LineCount": 65
}

Results:
{
  "Contents": "2835:\t * what the scan returned; anything else is why there is nothing to do.\n2836:\t */\n2837:\tenum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n2838:\t\t\tunsigned long addr, struct collapse_control *cc,\n2839:\t\t\tunsigned long orders)\n2840:\t{\n2841:\t\tmmap_assert_locked(vma-\u003evm_mm);\n2842:\t\t/* Whatever the last scan found has to have been run by now */\n2843:\t\tcollapse_put_scan_file(cc);\n2844:\t\n2845:\t\tif (vma_is_anonymous(vma))\n2846:\t\t\treturn collapse_scan_anon_pmd(vma, addr, cc, orders);\n2847:\t\n2848:\t\treturn collapse_scan_file(vma, addr, cc, orders);\n2849:\t}\n2850:\t\n2851:\t/*\n2852:\t * Collapse the table a scan found work in.  @result is what the scan\n2853:\t * returned.\n2854:\t *\n2855:\t * Called without mmap_lock and returns without it, taking what it needs in\n2856:\t * between: what it does -- allocate, isolate, copy, flush -- is slow enough\n2857:\t * that a writer would wait behind it.  The caller gives the lock up first,\n2858:\t * and with it the VMA and anything derived under it.  The run revalidates for\n2859:\t * itself rather than trusting what the scan saw.\n2860:\t */\n2861:\tenum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,\n2862:\t\t\tenum scan_result result, struct collapse_control *cc)\n2863:\t{\n2864:\t\tstruct file *file = cc-\u003escan_file;\n2865:\t\tbool triggered_wb = false;\n2866:\t\n2867:\t\t/* The scan found the PMD folio in place: nothing to collapse */\n2868:\t\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\n2869:\t\t\tgoto retract;\n2870:\t\n2871:\tretry:\n2872:\t\tresult = mthp_collapse(mm, addr, cc);\n2873:\t\t/* Just return the results for anonymous folio collapse. */\n2874:\t\tif (!file)\n2875:\t\t\treturn result;\n2876:\t\n2877:\t\t/* Dirty pages are worth a writeback and one more try, if asked for */\n2878:\t\tif (cc-\u003epolicy.writeback_dirty \u0026\u0026 result == SCAN_PAGE_DIRTY_OR_WRITEBACK \u0026\u0026\n2879:\t\t    !triggered_wb \u0026\u0026 mapping_can_writeback(file-\u003ef_mapping)) {\n2880:\t\t\tpgoff_t pgoff = cc-\u003escan_pgoff;\n2881:\t\t\tconst loff_t lstart = (loff_t)pgoff \u003c\u003c PAGE_SHIFT;\n2882:\t\t\tconst loff_t lend = lstart + HPAGE_PMD_SIZE - 1;\n2883:\t\n2884:\t\t\tfilemap_write_and_wait_range(file-\u003ef_mapping, lstart, lend);\n2885:\t\t\ttriggered_wb = true;\n2886:\t\t\tgoto retry;\n2887:\t\t}\n2888:\tretract:\n2889:\t\tcc-\u003escan_file = NULL;\n2890:\t\tVM_WARN_ON_ONCE(!file);\n2891:\t\tfput(file);\n2892:\t\n2893:\t\t/*\n2894:\t\t * A PMD folio is in the page cache, whether the collapse just put it\n2895:\t\t * there or found it: retract the PTE table, and map the PMD if asked.\n2896:\t\t */\n2897:\t\tif (result == SCAN_PTE_MAPPED_HUGEPAGE) {\n2898:\t\t\tmmap_read_lock(mm);\n2899:\t\t\tif (collapse_test_exit_or_disable(mm))\n"
}

15/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28201
							output: 28
							thoughts: 452
						

Thoughts:
**Analyzing khugepaged Function Symbols**

Okay, let's dive into this `khugepaged.c` file. I'm looking at `collapse_scan_file` and `collapse_file` – and I'm immediately wondering if these are static functions. Static functions can be tricky, as they're internal to the compilation unit. A quick check of the function definitions confirms it. Yes, both `collapse_file` and `collapse_scan_file` are indeed declared as `static`.

Now, the next thought is: does being static in `.c` mean they're definitely not symbols in `vmlinux`? Ah, but hold on, unless the compiler inlines them, they will have symbols! So, they *should* be present, unless they are inlined.

The critical question now becomes: are any of these functions inlined by the compiler? Let's rule that out. I know `collapse_file` is well over 400 lines long, and it's forward declared as `static`, so no way is it inlined. `collapse_scan_file` is also quite lengthy, over 100 lines, so also definitely not inlined.

And *wait*, is `collapse_run_pmd` or `collapse_scan_pmd` static? Nope. I can see from the code, `collapse_run_pmd` is *not* static, so it should be visible outside the compilation unit. Let me confirm `collapse_scan_pmd` is also not static, line 2837 and 2861 confirm this.

So, where are `collapse_scan_pmd` and `collapse_run_pmd` called? I need to track down the call sites. Time to fire up the `grepper`.



16/2 2026/09/20 07:12 tool grepper
0m Args:
{
  "Expression": "collapse_run_pmd",
  "PathPrefix": "mm/"
}

Results:
{
  "Output": "mm/collapse.h=109=unsigned long collapse_possible_orders(struct vm_area_struct *vma,\n--\nmm/collapse.h-117- *     collapse_scan_pmd(vma, addr, ...)      per table\nmm/collapse.h:118: *     collapse_run_pmd(mm, addr, result, cc) when a scan found work\nmm/collapse.h-119- *     collapse_control_release(cc)           once, when done with the control\n--\nmm/collapse.h=145=enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n--\nmm/collapse.h-147-\t\tunsigned long orders);\nmm/collapse.h:148:enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,\nmm/collapse.h-149-\t\tenum scan_result result, struct collapse_control *cc);\n--\nmm/khugepaged.c=2819=void collapse_control_release(struct collapse_control *cc)\n--\nmm/khugepaged.c-2833- * means the page cache already holds the PMD folio and only the PTE table is\nmm/khugepaged.c:2834: * left to retract.  Both are work for collapse_run_pmd(), which is handed\nmm/khugepaged.c-2835- * what the scan returned; anything else is why there is nothing to do.\n--\nmm/khugepaged.c=2837=enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-2860- */\nmm/khugepaged.c:2861:enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,\nmm/khugepaged.c-2862-\t\tenum scan_result result, struct collapse_control *cc)\n--\nmm/khugepaged.c=2911=static void collapse_scan_mm_slot(unsigned int progress_max,\n--\nmm/khugepaged.c-3004-\t\t\tmmap_read_unlock(mm);\nmm/khugepaged.c:3005:\t\t\t*result = collapse_run_pmd(mm, addr, *result, cc);\nmm/khugepaged.c-3006-\t\t\tif (*result == SCAN_SUCCEED)\n--\nmm/madvise.c=959=static int madvise_collapse(struct madvise_behavior *madv_behavior)\n--\nmm/madvise.c-1025-\nmm/madvise.c:1026:\t\tresult = collapse_run_pmd(mm, addr, result, cc);\nmm/madvise.c-1027-tally:\n"
}

17/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 29785
							output: 39
							thoughts: 1935
						

Thoughts:
**Focusing on Target Symbols for MADV_COLLAPSE & Khugepaged**

Okay, let's break this down. My goal here is to identify the crucial functions to target for fuzzing, specifically related to the `MADV_COLLAPSE` system call and the khugepaged background thread. The key is to find *specific feature logic* and entry points, not ubiquitous functions.

First, I see the core functions involved in this patch are `collapse_run_pmd`, called by both the `madvise_collapse` path and the khugepaged scan. Also, `collapse_scan_pmd` is called in those paths, which in turn calls `collapse_scan_file` (or `collapse_scan_anon_pmd` based on an anonymous vma) and `collapse_file`. The `mthp_collapse` function is called by `collapse_run_pmd` which then calls `collapse_file` if `cc->scan_file` is set.  I also see that `madvise_collapse` is called via the system call.  I need to remember that `khugepaged_do_scan` eventually calls `collapse_scan_pmd` and then calls `collapse_run_pmd` in the background.

The patch has modified these functions substantially, especially `collapse_file` which now handles orders, mTHP file/shmem collapse, and various checks. I also see `shmem_hpage_enabled`, `shmem_parse_huge`, and `collapse_possible_orders` are in the mix, and these related to shmem (shared memory).

I'm focused on what I can see in the symbol table. I need to make sure I am fuzzing the right code! The functions directly touched by this patch are present as symbols, and in Linux they are visible because these static functions are in a C file and are not inlined.

However, I remember `madvise_vma_behavior` is *very* common and called for every `madvise` syscall. So it's out.  `madvise_collapse` is the one specific to `MADV_COLLAPSE`!

Now, the interesting bit: I spotted a new assertion, `VM_WARN_ON_ONCE(!file)`. This is worth investigating. In `collapse_run_pmd`, this assertion appears after a call to `mthp_collapse`. Looking at the code, if `result` is `SCAN_PTE_MAPPED_HUGEPAGE`, the function goes to the `retract` label and the assertion fires! But if the PMD folio is mapped, and `file == NULL`, the check will trigger!  Is this possible? I need to check how `collapse_scan_anon_pmd` is called. It may return `SCAN_PTE_MAPPED_HUGEPAGE`, which means the `file == NULL` and the assertion would be triggered. This is a potential bug or unhandled case that warrants fuzzing!

My focus goes to `collapse_run_pmd`, `collapse_scan_pmd`, `mthp_collapse`, `collapse_file`, `collapse_scan_file`, `shmem_hpage_enabled`, `shmem_parse_huge`, `collapse_possible_orders`. And, especially, I should look into the cases where `!file` could be true when calling these. This likely includes examining the path from `khugepaged_do_scan` and the `madvise` syscall path.



18/2 2026/09/20 07:12 tool grepper
0m Args:
{
  "Expression": "SCAN_PTE_MAPPED_HUGEPAGE",
  "PathPrefix": "mm/khugepaged.c"
}

Results:
{
  "Output": "mm/khugepaged.c=609=static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-681-\t\tif (!is_pmd_order(order) \u0026\u0026 folio_order(folio) \u003e= order) {\nmm/khugepaged.c:682:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-683-\t\t\tgoto out;\n--\nmm/khugepaged.c=1431=static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long address,\n--\nmm/khugepaged.c-1474-\t\t\t\tfallthrough;\nmm/khugepaged.c:1475:\t\t\tcase SCAN_PTE_MAPPED_HUGEPAGE:\nmm/khugepaged.c-1476-\t\t\t\t/*\nmm/khugepaged.c:1477:\t\t\t\t * Return SCAN_PTE_MAPPED_HUGEPAGE to call\nmm/khugepaged.c-1478-\t\t\t\t * collapse_pte_mapped_thp() if the page cache\n--\nmm/khugepaged.c=2187=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2362-\t\tif (is_pmd_order(folio_order(folio))) {\nmm/khugepaged.c:2363:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2364-\t\t\tgoto out_unlock;\n--\nmm/khugepaged.c-2371-\t\tif (folio_order(folio) \u003e= order) {\nmm/khugepaged.c:2372:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2373-\t\t\tgoto out_unlock;\n--\nmm/khugepaged.c-2603-\tif (cc-\u003epolicy.install_pmd)\nmm/khugepaged.c:2604:\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2605-\tfolio_unlock(new_folio);\n--\nmm/khugepaged.c=2652=static enum scan_result collapse_scan_file(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-2706-\t\tif (is_pmd_order(folio_order(folio))) {\nmm/khugepaged.c:2707:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2708-\t\t\tfailed_pfn = folio_pfn(folio);\n--\nmm/khugepaged.c-2765-\trcu_read_unlock();\nmm/khugepaged.c:2766:\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c-2767-\t\tcc-\u003eprogress++;\n--\nmm/khugepaged.c-2777-\t/*\nmm/khugepaged.c:2778:\t * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds\nmm/khugepaged.c-2779-\t * the PMD folio, and retracting the PTE table is the run's job.\nmm/khugepaged.c-2780-\t */\nmm/khugepaged.c:2781:\tif (result == SCAN_SUCCEED || result == SCAN_PTE_MAPPED_HUGEPAGE) {\nmm/khugepaged.c-2782-\t\t/*\n--\nmm/khugepaged.c=2819=void collapse_control_release(struct collapse_control *cc)\n--\nmm/khugepaged.c-2831- *\nmm/khugepaged.c:2832: * SCAN_SUCCEED means there is something to collapse.  SCAN_PTE_MAPPED_HUGEPAGE\nmm/khugepaged.c-2833- * means the page cache already holds the PMD folio and only the PTE table is\n--\nmm/khugepaged.c=2861=enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2867-\t/* The scan found the PMD folio in place: nothing to collapse */\nmm/khugepaged.c:2868:\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c-2869-\t\tgoto retract;\n--\nmm/khugepaged.c-2896-\t */\nmm/khugepaged.c:2897:\tif (result == SCAN_PTE_MAPPED_HUGEPAGE) {\nmm/khugepaged.c-2898-\t\tmmap_read_lock(mm);\n--\nmm/khugepaged.c=2911=static void collapse_scan_mm_slot(unsigned int progress_max,\n--\nmm/khugepaged.c-2991-\t\t\tif (*result != SCAN_SUCCEED \u0026\u0026\nmm/khugepaged.c:2992:\t\t\t    *result != SCAN_PTE_MAPPED_HUGEPAGE) {\nmm/khugepaged.c-2993-\t\t\t\tif (cc-\u003eprogress \u003e= progress_max)\n"
}

19/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 33929
							output: 39
							thoughts: 26
						

Thoughts:
Here's my attempt at summarizing the thought process, tailored for an expert audience:

**Diving into khugepaged.c**

Alright, time to troubleshoot this memory issue. I'm going to jump straight into `mm/khugepaged.c`, specifically focusing on the `collapse_scan_anon_pmd` function. This feels like the right place to start digging, given the context. I'm curious about how it handles anonymous pages during collapse scans. There could be something subtle going on there with the PMD handling or possibly contention, particularly given the potential complexity of handling hugepage allocation in the kernel. Let's see what the code reveals!



20/2 2026/09/20 07:12 tool grepper
0m Args:
{
  "Expression": "SCAN_PTE_MAPPED_HUGEPAGE",
  "PathPrefix": "mm/khugepaged.c"
}

Results:
{
  "Output": "mm/khugepaged.c=609=static enum scan_result __collapse_huge_page_isolate(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-681-\t\tif (!is_pmd_order(order) \u0026\u0026 folio_order(folio) \u003e= order) {\nmm/khugepaged.c:682:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-683-\t\t\tgoto out;\n--\nmm/khugepaged.c=1431=static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long address,\n--\nmm/khugepaged.c-1474-\t\t\t\tfallthrough;\nmm/khugepaged.c:1475:\t\t\tcase SCAN_PTE_MAPPED_HUGEPAGE:\nmm/khugepaged.c-1476-\t\t\t\t/*\nmm/khugepaged.c:1477:\t\t\t\t * Return SCAN_PTE_MAPPED_HUGEPAGE to call\nmm/khugepaged.c-1478-\t\t\t\t * collapse_pte_mapped_thp() if the page cache\n--\nmm/khugepaged.c=2187=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2362-\t\tif (is_pmd_order(folio_order(folio))) {\nmm/khugepaged.c:2363:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2364-\t\t\tgoto out_unlock;\n--\nmm/khugepaged.c-2371-\t\tif (folio_order(folio) \u003e= order) {\nmm/khugepaged.c:2372:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2373-\t\t\tgoto out_unlock;\n--\nmm/khugepaged.c-2603-\tif (cc-\u003epolicy.install_pmd)\nmm/khugepaged.c:2604:\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2605-\tfolio_unlock(new_folio);\n--\nmm/khugepaged.c=2652=static enum scan_result collapse_scan_file(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-2706-\t\tif (is_pmd_order(folio_order(folio))) {\nmm/khugepaged.c:2707:\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\nmm/khugepaged.c-2708-\t\t\tfailed_pfn = folio_pfn(folio);\n--\nmm/khugepaged.c-2765-\trcu_read_unlock();\nmm/khugepaged.c:2766:\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c-2767-\t\tcc-\u003eprogress++;\n--\nmm/khugepaged.c-2777-\t/*\nmm/khugepaged.c:2778:\t * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds\nmm/khugepaged.c-2779-\t * the PMD folio, and retracting the PTE table is the run's job.\nmm/khugepaged.c-2780-\t */\nmm/khugepaged.c:2781:\tif (result == SCAN_SUCCEED || result == SCAN_PTE_MAPPED_HUGEPAGE) {\nmm/khugepaged.c-2782-\t\t/*\n--\nmm/khugepaged.c=2819=void collapse_control_release(struct collapse_control *cc)\n--\nmm/khugepaged.c-2831- *\nmm/khugepaged.c:2832: * SCAN_SUCCEED means there is something to collapse.  SCAN_PTE_MAPPED_HUGEPAGE\nmm/khugepaged.c-2833- * means the page cache already holds the PMD folio and only the PTE table is\n--\nmm/khugepaged.c=2861=enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2867-\t/* The scan found the PMD folio in place: nothing to collapse */\nmm/khugepaged.c:2868:\tif (result == SCAN_PTE_MAPPED_HUGEPAGE)\nmm/khugepaged.c-2869-\t\tgoto retract;\n--\nmm/khugepaged.c-2896-\t */\nmm/khugepaged.c:2897:\tif (result == SCAN_PTE_MAPPED_HUGEPAGE) {\nmm/khugepaged.c-2898-\t\tmmap_read_lock(mm);\n--\nmm/khugepaged.c=2911=static void collapse_scan_mm_slot(unsigned int progress_max,\n--\nmm/khugepaged.c-2991-\t\t\tif (*result != SCAN_SUCCEED \u0026\u0026\nmm/khugepaged.c:2992:\t\t\t    *result != SCAN_PTE_MAPPED_HUGEPAGE) {\nmm/khugepaged.c-2993-\t\t\t\tif (cc-\u003eprogress \u003e= progress_max)\n"
}

21/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 35539
							output: 37
							thoughts: 57
						

Thoughts:
Here's my take on those thoughts:

**Analyzing `collapse_scan_anon_pmd` Behavior**

Alright, so the question is: does this `collapse_scan_anon_pmd` function actually return `SCAN_PTE_MAPPED_HUGEPAGE`? I need to quickly verify that. Let me jump into the code and take a look at the relevant portion, specifically lines 1350 to 1430 in `mm/khugepaged.c`. That's where I'd expect to find the logic that determines the return value and I can quickly spot the exit paths and conditions that would result in returning the flag. I am already anticipating where to look for potential areas of concern, depending on the architecture. I'll focus on the conditions under which it *might* return that particular flag and make a quick assessment if my assumptions are correct, or if something else is at play.



22/2 2026/09/20 07:12 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1370,
  "LineCount": 50
}

Results:
{
  "Contents": "1370:\t\t\tpgtable_trans_huge_deposit(mm, pmd, pgtable);\n1371:\t\t\tmap_anon_folio_pmd_nopf(folio, pmd, vma, pmd_addr);\n1372:\t\t} else {\n1373:\t\t\t/*\n1374:\t\t\t * Some architectures (e.g. MIPS) walk the live page table in\n1375:\t\t\t * their implementation. update_mmu_cache_range() must be called\n1376:\t\t\t * with a valid page table hierarchy and the PTE lock held.\n1377:\t\t\t * Acquire it nested inside pmd_ptl when they are distinct locks.\n1378:\t\t\t */\n1379:\t\t\tif (pte_ptl != pmd_ptl)\n1380:\t\t\t\tspin_lock_nested(pte_ptl, SINGLE_DEPTH_NESTING);\n1381:\t\t\tpmd_populate(mm, pmd, pmd_pgtable(_pmd));\n1382:\t\t\tmap_anon_folio_pte_nopf(folio, pte, vma, start_addr,\n1383:\t\t\t\t\t\t  /*uffd_wp=*/ false);\n1384:\t\t\tif (pte_ptl != pmd_ptl)\n1385:\t\t\t\tspin_unlock(pte_ptl);\n1386:\t\t}\n1387:\t\tspin_unlock(pmd_ptl);\n1388:\t\n1389:\t\tfolio = NULL;\n1390:\t\n1391:\t\tresult = SCAN_SUCCEED;\n1392:\tout_up_write:\n1393:\t\tif (pte)\n1394:\t\t\tpte_unmap(pte);\n1395:\t\tif (anon_vma_locked)\n1396:\t\t\tanon_vma_unlock_write(vma-\u003eanon_vma);\n1397:\t\tmmap_write_unlock(mm);\n1398:\tout_nolock:\n1399:\t\tif (folio)\n1400:\t\t\tfolio_put(folio);\n1401:\t\ttrace_mm_collapse_huge_page(mm, result == SCAN_SUCCEED, result, order);\n1402:\t\treturn result;\n1403:\t}\n1404:\t\n1405:\t/* Return the highest naturally aligned order that fits at @offset within a PMD. */\n1406:\tstatic unsigned int max_order_from_offset(unsigned int offset)\n1407:\t{\n1408:\t\tif (offset == 0)\n1409:\t\t\treturn HPAGE_PMD_ORDER;\n1410:\t\n1411:\t\treturn min_t(unsigned int, __ffs(offset), HPAGE_PMD_ORDER);\n1412:\t}\n1413:\t\n1414:\t/*\n1415:\t * mthp_collapse() consumes the bitmap that is generated during\n1416:\t * collapse_scan_pmd() to determine what regions and mTHP orders fit best.\n1417:\t *\n1418:\t * Each bit in cc-\u003eeligible_ptes marks a PTE the scan accepted as a collapse\n1419:\t * source. We start at the PMD order and check if it is eligible for collapse;\n"
}

23/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 36672
							output: 36
							thoughts: 14
						

Thoughts:
Okay, here's my take on those thoughts, tailored for an expert audience, presented in the first person:

**Checking `collapse_scan_anon_pmd`**

Right, let's dive into this `collapse_scan_anon_pmd` functionality. My initial thought is to quickly assess its purpose. I'm assuming it's related to some anonymization process for scan data, likely a post-processing step. I need to understand its role within the broader pipeline – is it for noise reduction, feature extraction, outlier removal, or something else entirely? The 'PMD' suffix suggests we might be dealing with some form of partial metadata de-identification or obfuscation, or maybe partial model data. I need to keep in mind possible implications on statistical power, feature interpretability, and any potential for introducing bias depending on the implementation details. Let’s start with that.



24/2 2026/09/20 07:12 tool grepper
0m Args:
{
  "Expression": "collapse_scan_anon_pmd",
  "PathPrefix": "mm/khugepaged.c"
}

Results:
{
  "Output": "mm/khugepaged.c=1431=static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long address,\n--\nmm/khugepaged.c-1541-\nmm/khugepaged.c:1542:static enum scan_result collapse_scan_anon_pmd(struct vm_area_struct *vma,\nmm/khugepaged.c-1543-\t\tunsigned long start_addr, struct collapse_control *cc,\n--\nmm/khugepaged.c=2837=enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-2845-\tif (vma_is_anonymous(vma))\nmm/khugepaged.c:2846:\t\treturn collapse_scan_anon_pmd(vma, addr, cc, orders);\nmm/khugepaged.c-2847-\n"
}

25/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 37160
							output: 37
							thoughts: 14
						

Thoughts:
Okay, let's dive into this. Here's my take on those thoughts, as if they're my own:

**Analyzing the Function: `collapse_scan_anon_pmd`**

Alright, time to get into it. Let's see what's happening with this `collapse_scan_anon_pmd` function. Seems like it's likely involved with managing potentially anonymous page-table entries during a scan operation. The name itself is fairly descriptive, breaking it down piece by piece. "Collapse" suggests some kind of merging or reduction of information, "scan" indicates it's part of an iterative process, "anon" likely refers to anonymous memory pages, and "pmd" points to the page-map directory level within the virtual memory hierarchy. So, this function is responsible for handling potentially anonymous pmd entries as part of a scanning operation, collapsing them somehow. My initial thought is it's probably related to memory management and likely optimization. I’m eager to see the nuances of its implementation.



26/2 2026/09/20 07:12 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1542,
  "LineCount": 40
}

Results:
{
  "Contents": "1542:\tstatic enum scan_result collapse_scan_anon_pmd(struct vm_area_struct *vma,\n1543:\t\t\tunsigned long start_addr, struct collapse_control *cc,\n1544:\t\t\tunsigned long enabled_orders)\n1545:\t{\n1546:\t\tconst unsigned int max_ptes_shared = collapse_max_ptes_shared(cc, HPAGE_PMD_ORDER);\n1547:\t\tconst unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);\n1548:\t\tunsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER);\n1549:\t\tstruct mm_struct *mm = vma-\u003evm_mm;\n1550:\t\tpmd_t *pmd;\n1551:\t\tpte_t *pte, *_pte, pteval;\n1552:\t\tint i;\n1553:\t\tint none_or_zero = 0, shared = 0, referenced = 0;\n1554:\t\tenum scan_result result = SCAN_FAIL;\n1555:\t\tstruct page *page = NULL;\n1556:\t\tstruct folio *folio = NULL;\n1557:\t\tunsigned long failed_pfn = -1;\n1558:\t\tunsigned long addr;\n1559:\t\tspinlock_t *ptl;\n1560:\t\tint node = NUMA_NO_NODE, unmapped = 0;\n1561:\t\n1562:\t\tVM_BUG_ON(start_addr \u0026 ~HPAGE_PMD_MASK);\n1563:\t\n1564:\t\tresult = find_pmd_or_thp_or_none(mm, start_addr, \u0026pmd);\n1565:\t\tif (result != SCAN_SUCCEED) {\n1566:\t\t\tcc-\u003eprogress++;\n1567:\t\t\tgoto out;\n1568:\t\t}\n1569:\t\n1570:\t\tcollapse_scan_reset(cc);\n1571:\t\n1572:\t\t/*\n1573:\t\t * If PMD is the only enabled order, enforce max_ptes_none, otherwise\n1574:\t\t * scan all pages to populate the bitmap for mTHP collapse. The bitmap\n1575:\t\t * is then checked again in mthp_collapse() for each attempted order.\n1576:\t\t */\n1577:\t\tif (enabled_orders != BIT(HPAGE_PMD_ORDER))\n1578:\t\t\tmax_ptes_none = COLLAPSE_MAX_PTES_LIMIT;\n1579:\t\n1580:\t\tpte = pte_offset_map_lock(mm, pmd, start_addr, \u0026ptl);\n1581:\t\tif (!pte) {\n"
}

27/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 38161
							output: 41
							thoughts: 22
						

Thoughts:
Okay, let's dive into this code.

**Analyzing the Function: `find_pmd_or_thp_or_none`**

Alright, so the task at hand is to understand the purpose and behavior of this function, `find_pmd_or_thp_or_none`. My initial thought is to figure out what each of the possible outcomes ("PMD", "THP", or "None") actually represents in this context. It's almost certainly related to memory management, likely within a paging system, given the names. My expertise in this area tells me "PMD" likely indicates a Page Map Directory entry, and "THP" is almost certainly Transparent Huge Pages. The "None" outcome is the tricky one. It could mean the address isn't mapped, that the level is mis-defined, or perhaps an error condition. I'll need to explore the code to pin down the exact meaning. I need to understand the logic flow within the function to determine under what circumstances each outcome is reached. Is there a clear decision tree? Are there edge cases I should watch out for, like invalid addresses or corrupted page tables? I need to analyze how it's used and where it's called to understand its context.



28/2 2026/09/20 07:12 tool grepper
0m Args:
{
  "Expression": "find_pmd_or_thp_or_none",
  "PathPrefix": "mm/khugepaged.c"
}

Results:
{
  "Output": "mm/khugepaged.c=1036=static inline enum scan_result check_pmd_state(pmd_t *pmd)\n--\nmm/khugepaged.c-1058-\nmm/khugepaged.c:1059:static enum scan_result find_pmd_or_thp_or_none(struct mm_struct *mm,\nmm/khugepaged.c-1060-\t\tunsigned long address, pmd_t **pmd)\n--\nmm/khugepaged.c=1069=static enum scan_result check_pmd_still_valid(struct mm_struct *mm,\n--\nmm/khugepaged.c-1072-\tpmd_t *new_pmd;\nmm/khugepaged.c:1073:\tenum scan_result result = find_pmd_or_thp_or_none(mm, address, \u0026new_pmd);\nmm/khugepaged.c-1074-\n--\nmm/khugepaged.c=1220=static enum scan_result collapse_huge_page(struct mm_struct *mm,\n--\nmm/khugepaged.c-1253-\nmm/khugepaged.c:1254:\tresult = find_pmd_or_thp_or_none(mm, pmd_addr, \u0026pmd);\nmm/khugepaged.c-1255-\tif (result != SCAN_SUCCEED) {\n--\nmm/khugepaged.c=1542=static enum scan_result collapse_scan_anon_pmd(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-1563-\nmm/khugepaged.c:1564:\tresult = find_pmd_or_thp_or_none(mm, start_addr, \u0026pmd);\nmm/khugepaged.c-1565-\tif (result != SCAN_SUCCEED) {\n--\nmm/khugepaged.c=1795=static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-1819-\t/* Fast check before locking page if already PMD-mapped */\nmm/khugepaged.c:1820:\tresult = find_pmd_or_thp_or_none(mm, haddr, \u0026pmd);\nmm/khugepaged.c-1821-\tif (result == SCAN_PMD_MAPPED)\n--\nmm/khugepaged.c-1850-\nmm/khugepaged.c:1851:\tresult = find_pmd_or_thp_or_none(mm, haddr, \u0026pmd);\nmm/khugepaged.c-1852-\tswitch (result) {\n--\nmm/khugepaged.c=2077=static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)\n--\nmm/khugepaged.c-2097-\t\tmm = vma-\u003evm_mm;\nmm/khugepaged.c:2098:\t\tif (find_pmd_or_thp_or_none(mm, addr, \u0026pmd) != SCAN_SUCCEED)\nmm/khugepaged.c-2099-\t\t\tcontinue;\n"
}

29/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 39353
							output: 37
							thoughts: 497
						

Thoughts:
**Analyzing a Potential Khugepaged Issue**

Okay, let's break this down. I'm looking at how the khugepaged collapse process works, specifically focusing on the anonymous memory case. The flow seems to be: `check_pmd_state` returns some scan result, then `collapse_scan_anon_pmd` is called. That one returns `SCAN_SUCCEED` (or `SCAN_FAIL`, etc.), and importantly, doesn't modify `cc->scan_file`. So, for an anonymous VMA, `collapse_scan_anon_pmd` is called by `collapse_scan_pmd`. The next step is `collapse_run_pmd`, which receives the result from `collapse_scan_anon_pmd` and has `cc->scan_file = NULL`.

Inside `collapse_run_pmd`, there's a specific check: `if (result == SCAN_PTE_MAPPED_HUGEPAGE) goto retract;`. Now, here's where it gets interesting. Can the `result` *ever* be `SCAN_PTE_MAPPED_HUGEPAGE` when `cc->scan_file` is `NULL`? Because if that happens, it will skip directly to the retract path and fput a NULL pointer (which would be bad!). And what's more, could `collapse_scan_pmd` even *return* `SCAN_PTE_MAPPED_HUGEPAGE` for an anon vma? That seems suspicious.

The critical question is whether `collapse_scan_anon_pmd` itself can return `SCAN_PTE_MAPPED_HUGEPAGE`. I need to verify that and see if this is a possible code path. I'm going to look at the code in `mm/khugepaged.c` lines 1660-1720, to check that. I need to trace the possible return values from that function.



30/2 2026/09/20 07:12 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1660,
  "LineCount": 60
}

Results:
{
  "Contents": "1660:\t\t\t * We treat a single page as shared if any part of the THP\n1661:\t\t\t * is shared.\n1662:\t\t\t */\n1663:\t\t\tif (folio_maybe_mapped_shared(folio)) {\n1664:\t\t\t\tif (++shared \u003e max_ptes_shared) {\n1665:\t\t\t\t\tresult = SCAN_EXCEED_SHARED_PTE;\n1666:\t\t\t\t\tfailed_pfn = folio_pfn(folio);\n1667:\t\t\t\t\tcount_collapse_event(HPAGE_PMD_ORDER, THP_SCAN_EXCEED_SHARED_PTE,\n1668:\t\t\t\t\t\t\t     MTHP_STAT_COLLAPSE_EXCEED_SHARED);\n1669:\t\t\t\t\tgoto out_unmap;\n1670:\t\t\t\t}\n1671:\t\t\t}\n1672:\t\n1673:\t\t\t/* The scan accepted this PTE as a collapse source */\n1674:\t\t\t__set_bit(i, cc-\u003eeligible_ptes);\n1675:\t\t\t/*\n1676:\t\t\t * Record which node the original page is from and save this\n1677:\t\t\t * information to cc-\u003enode_load[].\n1678:\t\t\t * Khugepaged will allocate hugepage from the node has the max\n1679:\t\t\t * hit record.\n1680:\t\t\t */\n1681:\t\t\tnode = folio_nid(folio);\n1682:\t\t\tif (collapse_scan_abort(node, cc)) {\n1683:\t\t\t\tresult = SCAN_SCAN_ABORT;\n1684:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1685:\t\t\t\tgoto out_unmap;\n1686:\t\t\t}\n1687:\t\t\tcc-\u003enode_load[node]++;\n1688:\t\t\tif (!folio_test_lru(folio)) {\n1689:\t\t\t\tresult = SCAN_PAGE_LRU;\n1690:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1691:\t\t\t\tgoto out_unmap;\n1692:\t\t\t}\n1693:\t\t\tif (folio_test_locked(folio)) {\n1694:\t\t\t\tresult = SCAN_PAGE_LOCK;\n1695:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1696:\t\t\t\tgoto out_unmap;\n1697:\t\t\t}\n1698:\t\n1699:\t\t\t/*\n1700:\t\t\t * Check if the page has any GUP (or other external) pins.\n1701:\t\t\t *\n1702:\t\t\t * Here the check is racy, but such cases are ephemeral and\n1703:\t\t\t * we can always retry collapse later. Anyway the same\n1704:\t\t\t * check will be done again later, so the risk seems to be low.\n1705:\t\t\t */\n1706:\t\t\tif (folio_expected_ref_count(folio) != folio_ref_count(folio)) {\n1707:\t\t\t\tresult = SCAN_PAGE_COUNT;\n1708:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1709:\t\t\t\tgoto out_unmap;\n1710:\t\t\t}\n1711:\t\n1712:\t\t\tif (cc-\u003epolicy.require_referenced \u0026\u0026\n1713:\t\t\t    folio_pte_referenced(folio, vma, addr, pteval))\n1714:\t\t\t\treferenced++;\n1715:\t\t}\n1716:\t\tif (cc-\u003epolicy.require_referenced \u0026\u0026\n1717:\t\t    (!referenced ||\n1718:\t\t     (unmapped \u0026\u0026 referenced \u003c HPAGE_PMD_NR / 2))) {\n1719:\t\t\tresult = SCAN_LACK_REFERENCED_PAGE;\n"
}

31/2 2026/09/20 07:12 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 41250
							output: 37
							thoughts: 17
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, as requested, geared toward an expert audience, and written in the first person:

**Diving into `collapse_scan_anon_pmd`**

Alright, let's get into this `collapse_scan_anon_pmd` function. I need to understand its role within the broader data processing pipeline, specifically within the anonymization stage. My immediate thought is, "What kind of scan are we collapsing, and why?" Is this about pre-processing, feature engineering, post-processing... where does it fit? The "anon" implies we're dealing with sensitive data, so I'll need to pay close attention to the preservation of data integrity and privacy. "PMD" is likely some specific naming convention, let's see what that refers to to keep my bearings.

I'll be looking for clues about the underlying data structures being used. Are we working with sparse matrices, dense arrays, or something else entirely? The choice of data structures will heavily influence the efficiency and complexity of this function. I'm also interested in how this collapsing action is implemented. Is it a simple aggregation, a more complex transformation, or is it a mapping onto another data structure? I'm anticipating that memory management might be a key consideration here, given that we are dealing with scans and PMDs.

Ultimately, I need to figure out the computational complexity and performance implications. What are the bottlenecks? Is it I/O-bound, CPU-bound, or memory-bound? I need to know this to be able to suggest optimizations down the line. I'll be particularly vigilant for potential issues related to data loss, data corruption, or inadvertently re-identifying individuals. I'm prepared to dig into the surrounding code to determine these things. Okay, let's see what the rest of this function has to say...



32/2 2026/09/20 07:13 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1720,
  "LineCount": 40
}

Results:
{
  "Contents": "1720:\t\t} else {\n1721:\t\t\tresult = SCAN_SUCCEED;\n1722:\t\t}\n1723:\tout_unmap:\n1724:\t\tpte_unmap_unlock(pte, ptl);\n1725:\t\tif (result == SCAN_SUCCEED) {\n1726:\t\t\tcc-\u003escan_orders = enabled_orders;\n1727:\t\t\tcc-\u003escan_referenced = referenced;\n1728:\t\t\tcc-\u003escan_unmapped = unmapped;\n1729:\t\t}\n1730:\tout:\n1731:\t\ttrace_mm_khugepaged_scan_pmd(mm, failed_pfn, referenced,\n1732:\t\t\t\t\t     none_or_zero, result, unmapped);\n1733:\t\treturn result;\n1734:\t}\n1735:\t\n1736:\tstatic void collect_mm_slot(struct mm_slot *slot)\n1737:\t{\n1738:\t\tstruct mm_struct *mm = slot-\u003emm;\n1739:\t\n1740:\t\tlockdep_assert_held(\u0026khugepaged_mm_lock);\n1741:\t\n1742:\t\tif (collapse_test_exit(mm)) {\n1743:\t\t\t/* free mm_slot */\n1744:\t\t\tmm_slot_remove(slot);\n1745:\t\n1746:\t\t\t/*\n1747:\t\t\t * Not strictly needed because the mm exited already.\n1748:\t\t\t *\n1749:\t\t\t * mm_flags_clear(MMF_VM_HUGEPAGE, mm);\n1750:\t\t\t */\n1751:\t\n1752:\t\t\t/* khugepaged_mm_lock actually not necessary for the below */\n1753:\t\t\tmm_slot_free(mm_slot_cache, slot);\n1754:\t\t\tmmdrop(mm);\n1755:\t\t}\n1756:\t}\n1757:\t\n1758:\t/* folio must be locked, and mmap_lock must be held */\n1759:\tstatic enum scan_result set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,\n"
}

33/2 2026/09/20 07:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 42276
							output: 32
							thoughts: 495
						

Thoughts:
**Analyzing PMD Folio Support in Collapse Operations**

Okay, so I'm digging into this `collapse_scan_anon_pmd` function, and it's hitting me that it doesn't return `SCAN_PTE_MAPPED_HUGEPAGE`, which is a key distinction from `collapse_scan_file`. Interesting. `collapse_scan_file`, on the other hand, *does* return `SCAN_PTE_MAPPED_HUGEPAGE`, and when it does, it sets up some crucial context – like the file, the page offset, enabled orders, and whether it's unmapped for swap. This suggests a very file-centric view for hugepage handling in that function.

Now, I see that `collapse_run_pmd` has introduced a `VM_WARN_ON_ONCE(!file);` check. That's a bit of a signal. It highlights this file-centric assumption. I have to wonder how this interacts with the higher-level collapse operations.

Moving on to `collapse_file`, I'm looking at this crucial change. The old code had a safety check: `VM_WARN_ON_ONCE(!is_shmem && !mapping_pmd_folio_support(mapping));`.  It was skipping the warning if it was shared memory (`is_shmem`). The *new* code has simplified the check to `VM_WARN_ON_ONCE(!mapping_pmd_folio_support(mapping));`. That's a huge shift!

The old code was *explicitly* excluding shared memory from this check. Now, it's included. The question is: why was `is_shmem` there in the first place? *Does* shared memory have `mapping_pmd_folio_support(mapping)`?  I need to investigate further and find out how shmem behaves with respect to `mapping_pmd_folio_support`. Time to dive into the codebase and search for that function to see where it's used and what it means in the context of shared memory. This change looks potentially significant.



34/2 2026/09/20 07:13 tool grepper
0m Args:
{
  "Expression": "mapping_pmd_folio_support",
  "PathPrefix": "include/linux/"
}

Results:
{
  "Output": "include/linux/pagemap.h=506=static inline bool mapping_large_folio_support(const struct address_space *mapping)\n--\ninclude/linux/pagemap.h-515-/**\ninclude/linux/pagemap.h:516: * mapping_pmd_folio_support() - Check if a mapping supports PMD-sized folio\ninclude/linux/pagemap.h-517- * @mapping: The address_space\n--\ninclude/linux/pagemap.h-526-#ifdef CONFIG_TRANSPARENT_HUGEPAGE\ninclude/linux/pagemap.h:527:static inline bool mapping_pmd_folio_support(const struct address_space *mapping)\ninclude/linux/pagemap.h-528-{\n--\ninclude/linux/pagemap.h-535-#else\ninclude/linux/pagemap.h:536:static inline bool mapping_pmd_folio_support(const struct address_space *mapping)\ninclude/linux/pagemap.h-537-{\n"
}

35/2 2026/09/20 07:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 43519
							output: 37
							thoughts: 29
						

Thoughts:
Okay, here's my take on those thoughts, framed as an expert's internal monologue:

**Investigating `mapping_pmd_folio_support`**

Alright, let's dive into this `mapping_pmd_folio_support` macro. Seems like something I should be familiar with, but a quick refresh is always good. I'm going to check the definition in `include/linux/pagemap.h`. This likely deals with how the kernel handles PMDs and folios within the context of a mapping. I bet it has to do with enabling or disabling certain optimizations or features related to folio support at the PMD level. I'm expecting it probably tests whether a particular mapping supports a PMD-based folio implementation, possibly depending on the underlying architecture or file system. Knowing this will be key to understanding the interplay of page-based and folio-based memory management within that specific mapping. Time to see what the header file reveals.



36/2 2026/09/20 07:13 tool read-file
0m Args:
{
  "File": "include/linux/pagemap.h",
  "FirstLine": 515,
  "LineCount": 30
}

Results:
{
  "Contents": " 515:\t/**\n 516:\t * mapping_pmd_folio_support() - Check if a mapping supports PMD-sized folio\n 517:\t * @mapping: The address_space\n 518:\t *\n 519:\t * While some mappings support large folios, they might not support PMD-sized\n 520:\t * folios. This function checks whether a mapping supports PMD-sized folios.\n 521:\t * For example, khugepaged needs this information before attempting to\n 522:\t * collapsing THPs.\n 523:\t *\n 524:\t * Return: True if PMD-sized folios are supported, otherwise false.\n 525:\t */\n 526:\t#ifdef CONFIG_TRANSPARENT_HUGEPAGE\n 527:\tstatic inline bool mapping_pmd_folio_support(const struct address_space *mapping)\n 528:\t{\n 529:\t\t/* AS_FOLIO_ORDER is only reasonable for pagecache folios */\n 530:\t\tVM_WARN_ON_ONCE((unsigned long)mapping \u0026 FOLIO_MAPPING_ANON);\n 531:\t\n 532:\t\treturn mapping_min_folio_order(mapping) \u003c= PMD_ORDER \u0026\u0026\n 533:\t\t       mapping_max_folio_order(mapping) \u003e= PMD_ORDER;\n 534:\t}\n 535:\t#else\n 536:\tstatic inline bool mapping_pmd_folio_support(const struct address_space *mapping)\n 537:\t{\n 538:\t\treturn false;\n 539:\t}\n 540:\t#endif\n 541:\t\n 542:\t/* Return the maximum folio size for this pagecache mapping, in bytes. */\n 543:\tstatic inline size_t mapping_max_folio_size(const struct address_space *mapping)\n 544:\t{\n"
}

37/2 2026/09/20 07:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 44287
							output: 30
							thoughts: 416
						

Thoughts:
**Fuzzing THP Collapse Logic - Jackpot!**

Okay, take a look at this code change in `collapse_file`. The original assertion, `VM_WARN_ON_ONCE(!is_shmem && !mapping_pmd_folio_support(mapping))`, has been simplified to `VM_WARN_ON_ONCE(!mapping_pmd_folio_support(mapping))`, and `start & (HPAGE_PMD_NR - 1)` has been changed to `start & (nr_pages - 1)`. I get it – the original code seemed to be making assumptions about shmem not supporting huge pages, but now it's a broader check, right?

But wait a minute, should that `mapping_pmd_folio_support(mapping)` be true for `shmem`? I have some nagging doubts, and it just *feels* off. My initial thought is that the original assertion was *only* triggered when the mapping wasn't shmem, but now that's changed!

This makes me wonder about file systems supporting mTHP but *not* PMD, or shmem with PMD disabled. What's even more interesting is that it seems like the assertion is still being triggered even with orders *below* PMD_ORDER!

The addition of `VM_WARN_ON_ONCE(!file);` in `collapse_run_pmd` is also worth noting; the logic is clearly evolving. And now, with `mthp_collapse` calling `collapse_file` for lower orders, it all seems like a breeding ground for subtle bugs, doesn't it?

This is practically begging for fuzzing! The collapse logic for transparent huge pages (THP), both managed by khugepaged and with `madvise(MADV_COLLAPSE)` has got to be vulnerable to all kinds of interesting edge cases. This syzkaller is *perfect* for this. Orders and conditions, combined!

Let's see… is this worth fuzzing? Absolutely! *WorthFuzzing: true!*

Now, let's nail down the essential configurations. We *need* `TRANSPARENT_HUGEPAGE`, obviously, because it controls everything related to huge pages and khugepaged. Also, we'll need `SHMEM` for shmem support; there is a lot of interaction, and we need to check every possibility.

I should also check `mm/khugepaged.c` for any other relevant `#ifdef CONFIG_` that might be relevant; there could be other settings or dependencies involved. Gotta be thorough here!



38/2 2026/09/20 07:13 tool grepper
0m Args:
{
  "Expression": "CONFIG_",
  "PathPrefix": "mm/khugepaged.c"
}

Results:
{
  "Output": "mm/khugepaged.c=87=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-90-\nmm/khugepaged.c:91:#ifdef CONFIG_SYSFS\nmm/khugepaged.c-92-static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,\n--\nmm/khugepaged.c=296=struct attribute_group khugepaged_attr_group = {\n--\nmm/khugepaged.c-299-};\nmm/khugepaged.c:300:#endif /* CONFIG_SYSFS */\nmm/khugepaged.c-301-\n--\nmm/khugepaged.c=953=static void collapse_policy_khugepaged(struct collapse_policy *p)\n--\nmm/khugepaged.c-966-\nmm/khugepaged.c:967:#ifdef CONFIG_NUMA\nmm/khugepaged.c-968-static int collapse_find_target_node(struct collapse_control *cc)\n"
}

39/2 2026/09/20 07:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 45585
							output: 32
							thoughts: 70
						

Thoughts:
**My Initial Thoughts on Transparent Huge Pages (THP)**

Okay, so I'm thinking about `TRANSPARENT_HUGEPAGE`, that's the primary focus here. But, hang on a second, what about that `READ_ONCE(huge_shmem_orders_...)` call I saw in `shmem.c`? That's got me curious. Let me just quickly check where `huge_shmem_orders_...` is actually defined within `mm/shmem.c`. Gotta get the complete picture before I move on.



40/2 2026/09/20 07:13 tool grepper
0m Args:
{
  "Expression": "huge_shmem_orders",
  "PathPrefix": "mm/shmem.c"
}

Results:
{
  "Output": "mm/shmem.c=114=struct shmem_options {\n--\nmm/shmem.c-138-#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/shmem.c:139:static unsigned long huge_shmem_orders_always __read_mostly;\nmm/shmem.c:140:static unsigned long huge_shmem_orders_madvise __read_mostly;\nmm/shmem.c:141:static unsigned long huge_shmem_orders_inherit __read_mostly;\nmm/shmem.c:142:static unsigned long huge_shmem_orders_within_size __read_mostly;\nmm/shmem.c-143-static bool shmem_orders_configured __initdata;\n--\nmm/shmem.c=671=static int shmem_parse_huge(const char *str, bool skip_deny_force)\n--\nmm/shmem.c-698-\tif (huge == SHMEM_HUGE_FORCE \u0026\u0026\nmm/shmem.c:699:\t    huge_shmem_orders_inherit != BIT(HPAGE_PMD_ORDER))\nmm/shmem.c-700-\t\treturn -EINVAL;\n--\nmm/shmem.c=2021=bool shmem_hpage_enabled(void)\n--\nmm/shmem.c-2024-\t\treturn false;\nmm/shmem.c:2025:\tif (READ_ONCE(huge_shmem_orders_always))\nmm/shmem.c-2026-\t\treturn true;\nmm/shmem.c:2027:\tif (READ_ONCE(huge_shmem_orders_madvise))\nmm/shmem.c-2028-\t\treturn true;\nmm/shmem.c:2029:\tif (READ_ONCE(huge_shmem_orders_within_size))\nmm/shmem.c-2030-\t\treturn true;\nmm/shmem.c:2031:\tif (READ_ONCE(huge_shmem_orders_inherit) \u0026\u0026\nmm/shmem.c-2032-\t    shmem_huge != SHMEM_HUGE_NEVER)\n--\nmm/shmem.c=2038=unsigned long shmem_allowable_huge_orders(struct inode *inode,\n--\nmm/shmem.c-2041-{\nmm/shmem.c:2042:\tunsigned long mask = READ_ONCE(huge_shmem_orders_always);\nmm/shmem.c:2043:\tunsigned long within_size_orders = READ_ONCE(huge_shmem_orders_within_size);\nmm/shmem.c-2044-\tvm_flags_t vm_flags = vma ? vma-\u003evm_flags : 0;\n--\nmm/shmem.c-2070-\tif (shmem_huge == SHMEM_HUGE_FORCE)\nmm/shmem.c:2071:\t\treturn READ_ONCE(huge_shmem_orders_inherit);\nmm/shmem.c-2072-\n--\nmm/shmem.c-2076-\tif (vm_flags \u0026 VM_HUGEPAGE)\nmm/shmem.c:2077:\t\tmask |= READ_ONCE(huge_shmem_orders_madvise);\nmm/shmem.c-2078-\nmm/shmem.c-2079-\tif (global_orders \u003e 0)\nmm/shmem.c:2080:\t\tmask |= READ_ONCE(huge_shmem_orders_inherit);\nmm/shmem.c-2081-\n--\nmm/shmem.c=2938=unsigned long shmem_get_unmapped_area(struct file *file,\n--\nmm/shmem.c-2998-#ifdef CONFIG_TRANSPARENT_HUGEPAGE\nmm/shmem.c:2999:\t\t\thpage_orders = READ_ONCE(huge_shmem_orders_always);\nmm/shmem.c:3000:\t\t\thpage_orders |= READ_ONCE(huge_shmem_orders_within_size);\nmm/shmem.c:3001:\t\t\thpage_orders |= READ_ONCE(huge_shmem_orders_madvise);\nmm/shmem.c-3002-\t\t\tif (SHMEM_SB(sb)-\u003ehuge != SHMEM_HUGE_NEVER)\nmm/shmem.c:3003:\t\t\t\thpage_orders |= READ_ONCE(huge_shmem_orders_inherit);\nmm/shmem.c-3004-\n--\nmm/shmem.c=5589=void __init shmem_init(void)\n--\nmm/shmem.c-5630-\tif (!shmem_orders_configured)\nmm/shmem.c:5631:\t\thuge_shmem_orders_inherit = BIT(HPAGE_PMD_ORDER);\nmm/shmem.c-5632-#endif\n--\nmm/shmem.c=5695=struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled);\nmm/shmem.c:5696:static DEFINE_SPINLOCK(huge_shmem_orders_lock);\nmm/shmem.c-5697-\n--\nmm/shmem.c=5714=static unsigned long * const huge_mode_orders[] = {\nmm/shmem.c:5715:\t[HUGE_SHMEM_ENABLED_ALWAYS]      = \u0026huge_shmem_orders_always,\nmm/shmem.c:5716:\t[HUGE_SHMEM_ENABLED_INHERIT]     = \u0026huge_shmem_orders_inherit,\nmm/shmem.c:5717:\t[HUGE_SHMEM_ENABLED_WITHIN_SIZE] = \u0026huge_shmem_orders_within_size,\nmm/shmem.c:5718:\t[HUGE_SHMEM_ENABLED_ADVISE]      = \u0026huge_shmem_orders_madvise,\nmm/shmem.c-5719-};\n--\nmm/shmem.c=5751=static bool set_shmem_enabled_mode(int order, enum huge_mode mode)\n--\nmm/shmem.c-5755-\nmm/shmem.c:5756:\tspin_lock(\u0026huge_shmem_orders_lock);\nmm/shmem.c-5757-\tfor (idx = 0; idx \u003c ARRAY_SIZE(huge_mode_orders); idx++) {\n--\nmm/shmem.c-5762-\t}\nmm/shmem.c:5763:\tspin_unlock(\u0026huge_shmem_orders_lock);\nmm/shmem.c-5764-\n--\nmm/shmem.c=5837=static int __init setup_thp_shmem(char *str)\n--\nmm/shmem.c-5848-\nmm/shmem.c:5849:\talways = huge_shmem_orders_always;\nmm/shmem.c:5850:\tinherit = huge_shmem_orders_inherit;\nmm/shmem.c:5851:\tmadvise = huge_shmem_orders_madvise;\nmm/shmem.c:5852:\twithin_size = huge_shmem_orders_within_size;\nmm/shmem.c-5853-\tp = str_dup;\n--\nmm/shmem.c-5923-\nmm/shmem.c:5924:\thuge_shmem_orders_always = always;\nmm/shmem.c:5925:\thuge_shmem_orders_madvise = madvise;\nmm/shmem.c:5926:\thuge_shmem_orders_inherit = inherit;\nmm/shmem.c:5927:\thuge_shmem_orders_within_size = within_size;\nmm/shmem.c-5928-\tshmem_orders_configured = true;\n"
}

41/2 2026/09/20 07:13 llm patch-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 47838
							output: 235
							thoughts: 795
						

Thoughts:
**My Analysis of the khugepaged File/Shmem mTHP Patch**

Okay, let's break this down. First, I need to verify which functions are directly involved in the altered logic for this multi-size Transparent Huge Page (mTHP) implementation within khugepaged for files and shared memory. I've pinpointed the key functions: `collapse_file` – the core of the collapse process, where order parameters, stats, and folio checks are handled – and a bunch of others. Specifically: `collapse_scan_file`, `mthp_collapse`, `collapse_run_pmd`, `collapse_scan_pmd`, `collapse_possible_orders`, `shmem_hpage_enabled`, and `shmem_parse_huge`.

Now, the crucial question is whether these functions are called during *normal* memory operations. If they were, they'd be incredibly broad and less specific to this new functionality. Thankfully, they're *not*! They are only invoked when khugepaged is actively running or when we use `madvise(..., MADV_COLLAPSE)`. That's a huge positive; these functions are high-signal, meaning they are specific to the new mTHP functionality. This narrows the scope significantly, making them excellent candidates for focused fuzzing.

Before I commit to this, I need to make absolutely sure I'm following the required format for `set-results`. Let me quickly double-check: `EnableConfigs` needs an array of strings, without the `CONFIG_` prefix, that's "TRANSPARENT_HUGEPAGE" and "SHMEM". And my `FocusSymbols` list, which I've already curated, must include `collapse_file`, `collapse_scan_file`, `mthp_collapse`, `collapse_run_pmd`, `collapse_scan_pmd`, `collapse_possible_orders`, `shmem_hpage_enabled`, and `shmem_parse_huge`. Yep, got it.

The reasoning? It's all about multi-size THP support for file and shared memory collapse with khugepaged. This includes changes to `collapse_file` to handle different folio orders, the updating of page cache insertion, updates to stat accounting, modifications to `collapse_scan_file`, and `mthp_collapse`. I'm seeing new assertions added, like `VM_WARN_ON_ONCE(!mapping_pmd_folio_support(mapping))` and `VM_WARN_ON_ONCE(!file)`. Also important, this updates shmem hugepage enablement checks. The patch touches reachable core memory management code. This makes the `madvise(MADV_COLLAPSE)` path and khugepaged background scanning ideal targets for fuzzing.

Looks good! Everything's checked, the reasoning is solid, and the focus is clear. Time to call `set-results`.



42/2 2026/09/20 07:13 tool set-results
0m Args:
{
  "EnableConfigs": [
    "TRANSPARENT_HUGEPAGE",
    "SHMEM"
  ],
  "FocusSymbols": [
    "collapse_file",
    "collapse_scan_file",
    "mthp_collapse",
    "collapse_run_pmd",
    "collapse_scan_pmd",
    "collapse_possible_orders",
    "shmem_hpage_enabled",
    "shmem_parse_huge"
  ],
  "Reasoning": "The patch extends khugepaged to support multi-size Transparent Huge Pages (mTHP) for file and shmem mappings. It modifies core MM collapse routines (collapse_file, collapse_scan_file, mthp_collapse, collapse_run_pmd) to handle non-PMD folio orders, adjusts page cache insertion and LRU accounting, and adds runtime assertions (such as VM_WARN_ON_ONCE(!file)). These changes touch core memory management code reachable from userspace via madvise(MADV_COLLAPSE) and background khugepaged scanning.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "TRANSPARENT_HUGEPAGE",
    "SHMEM"
  ],
  "FocusSymbols": [
    "collapse_file",
    "collapse_scan_file",
    "mthp_collapse",
    "collapse_run_pmd",
    "collapse_scan_pmd",
    "collapse_possible_orders",
    "shmem_hpage_enabled",
    "shmem_parse_huge"
  ],
  "Reasoning": "The patch extends khugepaged to support multi-size Transparent Huge Pages (mTHP) for file and shmem mappings. It modifies core MM collapse routines (collapse_file, collapse_scan_file, mthp_collapse, collapse_run_pmd) to handle non-PMD folio orders, adjusts page cache insertion and LRU accounting, and adds runtime assertions (such as VM_WARN_ON_ONCE(!file)). These changes touch core memory management code reachable from userspace via madvise(MADV_COLLAPSE) and background khugepaged scanning.",
  "WorthFuzzing": true
}

43/1 2026/09/20 07:13 action If
1m Args:
{
  "WorthFuzzing": true
}

Results:
null

44/2 2026/09/20 07:13 agent kmsan-evaluator
1m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch series extends khugepaged to support collapsing multi-size Transparent Huge Pages (mTHP) for shmem and file-backed mappings. The changes include generalizing collapse_file() to arbitrary THP orders, scanning file mappings to build eligible PTE bitmaps, adjusting sysfs/boot parsing for shmem huge page policies, and inlining hugepage_madvise() into madvise_vma_behavior().\n\nKMSAN vs KASAN Applicability Analysis:\n1. Uninitialized Memory: No new uninitialized stack or heap variables are introduced. In collapse_scan_file(), all local variables and scan state are explicitly initialized or cleared via collapse_scan_reset() (which calls bitmap_zero() and memset()). Newly allocated collapse folios have unpopulated pages zeroed with clear_highpage() and valid pages copied from uptodate folios.\n2. Userspace Info-leaks: The changes do not introduce or modify copy_to_user(), put_user(), netlink attributes, socket options, or BPF buffers that could leak uninitialized kernel memory to user space.\n3. Bug Profile: Potential bugs in this area are locking issues, folio refcounting discrepancies, page table synchronization races, or out-of-bounds page indexing. These are detected by KASAN, LOCKDEP, and CONFIG_DEBUG_VM/CONFIG_DEBUG_PAGEALLOC, not KMSAN.\n\nTherefore, a dedicated KMSAN fuzzing session is not warranted for this patch series.",
  "NeedsKMSAN": false
}

Instruction:
You are an expert Linux kernel security engineer specializing in kernel memory
error detectors (KASAN and KMSAN). Your job is to review the provided patch series and
determine if the code changes justify spawning a dedicated KMSAN (KernelMemorySanitizer)
fuzzing session in addition to standard KASAN fuzzing.

CRITICAL DISTINCTION BETWEEN KASAN AND KMSAN:
- Standard KASAN kernel builds (upstream-apparmor-kasan.config) already enable
  a comprehensive suite of debugging tools and sanitizers, including KASAN
  (out-of-bounds accesses, use-after-free, double free, invalid free), LOCKDEP
  (locking bugs and deadlocks), UB-sanitizers, and memory corruption checks.
- KMSAN (KernelMemorySanitizer) detects reads of UNINITIALIZED memory (stack, heap,
  or page allocations) and kernel-to-user memory info-leaks.

Rule: THERE IS NO SENSE IN RUNNING A KMSAN SESSION IF A BUG CAN BE CAUGHT BY KASAN,
LOCKDEP, OR OTHER STANDARD BUG DETECTORS.
A dedicated KMSAN fuzzing session incurs significant resource costs. You must ONLY
set NeedsKMSAN=true if the code changes introduce or expose UNINITIALIZED MEMORY risks
that are detected ONLY by KMSAN.

Look holistically at the patch series and surrounding code. Even if no direct
uninitialized field accesses or new buffer allocations are added in the diff itself,
a patch may alter control flow, bounds checking, or data length calculations in ways
that change how the rest of the code operates on existing buffers (e.g. allowing
uninitialized stack/heap memory to be read, copied to user space, or used in control
flow). Do not hesitate to use your code access tools to inspect the surrounding code,
called functions, and callers.

Set NeedsKMSAN=true ONLY IF the patch introduces or modifies:
1. Kernel structures sent to user space (via copy_to_user, put_user, netlink skb
   attributes, ioctl output arguments, socket options, or BPF buffers) where fields
   or structure padding might not be fully initialized/zeroed.
2. Conditional logic or branching that depends on potentially uninitialized variables
   or struct fields.
3. Allocation or initialization of complex data structures where uninitialized fields
   could be read later in reachable code paths.
4. Bounds checks, lengths, or logic in a way that allows surrounding code to access
   uninitialized bytes of existing buffers.

Set NeedsKMSAN=false IF:
- The code changes primarily risk out-of-bounds access, array overflows, NULL pointer
  dereferences, locking deadlocks, or use-after-free bugs (these are already caught
  by KASAN, LOCKDEP, or standard bug detectors).
- All stack/heap structures touched or introduced by the patch are fully zeroed
  or initialized (e.g. using = {0}, memset, kzalloc) before being read or copied.
- The patch does not introduce any risk of uninitialized memory usage or info-leaks.

Use your code access tools to inspect the surrounding code if necessary, then provide
detailed KMSANReasoning contrasting KASAN vs KMSAN applicability for this patch.
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:
Target architecture: amd64

For your convenience, here is the diff of the changes:
commit e0ea9a9e1bc3968fefab125ca103ef9197c81d03
Author: syz-cluster <triage@syzkaller.com>
Date:   Sun Sep 20 07:11:47 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/admin-guide/mm/transhuge.rst b/Documentation/admin-guide/mm/transhuge.rst
index b187d618452f4..0a8265d1cb553 100644
--- a/Documentation/admin-guide/mm/transhuge.rst
+++ b/Documentation/admin-guide/mm/transhuge.rst
@@ -389,8 +389,8 @@ is not defined within a valid ``thp_anon``, its policy will default to
 Similarly to ``transparent_hugepage``, you can control the hugepage
 allocation policy for the internal shmem mount by using the kernel parameter
 ``transparent_hugepage_shmem=<policy>``, where ``<policy>`` is one of the
-seven valid policies for shmem (``always``, ``within_size``, ``advise``,
-``never``, ``deny``, and ``force``).
+four valid policies for shmem (``always``, ``within_size``, ``advise``,
+``never``).
 
 Similarly to ``transparent_hugepage_shmem``, you can control the default
 hugepage allocation policy for the tmpfs mount by using the kernel parameter
diff --git a/include/linux/huge_mm.h b/include/linux/huge_mm.h
index 8ca0fa3be2acb..334c387ad9976 100644
--- a/include/linux/huge_mm.h
+++ b/include/linux/huge_mm.h
@@ -508,8 +508,6 @@ change_huge_pud(struct mmu_gather *tlb, struct vm_area_struct *vma,
 			__split_huge_pud(__vma, __pud, __address);	\
 	}  while (0)
 
-int hugepage_madvise(struct vm_area_struct *vma, vm_flags_t *vm_flags,
-		     int advice);
 void vma_adjust_trans_huge(struct vm_area_struct *vma, unsigned long start,
 			   unsigned long end, struct vm_area_struct *next);
 spinlock_t *__pmd_trans_huge_lock(pmd_t *pmd, struct vm_area_struct *vma);
@@ -707,12 +705,6 @@ static inline bool unmap_huge_pmd_locked(struct vm_area_struct *vma,
 #define split_huge_pud(__vma, __pmd, __address)	\
 	do { } while (0)
 
-static inline int hugepage_madvise(struct vm_area_struct *vma,
-				   vm_flags_t *vm_flags, int advice)
-{
-	return -EINVAL;
-}
-
 static inline void vma_adjust_trans_huge(struct vm_area_struct *vma,
 					 unsigned long start,
 					 unsigned long end,
diff --git a/include/linux/shmem_fs.h b/include/linux/shmem_fs.h
index a7c7a96a7cbf9..9f2036f58bb8f 100644
--- a/include/linux/shmem_fs.h
+++ b/include/linux/shmem_fs.h
@@ -135,7 +135,7 @@ int shmem_unuse(unsigned int type);
 unsigned long shmem_allowable_huge_orders(struct inode *inode,
 				struct vm_area_struct *vma, pgoff_t index,
 				loff_t write_end, bool shmem_huge_force);
-bool shmem_hpage_pmd_enabled(void);
+bool shmem_hpage_enabled(void);
 #else
 static inline unsigned long shmem_allowable_huge_orders(struct inode *inode,
 				struct vm_area_struct *vma, pgoff_t index,
@@ -144,7 +144,7 @@ static inline unsigned long shmem_allowable_huge_orders(struct inode *inode,
 	return 0;
 }
 
-static inline bool shmem_hpage_pmd_enabled(void)
+static inline bool shmem_hpage_enabled(void)
 {
 	return false;
 }
diff --git a/mm/collapse.h b/mm/collapse.h
index e529699652623..d2fff6b5e1ec4 100644
--- a/mm/collapse.h
+++ b/mm/collapse.h
@@ -8,7 +8,8 @@
 #include <linux/types.h>
 
 #define COLLAPSE_MAX_PTES_LIMIT		(HPAGE_PMD_NR - 1)
-#define COLLAPSE_MIN_MTHP_ORDER		2
+#define COLLAPSE_MIN_ANON_MTHP_ORDER		2
+#define COLLAPSE_MIN_FILE_MTHP_ORDER		1
 
 enum scan_result {
 	SCAN_FAIL,
diff --git a/mm/khugepaged.c b/mm/khugepaged.c
index a3a9e4d93b461..4b5e1f8ddf87a 100644
--- a/mm/khugepaged.c
+++ b/mm/khugepaged.c
@@ -84,6 +84,10 @@ static struct khugepaged_scan khugepaged_scan = {
 	.mm_head = LIST_HEAD_INIT(khugepaged_scan.mm_head),
 };
 
+static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
+		struct file *file, pgoff_t start,
+		struct collapse_control *cc, int order);
+
 #ifdef CONFIG_SYSFS
 static ssize_t scan_sleep_millisecs_show(struct kobject *kobj,
 					 struct kobj_attribute *attr,
@@ -302,6 +306,14 @@ static bool pte_none_or_zero(pte_t pte)
 	return pte_present(pte) && is_zero_pfn(pte_pfn(pte));
 }
 
+static unsigned int collapse_min_mthp_order(struct file *file)
+{
+	if (file)
+		return COLLAPSE_MIN_FILE_MTHP_ORDER;
+
+	return COLLAPSE_MIN_ANON_MTHP_ORDER;
+}
+
 /**
  * collapse_max_ptes_none - Calculate maximum allowed empty PTEs or PTEs mapping
  * the shared zeropage for the given collapse operation.
@@ -380,28 +392,6 @@ static unsigned int collapse_max_ptes_swap(struct collapse_control *cc,
 	return cc->policy.max_ptes_swap;
 }
 
-int hugepage_madvise(struct vm_area_struct *vma,
-		     vm_flags_t *vm_flags, int advice)
-{
-	switch (advice) {
-	case MADV_HUGEPAGE:
-		*vm_flags &= ~VM_NOHUGEPAGE;
-		*vm_flags |= VM_HUGEPAGE;
-		break;
-	case MADV_NOHUGEPAGE:
-		*vm_flags &= ~VM_HUGEPAGE;
-		*vm_flags |= VM_NOHUGEPAGE;
-		/*
-		 * Setting VM_NOHUGEPAGE will prevent khugepaged from scanning
-		 * this vma even if we leave the mm registered in khugepaged if
-		 * it got registered before VM_NOHUGEPAGE was set.
-		 */
-		break;
-	}
-
-	return 0;
-}
-
 int __init khugepaged_init(void)
 {
 	mm_slot_cache = KMEM_CACHE(mm_slot, 0);
@@ -457,7 +447,7 @@ static bool hugepage_enabled(void)
 		return true;
 	if (anon_hpage_enabled())
 		return true;
-	if (shmem_hpage_pmd_enabled())
+	if (shmem_hpage_enabled())
 		return true;
 	return false;
 }
@@ -503,9 +493,14 @@ unsigned long collapse_possible_orders(struct vm_area_struct *vma,
 {
 	unsigned long orders;
 
-	/* If khugepaged is scanning an anonymous vma, allow mTHP collapse */
+	/*
+	 * If khugepaged is scanning an anonymous or shmem vma,
+	 * allow mTHP collapse.
+	 */
 	if ((tva_flags == TVA_KHUGEPAGED) && vma_is_anonymous(vma))
 		orders = THP_ORDERS_ALL_ANON;
+	else if ((tva_flags == TVA_KHUGEPAGED) && vma_is_shmem(vma))
+		orders = THP_ORDERS_ALL_FILE_DEFAULT;
 	else
 		orders = BIT(HPAGE_PMD_ORDER);
 
@@ -1466,7 +1461,11 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long addres
 			enum scan_result ret;
 
 			collapse_address = address + offset * PAGE_SIZE;
-			ret = collapse_huge_page(mm, collapse_address, cc, order);
+			if (cc->scan_file)
+				ret = collapse_file(mm, collapse_address, cc->scan_file,
+						cc->scan_pgoff + offset, cc, order);
+			else
+				ret = collapse_huge_page(mm, collapse_address, cc, order);
 
 			switch (ret) {
 			/* Cases where we continue to next collapse candidate */
@@ -1474,6 +1473,13 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long addres
 				collapsed += nr_ptes;
 				fallthrough;
 			case SCAN_PTE_MAPPED_HUGEPAGE:
+				/*
+				 * Return SCAN_PTE_MAPPED_HUGEPAGE to call
+				 * collapse_pte_mapped_thp() if the page cache
+				 * already holds the PMD folio.
+				 */
+				if (order == HPAGE_PMD_ORDER)
+					last_result = ret;
 				goto next_offset;
 			/* Cases where lower orders might still succeed */
 			case SCAN_ALLOC_HUGE_PAGE_FAIL:
@@ -1507,7 +1513,7 @@ static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long addres
 		 * any smaller order enabled. When at the smallest order
 		 * we must always move to the next offset.
 		 */
-		if (order > COLLAPSE_MIN_MTHP_ORDER &&
+		if (order > collapse_min_mthp_order(cc->scan_file) &&
 		    (cc->scan_orders & GENMASK(order - 1, 0))) {
 			order--;
 			continue;
@@ -2160,6 +2166,7 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
  * @file: file that collapse on
  * @start: collapse start address
  * @cc: collapse context and scratchpad
+ * @order: folio order being collapsed to
  *
  * Basic scheme is simple, details are more complex:
  *  - allocate and lock a new huge page;
@@ -2178,29 +2185,29 @@ static void retract_page_tables(struct address_space *mapping, pgoff_t pgoff)
  *    + unlock and free huge page;
  */
 static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
-		struct file *file, pgoff_t start, struct collapse_control *cc)
+		struct file *file, pgoff_t start, struct collapse_control *cc,
+		int order)
 {
+	const unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, order);
 	struct address_space *mapping = file->f_mapping;
+	const unsigned long nr_pages = 1UL << order;
 	struct page *dst;
 	struct folio *folio, *tmp, *new_folio;
 	unsigned long new_pfn = -1;
-	pgoff_t index = 0, end = start + HPAGE_PMD_NR;
+	pgoff_t index = 0, end = start + nr_pages;
 	LIST_HEAD(pagelist);
-	XA_STATE_ORDER(xas, &mapping->i_pages, start, HPAGE_PMD_ORDER);
+	XA_STATE_ORDER(xas, &mapping->i_pages, start, order);
 	enum scan_result result = SCAN_SUCCEED;
 	int nr_none = 0;
 	bool is_shmem = shmem_file(file);
 
 	/*
-	 * MADV_COLLAPSE ignores shmem huge config, so do not check shmem
-	 *
-	 * TODO: once shmem always calls mapping_set_large_folios() on its
-	 * mapping, the shmem check can be removed.
+	 * MADV_COLLAPSE ignores shmem huge config, so do not check shmem.
 	 */
-	VM_WARN_ON_ONCE(!is_shmem && !mapping_pmd_folio_support(mapping));
-	VM_WARN_ON_ONCE(start & (HPAGE_PMD_NR - 1));
+	VM_WARN_ON_ONCE(!mapping_pmd_folio_support(mapping));
+	VM_WARN_ON_ONCE(start & (nr_pages - 1));
 
-	result = alloc_charge_folio(&new_folio, mm, cc, HPAGE_PMD_ORDER);
+	result = alloc_charge_folio(&new_folio, mm, cc, order);
 	if (result != SCAN_SUCCEED)
 		goto out;
 	new_pfn = folio_pfn(new_folio);
@@ -2247,13 +2254,33 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 						goto xa_locked;
 					}
 				}
-				nr_none++;
+
+				if (++nr_none > max_ptes_none) {
+					result = SCAN_EXCEED_NONE_PTE;
+					count_collapse_event(order, THP_SCAN_EXCEED_NONE_PTE,
+							MTHP_STAT_COLLAPSE_EXCEED_NONE);
+					goto xa_locked;
+				}
+
 				index++;
 				continue;
 			}
 
 			if (xa_is_value(folio) || !folio_test_uptodate(folio)) {
 				xas_unlock_irq(&xas);
+
+				/*
+				 * TODO: Support swapin without leading to further mTHP
+				 * collapses. Currently bringing in new pages via swapin may
+				 * cause a future higher order collapse on a rescan of the same
+				 * range.
+				 */
+				if (!is_pmd_order(order)) {
+					count_mthp_stat(order, MTHP_STAT_COLLAPSE_EXCEED_SWAP);
+					result = SCAN_EXCEED_SWAP_PTE;
+					goto xa_unlocked;
+				}
+
 				/* swap in or instantiate fallocated page */
 				if (shmem_get_folio(mapping->host, index, 0,
 						&folio, SGP_NOALLOC)) {
@@ -2337,6 +2364,15 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 			goto out_unlock;
 		}
 
+		/*
+		 * If the folio order is greater than the collapse order, there is
+		 * no need to continue attempting to collapse.
+		 */
+		if (folio_order(folio) >= order) {
+			result = SCAN_PTE_MAPPED_HUGEPAGE;
+			goto out_unlock;
+		}
+
 		if (folio_mapping(folio) != mapping) {
 			result = SCAN_TRUNCATED;
 			goto out_unlock;
@@ -2532,12 +2568,13 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	}
 
 	if (is_shmem) {
-		lruvec_stat_mod_folio(new_folio, NR_SHMEM, HPAGE_PMD_NR);
-		lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);
-	} else {
+		lruvec_stat_mod_folio(new_folio, NR_SHMEM, nr_pages);
+		if (is_pmd_order(order))
+			lruvec_stat_mod_folio(new_folio, NR_SHMEM_THPS, HPAGE_PMD_NR);
+	} else if (is_pmd_order(order)) {
 		lruvec_stat_mod_folio(new_folio, NR_FILE_THPS, HPAGE_PMD_NR);
 	}
-	lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, HPAGE_PMD_NR);
+	lruvec_stat_mod_folio(new_folio, NR_FILE_PAGES, nr_pages);
 
 	/*
 	 * Mark new_folio as uptodate before inserting it into the
@@ -2545,23 +2582,24 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	 * unwritten page.
 	 */
 	folio_mark_uptodate(new_folio);
-	folio_ref_add(new_folio, HPAGE_PMD_NR - 1);
+	folio_ref_add(new_folio, nr_pages - 1);
 
 	if (is_shmem)
 		folio_mark_dirty(new_folio);
 	folio_add_lru(new_folio);
 
 	/* Join all the small entries into a single multi-index entry. */
-	xas_set_order(&xas, start, HPAGE_PMD_ORDER);
+	xas_set_order(&xas, start, order);
 	xas_store(&xas, new_folio);
 	WARN_ON_ONCE(xas_error(&xas));
 	xas_unlock_irq(&xas);
 
 	/*
-	 * Remove pte page tables, so we can re-fault the page as huge.  A
-	 * caller that wants the PMD mapped now is told to go and do that.
+	 * Remove pte page tables for PMD-sized THP collapse, so we can
+	 * re-fault the page as huge.
 	 */
-	retract_page_tables(mapping, start);
+	if (is_pmd_order(order))
+		retract_page_tables(mapping, start);
 	if (cc->policy.install_pmd)
 		result = SCAN_PTE_MAPPED_HUGEPAGE;
 	folio_unlock(new_folio);
@@ -2607,27 +2645,38 @@ static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,
 	folio_put(new_folio);
 out:
 	VM_BUG_ON(!list_empty(&pagelist));
-	trace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, HPAGE_PMD_NR, result);
+	trace_mm_khugepaged_collapse_file(mm, new_pfn, index, addr, is_shmem, file, nr_pages, result);
 	return result;
 }
 
-static enum scan_result collapse_scan_file(struct mm_struct *mm,
-		unsigned long addr, struct file *file, pgoff_t start,
-		struct collapse_control *cc)
+static enum scan_result collapse_scan_file(struct vm_area_struct *vma,
+		unsigned long addr, struct collapse_control *cc,
+		unsigned long enabled_orders)
 {
-	const unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, HPAGE_PMD_ORDER);
 	const unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);
+	unsigned int max_ptes_none = collapse_max_ptes_none(cc, NULL, HPAGE_PMD_ORDER);
+	struct file *file = vma->vm_file;
 	struct folio *folio = NULL;
 	struct address_space *mapping = file->f_mapping;
+	pgoff_t start = linear_page_index(vma, addr);
 	XA_STATE(xas, &mapping->i_pages, start);
 	int present, swap;
 	int node = NUMA_NO_NODE;
 	enum scan_result result = SCAN_SUCCEED;
 	unsigned long failed_pfn = -1;
+	unsigned long nr_pages;
+	pgoff_t pgoff;
 
 	present = 0;
 	swap = 0;
 	collapse_scan_reset(cc);
+	/*
+	 * If PMD is the only enabled order, enforce max_ptes_none, otherwise
+	 * scan all pages to populate the bitmap for mTHP collapse.
+	 */
+	if (enabled_orders != BIT(HPAGE_PMD_ORDER))
+		max_ptes_none = COLLAPSE_MAX_PTES_LIMIT;
+
 	rcu_read_lock();
 	xas_for_each(&xas, folio, start + HPAGE_PMD_NR - 1) {
 		if (xas_retry(&xas, folio))
@@ -2695,7 +2744,17 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,
 		 * is just too costly...
 		 */
 
-		present += folio_nr_pages(folio);
+		nr_pages = folio_nr_pages(folio);
+		present += nr_pages;
+
+		/*
+		 * If there are folios present, keep track of it in the bitmap
+		 * for file/shmem mTHP collapse.
+		 */
+		pgoff = max_t(pgoff_t, start, folio->index) - start;
+		nr_pages = min_t(int, HPAGE_PMD_NR - pgoff, nr_pages);
+		bitmap_set(cc->eligible_ptes, pgoff, nr_pages);
+
 		folio_put(folio);
 
 		if (need_resched()) {
@@ -2711,10 +2770,27 @@ static enum scan_result collapse_scan_file(struct mm_struct *mm,
 
 	if (result == SCAN_SUCCEED && present < HPAGE_PMD_NR - max_ptes_none) {
 		result = SCAN_EXCEED_NONE_PTE;
-		count_vm_event(THP_SCAN_EXCEED_NONE_PTE);
+		count_collapse_event(HPAGE_PMD_ORDER, THP_SCAN_EXCEED_NONE_PTE,
+				MTHP_STAT_COLLAPSE_EXCEED_NONE);
+	}
+
+	/*
+	 * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds
+	 * the PMD folio, and retracting the PTE table is the run's job.
+	 */
+	if (result == SCAN_SUCCEED || result == SCAN_PTE_MAPPED_HUGEPAGE) {
+		/*
+		 * A file collapse works on the page cache and never sees a
+		 * VMA, so take what it needs from this one while it is still
+		 * here.
+		 */
+		cc->scan_file = get_file(file);
+		cc->scan_pgoff = start;
+		cc->scan_orders = enabled_orders;
+		cc->scan_unmapped = swap;
 	}
 
-	trace_mm_khugepaged_scan_file(mm, failed_pfn, file, present, swap,
+	trace_mm_khugepaged_scan_file(vma->vm_mm, failed_pfn, file, present, swap,
 				      result);
 	return result;
 }
@@ -2762,9 +2838,6 @@ enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,
 		unsigned long addr, struct collapse_control *cc,
 		unsigned long orders)
 {
-	enum scan_result result;
-	pgoff_t pgoff;
-
 	mmap_assert_locked(vma->vm_mm);
 	/* Whatever the last scan found has to have been run by now */
 	collapse_put_scan_file(cc);
@@ -2772,22 +2845,7 @@ enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,
 	if (vma_is_anonymous(vma))
 		return collapse_scan_anon_pmd(vma, addr, cc, orders);
 
-	pgoff = linear_page_index(vma, addr);
-	result = collapse_scan_file(vma->vm_mm, addr, vma->vm_file, pgoff, cc);
-	/*
-	 * SCAN_PTE_MAPPED_HUGEPAGE is work too: the page cache already holds
-	 * the PMD folio, and retracting the PTE table is the run's job.
-	 */
-	if (result != SCAN_SUCCEED && result != SCAN_PTE_MAPPED_HUGEPAGE)
-		return result;
-
-	/*
-	 * A file collapse works on the page cache and never sees a VMA, so take
-	 * what it needs from this one while it is still here.
-	 */
-	cc->scan_file = get_file(vma->vm_file);
-	cc->scan_pgoff = pgoff;
-	return result;
+	return collapse_scan_file(vma, addr, cc, orders);
 }
 
 /*
@@ -2805,23 +2863,21 @@ enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,
 {
 	struct file *file = cc->scan_file;
 	bool triggered_wb = false;
-	pgoff_t pgoff;
-
-	if (!file)
-		return mthp_collapse(mm, addr, cc);
-
-	cc->scan_file = NULL;
-	pgoff = cc->scan_pgoff;
 
 	/* The scan found the PMD folio in place: nothing to collapse */
 	if (result == SCAN_PTE_MAPPED_HUGEPAGE)
 		goto retract;
+
 retry:
-	result = collapse_file(mm, addr, file, pgoff, cc);
+	result = mthp_collapse(mm, addr, cc);
+	/* Just return the results for anonymous folio collapse. */
+	if (!file)
+		return result;
 
 	/* Dirty pages are worth a writeback and one more try, if asked for */
 	if (cc->policy.writeback_dirty && result == SCAN_PAGE_DIRTY_OR_WRITEBACK &&
 	    !triggered_wb && mapping_can_writeback(file->f_mapping)) {
+		pgoff_t pgoff = cc->scan_pgoff;
 		const loff_t lstart = (loff_t)pgoff << PAGE_SHIFT;
 		const loff_t lend = lstart + HPAGE_PMD_SIZE - 1;
 
@@ -2830,6 +2886,8 @@ enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,
 		goto retry;
 	}
 retract:
+	cc->scan_file = NULL;
+	VM_WARN_ON_ONCE(!file);
 	fput(file);
 
 	/*
diff --git a/mm/madvise.c b/mm/madvise.c
index eb491fa88325d..4150f6a8cf64c 100644
--- a/mm/madvise.c
+++ b/mm/madvise.c
@@ -1598,10 +1598,12 @@ static int madvise_vma_behavior(struct madvise_behavior *madv_behavior)
 			goto out;
 		break;
 	case MADV_HUGEPAGE:
+		new_flags &= ~VM_NOHUGEPAGE;
+		new_flags |= VM_HUGEPAGE;
+		break;
 	case MADV_NOHUGEPAGE:
-		error = hugepage_madvise(vma, &new_flags, behavior);
-		if (error)
-			goto out;
+		new_flags &= ~VM_HUGEPAGE;
+		new_flags |= VM_NOHUGEPAGE;
 		break;
 	case __MADV_SET_ANON_VMA_NAME:
 		/* Only anonymous mappings can be named */
diff --git a/mm/shmem.c b/mm/shmem.c
index b572c60f2af85..6567bd4cdc07b 100644
--- a/mm/shmem.c
+++ b/mm/shmem.c
@@ -668,7 +668,7 @@ static unsigned int shmem_huge_global_enabled(struct inode *inode, pgoff_t index
 	}
 }
 
-static int shmem_parse_huge(const char *str)
+static int shmem_parse_huge(const char *str, bool skip_deny_force)
 {
 	int huge;
 
@@ -683,9 +683,9 @@ static int shmem_parse_huge(const char *str)
 		huge = SHMEM_HUGE_WITHIN_SIZE;
 	else if (!strcmp(str, "advise"))
 		huge = SHMEM_HUGE_ADVISE;
-	else if (!strcmp(str, "deny"))
+	else if (!strcmp(str, "deny") && !skip_deny_force)
 		huge = SHMEM_HUGE_DENY;
-	else if (!strcmp(str, "force"))
+	else if (!strcmp(str, "force") && !skip_deny_force)
 		huge = SHMEM_HUGE_FORCE;
 	else
 		return -EINVAL;
@@ -2018,17 +2018,17 @@ static struct folio *shmem_swapin_cluster(swp_entry_t swap, gfp_t gfp,
 }
 
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
-bool shmem_hpage_pmd_enabled(void)
+bool shmem_hpage_enabled(void)
 {
 	if (shmem_huge == SHMEM_HUGE_DENY)
 		return false;
-	if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_always))
+	if (READ_ONCE(huge_shmem_orders_always))
 		return true;
-	if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_madvise))
+	if (READ_ONCE(huge_shmem_orders_madvise))
 		return true;
-	if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_within_size))
+	if (READ_ONCE(huge_shmem_orders_within_size))
 		return true;
-	if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_inherit) &&
+	if (READ_ONCE(huge_shmem_orders_inherit) &&
 	    shmem_huge != SHMEM_HUGE_NEVER)
 		return true;
 
@@ -5680,7 +5680,7 @@ static ssize_t shmem_enabled_store(struct kobject *kobj,
 	if (count && tmp[count - 1] == '\n')
 		tmp[count - 1] = '\0';
 
-	huge = shmem_parse_huge(tmp);
+	huge = shmem_parse_huge(tmp, /*skip_deny_force=*/false);
 	if (huge == -EINVAL)
 		return huge;
 
@@ -5807,7 +5807,7 @@ static int __init setup_transparent_hugepage_shmem(char *str)
 {
 	int huge;
 
-	huge = shmem_parse_huge(str);
+	huge = shmem_parse_huge(str, /*skip_deny_force=*/true);
 	if (huge == -EINVAL) {
 		pr_warn("transparent_hugepage_shmem= cannot parse, ignored\n");
 		return huge;
@@ -5822,7 +5822,7 @@ static int __init setup_transparent_hugepage_tmpfs(char *str)
 {
 	int huge;
 
-	huge = shmem_parse_huge(str);
+	huge = shmem_parse_huge(str, /*skip_deny_force=*/true);
 	if (huge < 0) {
 		pr_warn("transparent_hugepage_tmpfs= cannot parse, ignored\n");
 		return huge;
diff --git a/tools/testing/selftests/mm/khugepaged.c b/tools/testing/selftests/mm/khugepaged.c
index f82673f5f6b47..a205b7afbc855 100644
--- a/tools/testing/selftests/mm/khugepaged.c
+++ b/tools/testing/selftests/mm/khugepaged.c
@@ -627,6 +627,9 @@ static void mthp_khugepaged_collapse(const char *msg, char *p, int nr_hpages,
 	if (ops == &__anon_ops) {
 		settings.thp_enabled = THP_NEVER;
 		settings.hugepages[collapse_order].enabled = THP_MADVISE;
+	} else if (ops == &__shmem_ops) {
+		settings.shmem_enabled = SHMEM_NEVER;
+		settings.shmem_hugepages[collapse_order].enabled = SHMEM_ADVISE;
 	}
 
 	thp_push_settings(&settings);
@@ -1260,8 +1263,6 @@ static void parse_test_type(int argc, char **argv)
 			usage();
 	} else if (!strcmp(buf, "shmem")) {
 		shmem_ops = &__shmem_ops;
-		if (mthp_khugepaged_context)
-			usage();
 	} else {
 		usage();
 	}
@@ -1358,6 +1359,7 @@ int main(int argc, char **argv)
 	TEST(collapse_full, khugepaged_context, read_write_file_write_ops);
 	TEST(collapse_full, khugepaged_context, shmem_ops);
 	TEST(collapse_full, mthp_khugepaged_context, anon_ops);
+	TEST(collapse_full, mthp_khugepaged_context, shmem_ops);
 	TEST(collapse_full, madvise_context, anon_ops);
 	TEST(collapse_full, madvise_context, read_only_file_ops);
 	TEST(collapse_full, madvise_context, read_write_file_read_ops);
@@ -1369,6 +1371,7 @@ int main(int argc, char **argv)
 	TEST(collapse_empty, madvise_context, anon_ops);
 
 	TEST(collapse_single_mthp, mthp_khugepaged_context, anon_ops);
+	TEST(collapse_single_mthp, mthp_khugepaged_context, shmem_ops);
 
 	TEST(collapse_single_pte_entry, khugepaged_context, anon_ops);
 	TEST(collapse_single_pte_entry, khugepaged_context, read_only_file_ops);
diff --git a/tools/testing/selftests/mm/run_vmtests.sh b/tools/testing/selftests/mm/run_vmtests.sh
index 19755fb4edb94..e1e404a612ccf 100755
--- a/tools/testing/selftests/mm/run_vmtests.sh
+++ b/tools/testing/selftests/mm/run_vmtests.sh
@@ -427,6 +427,8 @@ CATEGORY="thp" run_test ./khugepaged -s 4 all:shmem
 
 CATEGORY="thp" run_test ./khugepaged -c 4 mthp_khugepaged:anon
 
+CATEGORY="thp" run_test ./khugepaged -c 4 mthp_khugepaged:shmem
+
 # Try to create XFS if not provided
 if [ -z "${SPLIT_HUGE_PAGE_TEST_XFS_PATH}" ]; then
     if test_selected "thp"; then

45/3 2026/09/20 07:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 11363
							output: 33
							thoughts: 1488
						

Thoughts:
**KMSAN Evaluation: Patch Series Analysis**

Alright, let's get down to brass tacks. I need to figure out if this patch series warrants a dedicated KMSAN fuzzing session. I'm going to follow the rules rigorously; KMSAN is only worth the effort if this code might leak uninitialized memory to user space, or if its control flow depends on uninitialized data. If KASAN, LOCKDEP, or other standard detectors can catch a bug, then we don't need KMSAN.

First, I've got to break down what's being touched here. It seems like a lot of the changes are related to transparent hugepages (THP), especially within shared memory (shmem) and file-backed mappings. There's a lot of refactoring and inlining, with function calls moved and some logic rearranged, so I will have to be very careful to look for any hidden uninitialized memory. There are also a couple of updates to documentation and selftests, which are unlikely to trigger KMSAN issues, but I'll still give those a quick glance.

The core changes are in the hugepage and collapse mechanisms, specifically the `khugepaged.c` file. This is where I'll focus my attention. I see changes in `collapse_file`, `collapse_scan_file`, and `mthp_collapse`, which sound like prime suspects for potential issues. The fact that the `collapse_file` function is now taking an `order` parameter instead of hardcoding `HPAGE_PMD_ORDER` is a small red flag. Also, I need to check how the code deals with folio allocation and management within `collapse_file`, especially the call to `alloc_charge_folio`. Does this function initialize everything it's supposed to?

I'm particularly interested in how pages are handled in `collapse_file`, because it seems like the function is moving a lot of data. Are there any spots where memory is read or copied before being fully initialized? I will need to verify that folio allocation and page copying happen in a way that avoids memory leaks.

To check these, I'm going to dive deeper. I'll need to use `grepper` or `read-file` to carefully examine the `alloc_charge_folio` function and the page copying logic within `collapse_file`. I'm especially interested in whether any uninitialized memory could be exposed to user space through any of the changes.

Based on this first pass, it doesn't immediately scream KMSAN. I don't see any obvious direct interaction with user space or any immediate signs of uninitialized memory being used in a risky way, but I have to be completely sure. I need to confirm with the deeper dive that `alloc_charge_folio` initializes correctly and that there are no unsafe memory reads within `collapse_file`. This is the make-or-break point for recommending a KMSAN session.



46/3 2026/09/20 07:13 tool grepper
0m Args:
{
  "Expression": "alloc_charge_folio",
  "PathPrefix": "mm/khugepaged.c"
}

Results:
{
  "Output": "mm/khugepaged.c=1093=static enum scan_result __collapse_huge_page_swapin(struct mm_struct *mm,\n--\nmm/khugepaged.c-1183-\nmm/khugepaged.c:1184:static enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,\nmm/khugepaged.c-1185-\t\tstruct collapse_control *cc, unsigned int order)\n--\nmm/khugepaged.c=1220=static enum scan_result collapse_huge_page(struct mm_struct *mm,\n--\nmm/khugepaged.c-1236-\nmm/khugepaged.c:1237:\tresult = alloc_charge_folio(\u0026folio, mm, cc, order);\nmm/khugepaged.c-1238-\tif (result != SCAN_SUCCEED)\n--\nmm/khugepaged.c=2187=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2209-\nmm/khugepaged.c:2210:\tresult = alloc_charge_folio(\u0026new_folio, mm, cc, order);\nmm/khugepaged.c-2211-\tif (result != SCAN_SUCCEED)\n"
}

47/3 2026/09/20 07:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 13856
							output: 37
							thoughts: 22
						

Thoughts:
Here's my summary, as though I'm thinking through this code:

**Diving into khugepaged: `alloc_charge_folio`**

Alright, time to dig into the internals of `khugepaged`. I want to understand how it's handling the memory allocation and charging process, so let's start with `alloc_charge_folio` in `mm/khugepaged.c`. My immediate thought is, this function *has* to be crucial for determining how and when khugepaged actually requests new physical pages to back the transparent hugepages it's managing. I'm expecting this to be the point where the actual memory "commitment" happens – the crucial step between deciding a hugepage *should* exist and getting the kernel to make that a reality. I'll need to pay close attention to the arguments here, because the information in the call probably dictates, at a very granular level, the type of folio requested and any associated constraints that it places on the memory management system. I'm looking for clues about NUMA affinity, how the allocation might interact with page reclaim, and of course, how it interfaces with the `memcg` if that's even a factor. Let's see how much memory actually gets consumed when this function is called, and how it handles the interaction between normal and huge page allocations.



48/3 2026/09/20 07:13 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1180,
  "LineCount": 40
}

Results:
{
  "Contents": "1180:\t\t\t\t\t\t   order);\n1181:\t\treturn result;\n1182:\t}\n1183:\t\n1184:\tstatic enum scan_result alloc_charge_folio(struct folio **foliop, struct mm_struct *mm,\n1185:\t\t\tstruct collapse_control *cc, unsigned int order)\n1186:\t{\n1187:\t\tgfp_t gfp = cc-\u003epolicy.gfp;\n1188:\t\tint node = collapse_find_target_node(cc);\n1189:\t\tstruct folio *folio;\n1190:\t\n1191:\t\tfolio = __folio_alloc(gfp, order, node, \u0026cc-\u003ealloc_nmask);\n1192:\t\tif (!folio) {\n1193:\t\t\t*foliop = NULL;\n1194:\t\t\tcount_collapse_event(order, THP_COLLAPSE_ALLOC_FAILED,\n1195:\t\t\t\t\t     MTHP_STAT_COLLAPSE_ALLOC_FAILED);\n1196:\t\t\treturn SCAN_ALLOC_HUGE_PAGE_FAIL;\n1197:\t\t}\n1198:\t\n1199:\t\tcount_collapse_event(order, THP_COLLAPSE_ALLOC, MTHP_STAT_COLLAPSE_ALLOC);\n1200:\t\n1201:\t\tif (unlikely(mem_cgroup_charge(folio, mm, gfp))) {\n1202:\t\t\tfolio_put(folio);\n1203:\t\t\t*foliop = NULL;\n1204:\t\t\treturn SCAN_CGROUP_CHARGE_FAIL;\n1205:\t\t}\n1206:\t\n1207:\t\tif (is_pmd_order(order))\n1208:\t\t\tcount_memcg_folio_events(folio, THP_COLLAPSE_ALLOC, 1);\n1209:\t\n1210:\t\t*foliop = folio;\n1211:\t\treturn SCAN_SUCCEED;\n1212:\t}\n1213:\t\n1214:\t/*\n1215:\t * collapse_huge_page() expects the mmap_lock to be unlocked before entering and\n1216:\t * will always return with the lock unlocked, to avoid holding the mmap_lock\n1217:\t * while allocating a THP, as that could trigger direct reclaim/compaction.\n1218:\t * Note that the VMA must be rechecked after grabbing the mmap_lock again.\n1219:\t */\n"
}

49/3 2026/09/20 07:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 14843
							output: 37
							thoughts: 59
						

Thoughts:
**Analyzing the Page Copying Logic**

Okay, so I need to understand exactly how the `collapse_file` function handles the transfer of pages from an existing structure into a `new_folio`, especially considering potentially uninitialized pages or 'holes' in the original data. To get the most precise view, I'm going to dive into the core implementation. I should look specifically at the `mm/khugepaged.c` file, from line 2360 to 2550. That should cover the crucial logic for this aspect of the process.



50/3 2026/09/20 07:13 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 2360,
  "LineCount": 80
}

Results:
{
  "Contents": "2360:\t\t\t * This will be discovered on the first iteration.\n2361:\t\t\t */\n2362:\t\t\tif (is_pmd_order(folio_order(folio))) {\n2363:\t\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n2364:\t\t\t\tgoto out_unlock;\n2365:\t\t\t}\n2366:\t\n2367:\t\t\t/*\n2368:\t\t\t * If the folio order is greater than the collapse order, there is\n2369:\t\t\t * no need to continue attempting to collapse.\n2370:\t\t\t */\n2371:\t\t\tif (folio_order(folio) \u003e= order) {\n2372:\t\t\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n2373:\t\t\t\tgoto out_unlock;\n2374:\t\t\t}\n2375:\t\n2376:\t\t\tif (folio_mapping(folio) != mapping) {\n2377:\t\t\t\tresult = SCAN_TRUNCATED;\n2378:\t\t\t\tgoto out_unlock;\n2379:\t\t\t}\n2380:\t\n2381:\t\t\tif (!is_shmem \u0026\u0026 (folio_test_dirty(folio) ||\n2382:\t\t\t\t\t  folio_test_writeback(folio))) {\n2383:\t\t\t\t/*\n2384:\t\t\t\t * khugepaged only works on clean file-backed folios,\n2385:\t\t\t\t * so this folio is dirty because it hasn't been flushed\n2386:\t\t\t\t * since first write.\n2387:\t\t\t\t */\n2388:\t\t\t\tresult = SCAN_PAGE_DIRTY_OR_WRITEBACK;\n2389:\t\t\t\tgoto out_unlock;\n2390:\t\t\t}\n2391:\t\n2392:\t\t\tif (!folio_isolate_lru(folio)) {\n2393:\t\t\t\tresult = SCAN_DEL_PAGE_LRU;\n2394:\t\t\t\tgoto out_unlock;\n2395:\t\t\t}\n2396:\t\n2397:\t\t\tif (!filemap_release_folio(folio, GFP_KERNEL)) {\n2398:\t\t\t\tresult = SCAN_PAGE_HAS_PRIVATE;\n2399:\t\t\t\tfolio_putback_lru(folio);\n2400:\t\t\t\tgoto out_unlock;\n2401:\t\t\t}\n2402:\t\n2403:\t\t\tif (folio_mapped(folio))\n2404:\t\t\t\ttry_to_unmap(folio,\n2405:\t\t\t\t\t\tTTU_IGNORE_MLOCK | TTU_BATCH_FLUSH);\n2406:\t\n2407:\t\t\txas_lock_irq(\u0026xas);\n2408:\t\n2409:\t\t\tVM_BUG_ON_FOLIO(folio != xa_load(xas.xa, index), folio);\n2410:\t\n2411:\t\t\t/*\n2412:\t\t\t * We control 2 + nr_pages references to the folio:\n2413:\t\t\t *  - we hold a pin on it;\n2414:\t\t\t *  - nr_pages reference from page cache;\n2415:\t\t\t *  - one from lru_isolate_folio;\n2416:\t\t\t * If those are the only references, then any new usage\n2417:\t\t\t * of the folio will have to fetch it from the page\n2418:\t\t\t * cache. That requires locking the folio to handle\n2419:\t\t\t * truncate, so any new usage will be blocked until we\n2420:\t\t\t * unlock folio after collapse/during rollback.\n2421:\t\t\t */\n2422:\t\t\tif (folio_ref_count(folio) != 2 + folio_nr_pages(folio)) {\n2423:\t\t\t\tresult = SCAN_PAGE_COUNT;\n2424:\t\t\t\txas_unlock_irq(\u0026xas);\n2425:\t\t\t\tfolio_putback_lru(folio);\n2426:\t\t\t\tgoto out_unlock;\n2427:\t\t\t}\n2428:\t\n2429:\t\t\t/*\n2430:\t\t\t * At this point, the folio is locked and unmapped. If the PTE\n2431:\t\t\t * was dirty, try_to_unmap() has transferred the dirty bit to\n2432:\t\t\t * the folio and we must not collapse it into a clean\n2433:\t\t\t * file-backed folio.\n2434:\t\t\t *\n2435:\t\t\t * If the folio is clean here, no one can write it until we\n2436:\t\t\t * drop the folio lock. A write through a stale TLB entry came\n2437:\t\t\t * from a clean PTE and must fault because the PTE has been\n2438:\t\t\t * cleared; the fault path has to take the folio lock before\n2439:\t\t\t * installing a writable mapping. Buffered write paths also\n"
}

51/3 2026/09/20 07:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 16260
							output: 37
							thoughts: 25
						

Thoughts:
Okay, let's dive into this. I need to get a handle on the `collapse_file` function, specifically from lines 2440 to 2540. It's a fairly specific section, so I'm guessing there's something critical happening here that warrants close attention. I'll need to absorb the surrounding context, of course, but my immediate goal is to understand the logic flow and identify any potential bottlenecks or edge cases within that particular segment of code. I'll be looking for anything unusual or unexpected that jumps out at me, especially if it relates to data structures, memory management, or performance. I'm treating this like a focused audit; I'm expecting something specific to be happening in that section. Time to get my reading glasses on and start dissecting.



52/3 2026/09/20 07:13 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 2440,
  "LineCount": 80
}

Results:
{
  "Contents": "2440:\t\t\t * have to take the folio lock before modifying file contents\n2441:\t\t\t * without a mapping, typically via write_begin_get_folio().\n2442:\t\t\t */\n2443:\t\t\tif (!is_shmem \u0026\u0026 folio_test_dirty(folio)) {\n2444:\t\t\t\tresult = SCAN_PAGE_DIRTY_OR_WRITEBACK;\n2445:\t\t\t\txas_unlock_irq(\u0026xas);\n2446:\t\t\t\tfolio_putback_lru(folio);\n2447:\t\t\t\tgoto out_unlock;\n2448:\t\t\t}\n2449:\t\n2450:\t\t\t/*\n2451:\t\t\t * Accumulate the folios that are being collapsed.\n2452:\t\t\t */\n2453:\t\t\tlist_add_tail(\u0026folio-\u003elru, \u0026pagelist);\n2454:\t\t\tindex += folio_nr_pages(folio);\n2455:\t\t\tcontinue;\n2456:\tout_unlock:\n2457:\t\t\tfolio_unlock(folio);\n2458:\t\t\tfolio_put(folio);\n2459:\t\t\tgoto xa_unlocked;\n2460:\t\t}\n2461:\t\n2462:\txa_locked:\n2463:\t\txas_unlock_irq(\u0026xas);\n2464:\txa_unlocked:\n2465:\t\n2466:\t\t/*\n2467:\t\t * If collapse is successful, flush must be done now before copying.\n2468:\t\t * If collapse is unsuccessful, does flush actually need to be done?\n2469:\t\t * Do it anyway, to clear the state.\n2470:\t\t */\n2471:\t\ttry_to_unmap_flush();\n2472:\t\n2473:\t\tif (result == SCAN_SUCCEED \u0026\u0026 nr_none \u0026\u0026\n2474:\t\t    !shmem_charge(mapping-\u003ehost, nr_none))\n2475:\t\t\tresult = SCAN_FAIL;\n2476:\t\tif (result != SCAN_SUCCEED) {\n2477:\t\t\tnr_none = 0;\n2478:\t\t\tgoto rollback;\n2479:\t\t}\n2480:\t\n2481:\t\t/*\n2482:\t\t * The old folios are locked, so they won't change anymore.\n2483:\t\t */\n2484:\t\tindex = start;\n2485:\t\tdst = folio_page(new_folio, 0);\n2486:\t\tlist_for_each_entry(folio, \u0026pagelist, lru) {\n2487:\t\t\tint i, nr_pages = folio_nr_pages(folio);\n2488:\t\n2489:\t\t\twhile (index \u003c folio-\u003eindex) {\n2490:\t\t\t\tclear_highpage(dst);\n2491:\t\t\t\tindex++;\n2492:\t\t\t\tdst++;\n2493:\t\t\t}\n2494:\t\n2495:\t\t\tfor (i = 0; i \u003c nr_pages; i++) {\n2496:\t\t\t\tif (copy_mc_highpage(dst, folio_page(folio, i)) \u003e 0) {\n2497:\t\t\t\t\tresult = SCAN_COPY_MC;\n2498:\t\t\t\t\tgoto rollback;\n2499:\t\t\t\t}\n2500:\t\t\t\tindex++;\n2501:\t\t\t\tdst++;\n2502:\t\t\t}\n2503:\t\t}\n2504:\t\twhile (index \u003c end) {\n2505:\t\t\tclear_highpage(dst);\n2506:\t\t\tindex++;\n2507:\t\t\tdst++;\n2508:\t\t}\n2509:\t\n2510:\t\tif (nr_none) {\n2511:\t\t\tstruct vm_area_struct *vma;\n2512:\t\t\tint nr_none_check = 0;\n2513:\t\n2514:\t\t\ti_mmap_lock_read(mapping);\n2515:\t\t\txas_lock_irq(\u0026xas);\n2516:\t\n2517:\t\t\txas_set(\u0026xas, start);\n2518:\t\t\tfor (index = start; index \u003c end; index++) {\n2519:\t\t\t\tif (!xas_next(\u0026xas)) {\n"
}

53/3 2026/09/20 07:13 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 17575
							output: 36
							thoughts: 1180
						

Thoughts:
**Analyzing Multi-Size THP Collapse for Shared Memory and File Mappings**

Okay, let's break this down. First, I'm looking at this block of code, lines 2484-2508. What I'm seeing is a process where the code iterates through a list of folios (`pagelist`). It zeroes out any gaps between the current index (`index`) and the starting point (`start`), using `clear_highpage(dst)`. Then, it copies pages from the existing folios into the newly created `new_folio`, using `copy_mc_highpage(dst, folio_page(folio, i))`. Every page within the specified range (from `start` to `end`) in the `new_folio` is either populated from an existing folio or cleared, ensuring a consistent state.

Now, zooming out, I need to grasp the overall functionality. This patch appears to introduce support for multi-size THP (mTHP) khugepaged collapse, specifically targeting shared memory (shmem) and file mappings. Previously, `khugepaged` only handled mTHP collapse for anonymous memory.

Here's the gist of the changes:

1.  `collapse_possible_orders()` now determines the allowable order sizes based on the VMA type. Anonymous memory gets `THP_ORDERS_ALL_ANON`, shared memory or files get `THP_ORDERS_ALL_FILE_DEFAULT`, and everything else is the standard huge page order (`HPAGE_PMD_ORDER`).
2.  `collapse_scan_file()` is now responsible for scanning file mappings, tracking present folios, and setting up relevant collapse control (`cc`) fields, such as `scan_file`, `scan_pgoff`, and `scan_orders`.
3.  `collapse_run_pmd()` then calls `mthp_collapse`, which is at the heart of the collapse operation.
4.  Within `mthp_collapse()`, the execution path branches based on whether it is scanning a file (`cc->scan_file`) or dealing with anonymous memory. `collapse_file()` handles file pages, collapsing file pages into a folio of a specific order. `collapse_huge_page()` handles anonymous memory.
5.  A cleanup phase removes `hugepage_madvise()` and integrates its logic into `madvise_vma_behavior()`.
6.  `shmem_parse_huge()` has been adjusted to handle the "deny" and "force" boot parameters more gracefully.

Now, let's dig into the details. I see that `collapse_scan_file` is critical. It appears that `cc` is initialized if `collapse_scan_file` returns either `SCAN_SUCCEED` or `SCAN_PTE_MAPPED_HUGEPAGE`. I see it then `get_file()` and sets up the file-specific scan data. Also, let's notice that `collapse_scan_pmd` handles things for both anonymous and file mappings, by calling `collapse_scan_anon_pmd` or `collapse_scan_file`, respectively. I need to compare `collapse_scan_anon_pmd` and `collapse_scan_file` to understand how `cc` is initialized. I need to trace this in more detail.



54/3 2026/09/20 07:14 tool grepper
0m Args:
{
  "Expression": "collapse_scan_anon_pmd",
  "PathPrefix": "mm/khugepaged.c"
}

Results:
{
  "Output": "mm/khugepaged.c=1431=static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long address,\n--\nmm/khugepaged.c-1541-\nmm/khugepaged.c:1542:static enum scan_result collapse_scan_anon_pmd(struct vm_area_struct *vma,\nmm/khugepaged.c-1543-\t\tunsigned long start_addr, struct collapse_control *cc,\n--\nmm/khugepaged.c=2837=enum scan_result collapse_scan_pmd(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-2845-\tif (vma_is_anonymous(vma))\nmm/khugepaged.c:2846:\t\treturn collapse_scan_anon_pmd(vma, addr, cc, orders);\nmm/khugepaged.c-2847-\n"
}

55/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 19756
							output: 37
							thoughts: 22
						

Thoughts:
Here's a first-person summary, tailored for an expert audience, as requested:

**Diving into `collapse_scan_anon_pmd`**

Okay, time to dig into the guts of this code. Let's zero in on `collapse_scan_anon_pmd` – seems like a good starting point, and based on context, it's likely responsible for some key data structure manipulation or optimization. Let's jump to around line 1542, specifically. I'm expecting to see the core logic for either consolidating, reformatting, or otherwise optimizing some anonymous PMD structures. Given the name, I'm leaning towards the former, or perhaps some scan-and-collapse operation to reduce overhead in a particular memory management scenario. I'm looking for the actual algorithm implementation here; things like loop structures, conditional statements to check for certain scenarios, and of course, pointer arithmetic if it's C or C++. It is likely that the function is doing a significant amount of memory manipulation based on the name. I'm hoping to quickly grasp the underlying assumptions and intended use case by carefully studying this function. Let's see if this hunch is correct, or if it involves a more complex scenario.



56/3 2026/09/20 07:14 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1542,
  "LineCount": 45
}

Results:
{
  "Contents": "1542:\tstatic enum scan_result collapse_scan_anon_pmd(struct vm_area_struct *vma,\n1543:\t\t\tunsigned long start_addr, struct collapse_control *cc,\n1544:\t\t\tunsigned long enabled_orders)\n1545:\t{\n1546:\t\tconst unsigned int max_ptes_shared = collapse_max_ptes_shared(cc, HPAGE_PMD_ORDER);\n1547:\t\tconst unsigned int max_ptes_swap = collapse_max_ptes_swap(cc, HPAGE_PMD_ORDER);\n1548:\t\tunsigned int max_ptes_none = collapse_max_ptes_none(cc, vma, HPAGE_PMD_ORDER);\n1549:\t\tstruct mm_struct *mm = vma-\u003evm_mm;\n1550:\t\tpmd_t *pmd;\n1551:\t\tpte_t *pte, *_pte, pteval;\n1552:\t\tint i;\n1553:\t\tint none_or_zero = 0, shared = 0, referenced = 0;\n1554:\t\tenum scan_result result = SCAN_FAIL;\n1555:\t\tstruct page *page = NULL;\n1556:\t\tstruct folio *folio = NULL;\n1557:\t\tunsigned long failed_pfn = -1;\n1558:\t\tunsigned long addr;\n1559:\t\tspinlock_t *ptl;\n1560:\t\tint node = NUMA_NO_NODE, unmapped = 0;\n1561:\t\n1562:\t\tVM_BUG_ON(start_addr \u0026 ~HPAGE_PMD_MASK);\n1563:\t\n1564:\t\tresult = find_pmd_or_thp_or_none(mm, start_addr, \u0026pmd);\n1565:\t\tif (result != SCAN_SUCCEED) {\n1566:\t\t\tcc-\u003eprogress++;\n1567:\t\t\tgoto out;\n1568:\t\t}\n1569:\t\n1570:\t\tcollapse_scan_reset(cc);\n1571:\t\n1572:\t\t/*\n1573:\t\t * If PMD is the only enabled order, enforce max_ptes_none, otherwise\n1574:\t\t * scan all pages to populate the bitmap for mTHP collapse. The bitmap\n1575:\t\t * is then checked again in mthp_collapse() for each attempted order.\n1576:\t\t */\n1577:\t\tif (enabled_orders != BIT(HPAGE_PMD_ORDER))\n1578:\t\t\tmax_ptes_none = COLLAPSE_MAX_PTES_LIMIT;\n1579:\t\n1580:\t\tpte = pte_offset_map_lock(mm, pmd, start_addr, \u0026ptl);\n1581:\t\tif (!pte) {\n1582:\t\t\tcc-\u003eprogress++;\n1583:\t\t\tresult = SCAN_NO_PTE_TABLE;\n1584:\t\t\tgoto out;\n1585:\t\t}\n1586:\t\n"
}

57/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 20861
							output: 37
							thoughts: 17
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, as if it were my own, assuming I'm an expert in the field:

**Analyzing the `collapse_scan_anon_pmd` Function's Termination**

Alright, I need to understand how this `collapse_scan_anon_pmd` function wraps up. I'm focusing on the end state. I'm guessing there's a specific pattern or condition that triggers its exit. Is it a successful completion? An error? A timeout? I need to look closely at the control flow around the function's final instructions. I'll need to figure out what data structures are modified as it winds down. Are resources freed? Are any return codes set that are important for the calling function to know about? Is there a subtle edge case in the termination logic that might lead to a resource leak or a hang? I'm anticipating potential concurrency issues if this is used in a multithreaded environment, too, so I'll keep that in mind. Essentially, I'm peeling back the layers to get a clean view of what's *supposed* to happen when this function wraps up and what could go wrong. The exit strategy defines the stability of the entire feature!



58/3 2026/09/20 07:14 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1680,
  "LineCount": 40
}

Results:
{
  "Contents": "1680:\t\t\t */\n1681:\t\t\tnode = folio_nid(folio);\n1682:\t\t\tif (collapse_scan_abort(node, cc)) {\n1683:\t\t\t\tresult = SCAN_SCAN_ABORT;\n1684:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1685:\t\t\t\tgoto out_unmap;\n1686:\t\t\t}\n1687:\t\t\tcc-\u003enode_load[node]++;\n1688:\t\t\tif (!folio_test_lru(folio)) {\n1689:\t\t\t\tresult = SCAN_PAGE_LRU;\n1690:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1691:\t\t\t\tgoto out_unmap;\n1692:\t\t\t}\n1693:\t\t\tif (folio_test_locked(folio)) {\n1694:\t\t\t\tresult = SCAN_PAGE_LOCK;\n1695:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1696:\t\t\t\tgoto out_unmap;\n1697:\t\t\t}\n1698:\t\n1699:\t\t\t/*\n1700:\t\t\t * Check if the page has any GUP (or other external) pins.\n1701:\t\t\t *\n1702:\t\t\t * Here the check is racy, but such cases are ephemeral and\n1703:\t\t\t * we can always retry collapse later. Anyway the same\n1704:\t\t\t * check will be done again later, so the risk seems to be low.\n1705:\t\t\t */\n1706:\t\t\tif (folio_expected_ref_count(folio) != folio_ref_count(folio)) {\n1707:\t\t\t\tresult = SCAN_PAGE_COUNT;\n1708:\t\t\t\tfailed_pfn = folio_pfn(folio);\n1709:\t\t\t\tgoto out_unmap;\n1710:\t\t\t}\n1711:\t\n1712:\t\t\tif (cc-\u003epolicy.require_referenced \u0026\u0026\n1713:\t\t\t    folio_pte_referenced(folio, vma, addr, pteval))\n1714:\t\t\t\treferenced++;\n1715:\t\t}\n1716:\t\tif (cc-\u003epolicy.require_referenced \u0026\u0026\n1717:\t\t    (!referenced ||\n1718:\t\t     (unmapped \u0026\u0026 referenced \u003c HPAGE_PMD_NR / 2))) {\n1719:\t\t\tresult = SCAN_LACK_REFERENCED_PAGE;\n"
}

59/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 21791
							output: 37
							thoughts: 16
						

Thoughts:
Okay, here's my attempt at summarizing the thought process, as requested, imagining myself as an expert reviewing the lines:

**Analyzing Code Snippets: Lines 1720-1760**

Alright, let's zoom in on lines 1720 to 1760. My initial thought is to quickly scan them for context. What function or method are we in? What's the general purpose of this section of code? I need to get a high-level understanding of what's happening *before* I dive into the nitty-gritty. Are we dealing with data manipulation, control flow, error handling, or something else entirely? A quick skim for variable names and key function calls will usually provide enough direction. Based on that, I can form my initial hypothesis, what I *expect* to find within these lines, then I need to test that hypothesis.

Now, let's look for any potential red flags. Are there any obvious inefficiencies? Are any sections overly complex, begging for refactoring? Any potential concurrency issues that jump out at me? Given my years of experience, a lot of that evaluation happens almost subconsciously. It's like having a mental checklist that runs automatically.

I'll be paying close attention to any input validation or error handling. That's always a critical area. Are there sufficient checks in place to prevent common vulnerabilities like buffer overflows or injection attacks? Or, is it just robust enough to handle unexpected cases gracefully without crashing?

Finally, what's the level of documentation? Are comments clear and concise, or are they sparse and unhelpful? Well-documented code is essential for maintainability. The less I have to mentally reverse engineer, the quicker I can provide an accurate assessment. After reviewing those lines, I'll need to know: if the code meets industry standards and the expectations I have set for it.



60/3 2026/09/20 07:14 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1720,
  "LineCount": 40
}

Results:
{
  "Contents": "1720:\t\t} else {\n1721:\t\t\tresult = SCAN_SUCCEED;\n1722:\t\t}\n1723:\tout_unmap:\n1724:\t\tpte_unmap_unlock(pte, ptl);\n1725:\t\tif (result == SCAN_SUCCEED) {\n1726:\t\t\tcc-\u003escan_orders = enabled_orders;\n1727:\t\t\tcc-\u003escan_referenced = referenced;\n1728:\t\t\tcc-\u003escan_unmapped = unmapped;\n1729:\t\t}\n1730:\tout:\n1731:\t\ttrace_mm_khugepaged_scan_pmd(mm, failed_pfn, referenced,\n1732:\t\t\t\t\t     none_or_zero, result, unmapped);\n1733:\t\treturn result;\n1734:\t}\n1735:\t\n1736:\tstatic void collect_mm_slot(struct mm_slot *slot)\n1737:\t{\n1738:\t\tstruct mm_struct *mm = slot-\u003emm;\n1739:\t\n1740:\t\tlockdep_assert_held(\u0026khugepaged_mm_lock);\n1741:\t\n1742:\t\tif (collapse_test_exit(mm)) {\n1743:\t\t\t/* free mm_slot */\n1744:\t\t\tmm_slot_remove(slot);\n1745:\t\n1746:\t\t\t/*\n1747:\t\t\t * Not strictly needed because the mm exited already.\n1748:\t\t\t *\n1749:\t\t\t * mm_flags_clear(MMF_VM_HUGEPAGE, mm);\n1750:\t\t\t */\n1751:\t\n1752:\t\t\t/* khugepaged_mm_lock actually not necessary for the below */\n1753:\t\t\tmm_slot_free(mm_slot_cache, slot);\n1754:\t\t\tmmdrop(mm);\n1755:\t\t}\n1756:\t}\n1757:\t\n1758:\t/* folio must be locked, and mmap_lock must be held */\n1759:\tstatic enum scan_result set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,\n"
}

61/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 22816
							output: 37
							thoughts: 11
						

Thoughts:
Okay, let's dive into this `mthp_collapse` thing. As a seasoned professional, I'm already anticipating the typical scenarios.

**Analyzing mthp_collapse:**

My initial thought is to quickly assess its purpose. What exactly is it designed to collapse? Is this related to data structures, maybe a simplification algorithm, or perhaps some kind of graphical element? My intuition tells me that the name likely hints at some form of reduction or aggregation. I will want to understand the inputs and the nature of the collapse. Does it handle different data types? Are there specific conditions that trigger the collapse?

Next, I need to understand the mechanism. Is this collapsing process deterministic? What's the computational complexity? And, does it preserve critical information, or is there data loss involved? Is this a lossy compression method or is it used to simplify data for analysis? My mind is already sketching out potential edge cases and looking for potential areas of optimization. I'm also curious about error handling. What happens if the input is malformed, or if the collapse results in an unexpected state?

The context will be key. Where is this function/algorithm used? Is it part of a larger system? What are the dependencies? Knowing the environment will help me to understand any design trade-offs and potential limitations. I need to understand its relationship to other elements in the system, to gain full comprehension of how `mthp_collapse` is used in a broader context.

Finally, I'll need to confirm these assumptions and questions with the information available about this tool. I want to compare this to existing and familiar paradigms. Ultimately, I'm expecting this to be elegant, efficient, and well-documented. Only then can I determine its true value and the applications where it might excel.



62/3 2026/09/20 07:14 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 1430,
  "LineCount": 90
}

Results:
{
  "Contents": "1430:\t */\n1431:\tstatic enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long address,\n1432:\t\t\tstruct collapse_control *cc)\n1433:\t{\n1434:\t\tunsigned int nr_eligible_ptes, nr_ptes, max_ptes_none;\n1435:\t\tenum scan_result last_result = SCAN_FAIL;\n1436:\t\tint collapsed = 0;\n1437:\t\tbool alloc_failed = false;\n1438:\t\tunsigned long collapse_address;\n1439:\t\tunsigned int offset = 0;\n1440:\t\tunsigned int order = HPAGE_PMD_ORDER;\n1441:\t\n1442:\t\twhile (offset \u003c HPAGE_PMD_NR) {\n1443:\t\t\tnr_ptes = 1UL \u003c\u003c order;\n1444:\t\n1445:\t\t\tif (!test_bit(order, \u0026cc-\u003escan_orders))\n1446:\t\t\t\tgoto next_order;\n1447:\t\n1448:\t\t\tmax_ptes_none = collapse_max_ptes_none(cc, NULL, order);\n1449:\t\t\tnr_eligible_ptes = bitmap_weight_from(cc-\u003eeligible_ptes, offset,\n1450:\t\t\t\t\t\t\t      offset + nr_ptes);\n1451:\t\n1452:\t\t\t/*\n1453:\t\t\t * Swap PTEs accepted during the scan are counted in\n1454:\t\t\t * cc-\u003escan_unmapped, not in cc-\u003eeligible_ptes. Account them for\n1455:\t\t\t * the PMD-order candidate.\n1456:\t\t\t */\n1457:\t\t\tif (is_pmd_order(order))\n1458:\t\t\t\tnr_eligible_ptes += cc-\u003escan_unmapped;\n1459:\t\n1460:\t\t\tif (nr_eligible_ptes \u003e= nr_ptes - max_ptes_none) {\n1461:\t\t\t\tenum scan_result ret;\n1462:\t\n1463:\t\t\t\tcollapse_address = address + offset * PAGE_SIZE;\n1464:\t\t\t\tif (cc-\u003escan_file)\n1465:\t\t\t\t\tret = collapse_file(mm, collapse_address, cc-\u003escan_file,\n1466:\t\t\t\t\t\t\tcc-\u003escan_pgoff + offset, cc, order);\n1467:\t\t\t\telse\n1468:\t\t\t\t\tret = collapse_huge_page(mm, collapse_address, cc, order);\n1469:\t\n1470:\t\t\t\tswitch (ret) {\n1471:\t\t\t\t/* Cases where we continue to next collapse candidate */\n1472:\t\t\t\tcase SCAN_SUCCEED:\n1473:\t\t\t\t\tcollapsed += nr_ptes;\n1474:\t\t\t\t\tfallthrough;\n1475:\t\t\t\tcase SCAN_PTE_MAPPED_HUGEPAGE:\n1476:\t\t\t\t\t/*\n1477:\t\t\t\t\t * Return SCAN_PTE_MAPPED_HUGEPAGE to call\n1478:\t\t\t\t\t * collapse_pte_mapped_thp() if the page cache\n1479:\t\t\t\t\t * already holds the PMD folio.\n1480:\t\t\t\t\t */\n1481:\t\t\t\t\tif (order == HPAGE_PMD_ORDER)\n1482:\t\t\t\t\t\tlast_result = ret;\n1483:\t\t\t\t\tgoto next_offset;\n1484:\t\t\t\t/* Cases where lower orders might still succeed */\n1485:\t\t\t\tcase SCAN_ALLOC_HUGE_PAGE_FAIL:\n1486:\t\t\t\t\talloc_failed = true;\n1487:\t\t\t\t\tfallthrough;\n1488:\t\t\t\tcase SCAN_LACK_REFERENCED_PAGE:\n1489:\t\t\t\tcase SCAN_EXCEED_NONE_PTE:\n1490:\t\t\t\tcase SCAN_EXCEED_SWAP_PTE:\n1491:\t\t\t\tcase SCAN_EXCEED_SHARED_PTE:\n1492:\t\t\t\tcase SCAN_PAGE_LOCK:\n1493:\t\t\t\tcase SCAN_PAGE_COUNT:\n1494:\t\t\t\tcase SCAN_PAGE_NULL:\n1495:\t\t\t\tcase SCAN_DEL_PAGE_LRU:\n1496:\t\t\t\tcase SCAN_PTE_NON_PRESENT:\n1497:\t\t\t\tcase SCAN_PTE_UFFD:\n1498:\t\t\t\tcase SCAN_PAGE_LAZYFREE:\n1499:\t\t\t\t\tlast_result = ret;\n1500:\t\t\t\t\tgoto next_order;\n1501:\t\t\t\t/* Cases where no further collapse is possible */\n1502:\t\t\t\tcase SCAN_PMD_MAPPED:\n1503:\t\t\t\t\tfallthrough;\n1504:\t\t\t\tdefault:\n1505:\t\t\t\t\tlast_result = ret;\n1506:\t\t\t\t\tgoto done;\n1507:\t\t\t\t}\n1508:\t\t\t}\n1509:\t\n1510:\tnext_order:\n1511:\t\t\t/*\n1512:\t\t\t * Continue with the next smaller order if there is still\n1513:\t\t\t * any smaller order enabled. When at the smallest order\n1514:\t\t\t * we must always move to the next offset.\n1515:\t\t\t */\n1516:\t\t\tif (order \u003e collapse_min_mthp_order(cc-\u003escan_file) \u0026\u0026\n1517:\t\t\t    (cc-\u003escan_orders \u0026 GENMASK(order - 1, 0))) {\n1518:\t\t\t\torder--;\n1519:\t\t\t\tcontinue;\n"
}

63/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 24610
							output: 27
							thoughts: 61
						

Thoughts:
Okay, let's break this down.

**Investigating a `bitmap_set` Call in `collapse_scan_file`**

Alright, so I'm digging into this `collapse_scan_file` function. I see a `bitmap_set` call, specifically setting bits in `cc->eligible_ptes`. My first thought is always *Where* is this bitmap allocated and crucially, when is it reset? Understanding the allocation and resetting is critical to avoid any logical errors when dealing with a bitmap in this type of process. To understand the function call, I need to understand its context. I need to understand what `cc->eligible_ptes` represents. Therefore, I need to know where it's initialized and if it's reused. This bitmap seems key, representing the pages that are 'eligible' for some operation; my next step is to trace the initialization and lifecycle of this bitmap. I'll need to confirm that `collapse_scan_reset` properly cleans it up to ensure no stale data remains before its next use. Let's start there.



64/3 2026/09/20 07:14 tool grepper
0m Args:
{
  "Expression": "collapse_scan_reset",
  "PathPrefix": "mm/"
}

Results:
{
  "Output": "mm/khugepaged.c=518=void __khugepaged_exit(struct mm_struct *mm)\n--\nmm/khugepaged.c-547-\nmm/khugepaged.c:548:static void collapse_scan_reset(struct collapse_control *cc)\nmm/khugepaged.c-549-{\n--\nmm/khugepaged.c=1542=static enum scan_result collapse_scan_anon_pmd(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-1569-\nmm/khugepaged.c:1570:\tcollapse_scan_reset(cc);\nmm/khugepaged.c-1571-\n--\nmm/khugepaged.c=2652=static enum scan_result collapse_scan_file(struct vm_area_struct *vma,\n--\nmm/khugepaged.c-2671-\tswap = 0;\nmm/khugepaged.c:2672:\tcollapse_scan_reset(cc);\nmm/khugepaged.c-2673-\t/*\n"
}

65/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25224
							output: 36
							thoughts: 11
						

Thoughts:
Okay, here's my interpretation of that thought process, tailored for an expert audience, and presented as if it were my own internal monologue:

**Diving into `collapse_scan_reset`**

Right, let's take a look at the `collapse_scan_reset` routine. I need to understand how it's behaving under the hood. Specifically, I need to see how it's interacting with the larger system during a scan and how it handles potential reset conditions. I'm probably looking for the nuances that differentiate it from other scan and reset functions in the codebase. What are the key performance considerations, and are there any potential race conditions I should immediately consider? What kind of data structures or locks are in play here? I need to understand the reset logic within the scan context. I'm thinking about the implications for consistency and data integrity, particularly if a scan is interrupted or encounters an error. Time to get down in the code and see exactly what's going on.



66/3 2026/09/20 07:14 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 547,
  "LineCount": 20
}

Results:
{
  "Contents": " 547:\t\n 548:\tstatic void collapse_scan_reset(struct collapse_control *cc)\n 549:\t{\n 550:\t\tmemset(cc-\u003enode_load, 0, sizeof(cc-\u003enode_load));\n 551:\t\tnodes_clear(cc-\u003ealloc_nmask);\n 552:\t\tbitmap_zero(cc-\u003eeligible_ptes, MAX_PTRS_PER_PTE);\n 553:\t}\n 554:\t\n 555:\tstatic void release_pte_folio(struct folio *folio)\n 556:\t{\n 557:\t\tnode_stat_mod_folio(folio,\n 558:\t\t\t\tNR_ISOLATED_ANON + folio_is_file_lru(folio),\n 559:\t\t\t\t-folio_nr_pages(folio));\n 560:\t\tfolio_unlock(folio);\n 561:\t\tfolio_putback_lru(folio);\n 562:\t}\n 563:\t\n 564:\tstatic void release_pte_pages(pte_t *pte, pte_t *_pte,\n 565:\t\t\tstruct list_head *compound_pagelist)\n 566:\t{\n"
}

67/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 25800
							output: 30
							thoughts: 1057
						

Thoughts:
**Analyzing the mTHP Collapse Path**

Okay, let's break this down. First, `collapse_scan_reset` initializes `eligible_ptes` to zero. That's our starting point.  Then, we move into `collapse_run_pmd`.  I need to trace the logic here, step by step.

I see that `collapse_run_pmd` is given a `result` value initially, but it can be changed. If the initial `result` shows a huge page already mapped, it jumps to `retract`.  Otherwise, it goes to `retry`.

At `retry`, the core action is calling `mthp_collapse`. The `file` pointer is crucial: If the file is not NULL it can cause a new execution and a goto. The key seems to be that `cc->scan_file` is set to `file` before the `mthp_collapse` call. Importantly, `mthp_collapse` *doesn't* modify `cc->scan_file` directly. It passes `cc->scan_file` to `collapse_file`. After `mthp_collapse`, regardless of the return value, the `scan_file` is set to `NULL` to prepare for the end of the execution.

A dirty page triggers a writeback and potentially another `retry`. That's important for ensuring data consistency. The final logic checks the `result` from the `mthp_collapse` call. If it's a success, or if a huge page was mapped, `collapse_pte_mapped_thp` is invoked.  This is where the magic (or the trouble) happens.

So, the critical path is the `mthp_collapse` function itself, especially if `collapsed` is non-zero. Let's see how `mthp_collapse` returns `SCAN_SUCCEED`.

Inside `mthp_collapse`, it iterates through offsets. It calls `collapse_file` repeatedly. If `collapse_file` returns either `SCAN_SUCCEED` or `SCAN_PTE_MAPPED_HUGEPAGE`, and a collapse happens (`collapsed > 0`), the outer `mthp_collapse` returns `SCAN_SUCCEED`. If no collapse occurred and no huge page was mapped, the function returns the `last_result`.

Therefore, the crucial factor here is the outcome of `collapse_file` and whether the number of collapsed entries is greater than zero. The return value influences whether we proceed to `collapse_pte_mapped_thp`. I'm going to have to dive into `collapse_file` and `collapse_pte_mapped_thp` next to understand the full implications. But the basic execution logic should be clear now.



68/3 2026/09/20 07:14 tool grepper
0m Args:
{
  "Expression": "collapse_pte_mapped_thp",
  "PathPrefix": "mm/"
}

Results:
{
  "Output": "mm/khugepaged.c=1431=static enum scan_result mthp_collapse(struct mm_struct *mm, unsigned long address,\n--\nmm/khugepaged.c-1477-\t\t\t\t * Return SCAN_PTE_MAPPED_HUGEPAGE to call\nmm/khugepaged.c:1478:\t\t\t\t * collapse_pte_mapped_thp() if the page cache\nmm/khugepaged.c-1479-\t\t\t\t * already holds the PMD folio.\n--\nmm/khugepaged.c=1759=static enum scan_result set_huge_pmd(struct vm_area_struct *vma, unsigned long addr,\n--\nmm/khugepaged.c-1794-\nmm/khugepaged.c:1795:static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,\nmm/khugepaged.c-1796-\t\tbool install_pmd)\n--\nmm/khugepaged.c-2021-/**\nmm/khugepaged.c:2022: * collapse_pte_mapped_thp - Try to collapse a pte-mapped THP for mm at\nmm/khugepaged.c-2023- * address haddr.\n--\nmm/khugepaged.c-2032- */\nmm/khugepaged.c:2033:void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,\nmm/khugepaged.c-2034-\t\tbool install_pmd)\nmm/khugepaged.c-2035-{\nmm/khugepaged.c:2036:\ttry_collapse_pte_mapped_thp(mm, addr, install_pmd);\nmm/khugepaged.c-2037-}\n--\nmm/khugepaged.c=2861=enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2901-\t\telse\nmm/khugepaged.c:2902:\t\t\tresult = try_collapse_pte_mapped_thp(mm, addr,\nmm/khugepaged.c-2903-\t\t\t\t\t\t\tcc-\u003epolicy.install_pmd);\n"
}

69/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28073
							output: 37
							thoughts: 79
						

Thoughts:
Here's my summary, as though I'm thinking through this process:

**Diving into `try_collapse_pte_mapped_thp`**

Okay, so `try_collapse_pte_mapped_thp` is *only* called when we're dealing with a PMD that's already mapped and potentially collapsible into a PMD THP. That's a key first point. Now, to understand the context of how this function gets used, I need to see how `collapse_run_pmd` interacts with it. Let's get the specific call in `mm/khugepaged.c` -- that'll be lines 2890-2910. The goal is to see exactly *when* the function is being called and get the bigger picture of the code it interfaces with.



70/3 2026/09/20 07:14 tool read-file
0m Args:
{
  "File": "mm/khugepaged.c",
  "FirstLine": 2880,
  "LineCount": 35
}

Results:
{
  "Contents": "2880:\t\t\tpgoff_t pgoff = cc-\u003escan_pgoff;\n2881:\t\t\tconst loff_t lstart = (loff_t)pgoff \u003c\u003c PAGE_SHIFT;\n2882:\t\t\tconst loff_t lend = lstart + HPAGE_PMD_SIZE - 1;\n2883:\t\n2884:\t\t\tfilemap_write_and_wait_range(file-\u003ef_mapping, lstart, lend);\n2885:\t\t\ttriggered_wb = true;\n2886:\t\t\tgoto retry;\n2887:\t\t}\n2888:\tretract:\n2889:\t\tcc-\u003escan_file = NULL;\n2890:\t\tVM_WARN_ON_ONCE(!file);\n2891:\t\tfput(file);\n2892:\t\n2893:\t\t/*\n2894:\t\t * A PMD folio is in the page cache, whether the collapse just put it\n2895:\t\t * there or found it: retract the PTE table, and map the PMD if asked.\n2896:\t\t */\n2897:\t\tif (result == SCAN_PTE_MAPPED_HUGEPAGE) {\n2898:\t\t\tmmap_read_lock(mm);\n2899:\t\t\tif (collapse_test_exit_or_disable(mm))\n2900:\t\t\t\tresult = SCAN_ANY_PROCESS;\n2901:\t\t\telse\n2902:\t\t\t\tresult = try_collapse_pte_mapped_thp(mm, addr,\n2903:\t\t\t\t\t\t\t\tcc-\u003epolicy.install_pmd);\n2904:\t\t\tif (result == SCAN_PMD_MAPPED)\n2905:\t\t\t\tresult = SCAN_SUCCEED;\n2906:\t\t\tmmap_read_unlock(mm);\n2907:\t\t}\n2908:\t\treturn result;\n2909:\t}\n2910:\t\n2911:\tstatic void collapse_scan_mm_slot(unsigned int progress_max,\n2912:\t\t\tenum scan_result *result, struct collapse_control *cc)\n2913:\t\t__releases(\u0026khugepaged_mm_lock)\n2914:\t\t__acquires(\u0026khugepaged_mm_lock)\n"
}

71/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 28946
							output: 26
							thoughts: 197
						

Thoughts:
**Analyzing THP Collapse in `collapse_file`**

Okay, let's dive into this `collapse_file` function. I see the core logic related to removing page tables for PMD-sized THP collapse, which makes sense. We're setting the stage to re-fault the page as huge. The code snippet clearly shows the conditional call to `retract_page_tables` when `is_pmd_order(order)` is true. That function would handle removing the PTE page tables.

But hold on, what happens when it isn't? What if `!is_pmd_order(order)`?  The code doesn't explicitly handle that case here, we might need to check other parts of the surrounding code for how that is handled.

And then there's this `cc->policy.install_pmd` thing. If that's true, which it *can* be for madvise collapse, we set the result to `SCAN_PTE_MAPPED_HUGEPAGE`, which is interesting. It implies we're in the madvise case, but let's just make sure. Let's trace back where this `install_pmd` flag is set. I need to understand the control flow, because something is clearly missing in the context. Is this a bug? It is unusual that there is a conditional path where `install_pmd` is *never* true. Or is that the intention? This conditional is the key to understanding the behaviour of madvise collapse and how it interacts with the standard collapse. I need to clarify that.



72/3 2026/09/20 07:14 tool grepper
0m Args:
{
  "Expression": "install_pmd",
  "PathPrefix": "mm/"
}

Results:
{
  "Output": "mm/collapse.h=50=struct collapse_policy {\n--\nmm/collapse.h-65-\t/* Map the PMD over a file collapse instead of leaving it to a fault */\nmm/collapse.h:66:\tbool install_pmd;\nmm/collapse.h-67-\n--\nmm/khugepaged.c=953=static void collapse_policy_khugepaged(struct collapse_policy *p)\n--\nmm/khugepaged.c-960-\tp-\u003erequire_referenced = true;\nmm/khugepaged.c:961:\tp-\u003einstall_pmd = false;\nmm/khugepaged.c-962-\tp-\u003ewriteback_dirty = false;\n--\nmm/khugepaged.c=1795=static enum scan_result try_collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,\nmm/khugepaged.c:1796:\t\tbool install_pmd)\nmm/khugepaged.c-1797-{\n--\nmm/khugepaged.c-1859-\t\t */\nmm/khugepaged.c:1860:\t\tgoto maybe_install_pmd;\nmm/khugepaged.c-1861-\tdefault:\n--\nmm/khugepaged.c-1995-\nmm/khugepaged.c:1996:maybe_install_pmd:\nmm/khugepaged.c-1997-\t/* step 5: install pmd entry */\nmm/khugepaged.c:1998:\tresult = install_pmd\nmm/khugepaged.c-1999-\t\t\t? set_huge_pmd(vma, haddr, pmd, folio, \u0026folio-\u003epage)\n--\nmm/khugepaged.c-2026- * @addr: THP collapse address\nmm/khugepaged.c:2027: * @install_pmd: If a huge PMD should be installed\nmm/khugepaged.c-2028- *\n--\nmm/khugepaged.c=2033=void collapse_pte_mapped_thp(struct mm_struct *mm, unsigned long addr,\nmm/khugepaged.c:2034:\t\tbool install_pmd)\nmm/khugepaged.c-2035-{\nmm/khugepaged.c:2036:\ttry_collapse_pte_mapped_thp(mm, addr, install_pmd);\nmm/khugepaged.c-2037-}\n--\nmm/khugepaged.c=2187=static enum scan_result collapse_file(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2602-\t\tretract_page_tables(mapping, start);\nmm/khugepaged.c:2603:\tif (cc-\u003epolicy.install_pmd)\nmm/khugepaged.c-2604-\t\tresult = SCAN_PTE_MAPPED_HUGEPAGE;\n--\nmm/khugepaged.c=2861=enum scan_result collapse_run_pmd(struct mm_struct *mm, unsigned long addr,\n--\nmm/khugepaged.c-2902-\t\t\tresult = try_collapse_pte_mapped_thp(mm, addr,\nmm/khugepaged.c:2903:\t\t\t\t\t\t\tcc-\u003epolicy.install_pmd);\nmm/khugepaged.c-2904-\t\tif (result == SCAN_PMD_MAPPED)\n--\nmm/madvise.c=913=static void collapse_policy_forced(struct collapse_policy *p)\n--\nmm/madvise.c-920-\tp-\u003erequire_referenced = false;\nmm/madvise.c:921:\tp-\u003einstall_pmd = true;\nmm/madvise.c-922-\tp-\u003ewriteback_dirty = true;\n--\nmm/madvise.c=1253=static int guard_install_pud_entry(pud_t *pud, unsigned long addr,\n--\nmm/madvise.c-1261-\nmm/madvise.c:1262:static int guard_install_pmd_entry(pmd_t *pmd, unsigned long addr,\nmm/madvise.c-1263-\t\t\t\t   unsigned long next, struct mm_walk *walk)\n--\nmm/madvise.c=1300=static long madvise_guard_install(struct madvise_behavior *madv_behavior)\n--\nmm/madvise.c-1305-\t\t.pud_entry\t= guard_install_pud_entry,\nmm/madvise.c:1306:\t\t.pmd_entry\t= guard_install_pmd_entry,\nmm/madvise.c-1307-\t\t.pte_entry\t= guard_install_pte_entry,\n"
}

73/3 2026/09/20 07:14 llm kmsan-evaluator
0m Model:
gemini-3.8-flash

Args:
null

Results:
null

Tokens:
							input: 30760
							output: 335
							thoughts: 2283
						

Thoughts:
**KMSAN Assessment: Transparent Huge Page Collapse Patch**

Okay, let's break this down. My primary focus here is to determine if this patch necessitates a KMSAN run. It seems we're adding support for collapsing smaller-order transparent huge pages (mTHP) in khugepaged for shmem and file mappings, tweaking collapse order limits, refining PTE eligibility bitmap population during file scans, updating `collapse_file()` to embrace arbitrary THP orders, inlining `hugepage_madvise()`, and parsing shmem mount options.

First, let's remind ourselves: KMSAN is specifically for finding uninitialized memory reads and information leaks. We *don't* want to use it if KASAN, LOCKDEP, or standard debuggers will suffice. So, are we introducing any risks KMSAN is *designed* to catch? I think not.

Looking at the code, all local variables are explicitly initialized. We have `collapse_file()` allocating new folios, but any "holes" (uninitialized areas) are explicitly zeroed out with `clear_highpage()`. Furthermore, it's operating on *uptodate* folios, which means we're not exposing uninitialized data. The `collapse_control` struct is carefully reset, ensuring its fields are zeroed or otherwise initialized as part of setup or scan reset.

Critically, nothing appears to be leaking uninitialized kernel data to userspace through syscalls, ioctls, netlink, or any other method. We're not sending uninitialized structures or page contents to user space.

I've checked for the four KMSAN criteria: No structures exposed, no reliance on uninitialized variables, no allocation of uninitialized structures, and no bounds check issues leading to reads of uninitialized memory. Everything checks out.

Of course, this patch *does* touch memory management, and there are inherent risks with any such changes. We still need to be mindful of page table synchronization, rmap, locking, concurrency, and refcounting issues. However, those are *not* the domain of KMSAN. KASAN, LOCKDEP, and page debugging tools (`DEBUG_VM`) are perfectly suited to detect those kinds of issues.

Ultimately, this patch does not expose any uninitialized memory or introduce information leaks. All local variables and data structures are fully initialized before use. The code modifications ensure no uninitialized data reaches userspace. Therefore, we should set `NeedsKMSAN` to `false`. KMSAN isn't warranted here.



74/3 2026/09/20 07:15 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch series extends khugepaged to support collapsing multi-size Transparent Huge Pages (mTHP) for shmem and file-backed mappings. The changes include generalizing collapse_file() to arbitrary THP orders, scanning file mappings to build eligible PTE bitmaps, adjusting sysfs/boot parsing for shmem huge page policies, and inlining hugepage_madvise() into madvise_vma_behavior().\n\nKMSAN vs KASAN Applicability Analysis:\n1. Uninitialized Memory: No new uninitialized stack or heap variables are introduced. In collapse_scan_file(), all local variables and scan state are explicitly initialized or cleared via collapse_scan_reset() (which calls bitmap_zero() and memset()). Newly allocated collapse folios have unpopulated pages zeroed with clear_highpage() and valid pages copied from uptodate folios.\n2. Userspace Info-leaks: The changes do not introduce or modify copy_to_user(), put_user(), netlink attributes, socket options, or BPF buffers that could leak uninitialized kernel memory to user space.\n3. Bug Profile: Potential bugs in this area are locking issues, folio refcounting discrepancies, page table synchronization races, or out-of-bounds page indexing. These are detected by KASAN, LOCKDEP, and CONFIG_DEBUG_VM/CONFIG_DEBUG_PAGEALLOC, not KMSAN.\n\nTherefore, a dedicated KMSAN fuzzing session is not warranted for this patch series.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch series extends khugepaged to support collapsing multi-size Transparent Huge Pages (mTHP) for shmem and file-backed mappings. The changes include generalizing collapse_file() to arbitrary THP orders, scanning file mappings to build eligible PTE bitmaps, adjusting sysfs/boot parsing for shmem huge page policies, and inlining hugepage_madvise() into madvise_vma_behavior().\n\nKMSAN vs KASAN Applicability Analysis:\n1. Uninitialized Memory: No new uninitialized stack or heap variables are introduced. In collapse_scan_file(), all local variables and scan state are explicitly initialized or cleared via collapse_scan_reset() (which calls bitmap_zero() and memset()). Newly allocated collapse folios have unpopulated pages zeroed with clear_highpage() and valid pages copied from uptodate folios.\n2. Userspace Info-leaks: The changes do not introduce or modify copy_to_user(), put_user(), netlink attributes, socket options, or BPF buffers that could leak uninitialized kernel memory to user space.\n3. Bug Profile: Potential bugs in this area are locking issues, folio refcounting discrepancies, page table synchronization races, or out-of-bounds page indexing. These are detected by KASAN, LOCKDEP, and CONFIG_DEBUG_VM/CONFIG_DEBUG_PAGEALLOC, not KMSAN.\n\nTherefore, a dedicated KMSAN fuzzing session is not warranted for this patch series.",
  "NeedsKMSAN": false
}

LLM Calls Summary:
Total Calls Total Tokens Avg Tokens Total Duration (Seconds) Avg Duration (Seconds)
Tool Calls Summary:
Total Calls Total Duration (Seconds) Avg Duration (Seconds)