AI Trajectory


Trajectory: (Expand/Collapse All)
Seq Timestamp Type Name Duration
0/0 2026/09/02 08:37 flow patch-triage
1m Args:
null

Results:
{
  "EnableConfigs": [
    "SMP"
  ],
  "FocusSymbols": [
    "percpu_counter_tree_init_many",
    "percpu_counter_tree_destroy_many",
    "percpu_counter_tree_precise_sum",
    "percpu_counter_tree_approximate_compare",
    "percpu_counter_tree_approximate_compare_value",
    "percpu_counter_tree_precise_compare",
    "percpu_counter_tree_precise_compare_value",
    "percpu_counter_tree_set"
  ],
  "KMSANReasoning": "The patch introduces Hierarchical Per-CPU Counters (HPCC / percpu_counter_tree) and transitions `mm_struct`'s RSS accounting (`rss_stat`) to use this new counter tree mechanism with storage placed in the flexible array of `mm_struct`.\n\nAnalyzing the changes for uninitialized memory risks and applicability of KMSAN vs KASAN:\n1. Initialization: All `percpu_counter_tree` structures and their associated tree items are explicitly initialized via `percpu_counter_tree_init_many()` (using `memset` to zero out the items buffer, zero-initialized per-cpu memory via `__alloc_percpu_gfp`, and explicit field initialization in `__percpu_counter_tree_init()`). On UP builds, `count` is initialized with `atomic_long_set(\u0026counters[i].count, 0)`.\n2. Userspace info-leaks: RSS statistics are numeric values accessed via `get_mm_counter()` and exposed as formatted integers (e.g. in `/proc/$pid/status` via `seq_printf`), rather than direct structure copies or uninitialized padding copies to user space.\n3. Memory safety risks: The primary potential risks in this patch involve memory sizing of the flexible array at the end of `mm_struct`, array index calculations during carry propagation, or concurrency issues. These classes of bugs (such as out-of-bounds reads/writes or use-after-free) are monitored and detected by KASAN and standard sanitizers.\n\nBecause no uninitialized memory branches or kernel-to-userspace leaks are introduced or exposed, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false,
  "Reasoning": "The patch introduces Hierarchical Per-CPU Counters (HPCC) for scalable approximate/precise counter aggregation and integrates them into core memory management (struct mm_struct RSS accounting). This introduces complex concurrency, carry propagation, and comparison logic in reachable core kernel paths on SMP systems.",
  "WorthFuzzing": true
}

1/1 2026/09/02 08:37 action read-patch-diff
0m Args:
null

Results:
{
  "PatchDiff": "commit 016f492f9418f19378197191c764e46711442f39\nAuthor: syz-cluster \u003ctriage@syzkaller.com\u003e\nDate:   Wed Sep 2 08:37:00 2026 +0000\n\n    syz-cluster: applied patch under review\n\ndiff --git a/Documentation/core-api/percpu-counter-tree.rst b/Documentation/core-api/percpu-counter-tree.rst\nnew file mode 100644\nindex 0000000000000..196da056e7b42\n--- /dev/null\n+++ b/Documentation/core-api/percpu-counter-tree.rst\n@@ -0,0 +1,75 @@\n+========================================\n+The Hierarchical Per-CPU Counters (HPCC)\n+========================================\n+\n+:Author: Mathieu Desnoyers\n+\n+Introduction\n+============\n+\n+Counters come in many varieties, each with their own trade offs:\n+\n+ * A global atomic counter provides a fast read access to the current\n+   sum, at the expense of cache-line bouncing on updates. This leads to\n+   poor performance of frequent updates from various cores on large SMP\n+   systems.\n+\n+ * A per-cpu split counter provides fast updates to per-cpu counters,\n+   at the expense of a slower aggregation (sum). The sum operation needs\n+   to iterate over all per-cpu counters to calculate the current total.\n+\n+The hierarchical per-cpu counters attempt to provide the best of both\n+worlds (fast updates, and fast sum) by relaxing requirements on the sum\n+accuracy. It allows quickly querying an approximated sum value, along\n+with the possible min/max ranges of the associated precise sum. The\n+exact precise sum can still be calculated with an iteration on all\n+per-cpu counter, but the availability of an approximated sum value with\n+possible precise sum min/max ranges allows eliminating candidates which\n+are certainly outside of a known target range without the overhead of\n+precise sums.\n+\n+Overview\n+========\n+\n+The herarchical per-cpu counters are organized as a tree with the tree\n+root at the bottom (last level) and the first level of the tree\n+consisting of per-cpu counters.\n+\n+The intermediate tree levels contain carry propagation counters. When\n+reaching a threshold (batch size), the carry is propagated down the\n+tree.\n+\n+This allows reading an approximated value at the root, which has a\n+bounded accuracy (minimum/maximum possible precise sum range) determined\n+by the tree topology.\n+\n+Use Cases\n+=========\n+\n+Use cases HPCC is meant to handle invove tracking resources which are\n+used across many CPUs to quickly sum as feedback for decision making to\n+apply throttling, quota limits, sort tasks, and perform memory or task\n+migration decisions. When considering approximated sums within the\n+accuracy range of the decision threshold, the user can either:\n+\n+ * Be conservative and fast: Consider that the sum has reached the\n+   limit as soon as the given limit is within the approximation range.\n+\n+ * Be aggressive and fast: Consider that the sum is over the\n+   limit only when the approximation range is over the given limit.\n+\n+ * Be precise and slow: Do a precise comparison with the limit, which\n+   requires a precise sum when the limit is within the approximated\n+   range.\n+\n+One use-case for these hierarchical counters is to implement a two-pass\n+algorithm to speed up sorting picking a maximum/minimunm sum value from\n+a set. A first pass compares the approximated values, and then a second\n+pass only needs the precise sum for counter trees which are within the\n+possible precise sum range of the counter tree chosen by the first pass.\n+\n+Functions and structures\n+========================\n+\n+.. kernel-doc:: include/linux/percpu_counter_tree.h\n+.. kernel-doc:: lib/percpu_counter_tree.c\ndiff --git a/include/linux/mm.h b/include/linux/mm.h\nindex dd09c438fa23e..ffbcd18c4ecb3 100644\n--- a/include/linux/mm.h\n+++ b/include/linux/mm.h\n@@ -3447,38 +3447,48 @@ static inline bool get_user_page_fast_only(unsigned long addr,\n {\n \treturn get_user_pages_fast_only(addr, 1, gup_flags, pagep) == 1;\n }\n+\n+static inline struct percpu_counter_tree_level_item *get_rss_stat_items(struct mm_struct *mm)\n+{\n+\tunsigned long ptr = (unsigned long)mm;\n+\n+\tptr += offsetof(struct mm_struct, flexible_array);\n+\tptr += get_rss_stat_items_offset();\n+\treturn (struct percpu_counter_tree_level_item *)ptr;\n+}\n+\n /*\n  * per-process(per-mm_struct) statistics.\n  */\n static inline unsigned long get_mm_counter(struct mm_struct *mm, int member)\n {\n-\treturn percpu_counter_read_positive(\u0026mm-\u003erss_stat[member]);\n+\treturn percpu_counter_tree_approximate_sum_positive(\u0026mm-\u003erss_stat[member]);\n }\n \n static inline unsigned long get_mm_counter_sum(struct mm_struct *mm, int member)\n {\n-\treturn percpu_counter_sum_positive(\u0026mm-\u003erss_stat[member]);\n+\treturn percpu_counter_tree_precise_sum_positive(\u0026mm-\u003erss_stat[member]);\n }\n \n void mm_trace_rss_stat(struct mm_struct *mm, int member);\n \n static inline void add_mm_counter(struct mm_struct *mm, int member, long value)\n {\n-\tpercpu_counter_add(\u0026mm-\u003erss_stat[member], value);\n+\tpercpu_counter_tree_add(\u0026mm-\u003erss_stat[member], value);\n \n \tmm_trace_rss_stat(mm, member);\n }\n \n static inline void inc_mm_counter(struct mm_struct *mm, int member)\n {\n-\tpercpu_counter_inc(\u0026mm-\u003erss_stat[member]);\n+\tpercpu_counter_tree_add(\u0026mm-\u003erss_stat[member], 1);\n \n \tmm_trace_rss_stat(mm, member);\n }\n \n static inline void dec_mm_counter(struct mm_struct *mm, int member)\n {\n-\tpercpu_counter_dec(\u0026mm-\u003erss_stat[member]);\n+\tpercpu_counter_tree_add(\u0026mm-\u003erss_stat[member], -1);\n \n \tmm_trace_rss_stat(mm, member);\n }\ndiff --git a/include/linux/mm_types.h b/include/linux/mm_types.h\nindex 6d815f6440c94..b26160b85f93a 100644\n--- a/include/linux/mm_types.h\n+++ b/include/linux/mm_types.h\n@@ -18,7 +18,7 @@\n #include \u003clinux/page-flags-layout.h\u003e\n #include \u003clinux/workqueue.h\u003e\n #include \u003clinux/seqlock.h\u003e\n-#include \u003clinux/percpu_counter.h\u003e\n+#include \u003clinux/percpu_counter_tree.h\u003e\n #include \u003clinux/types.h\u003e\n #include \u003clinux/futex_types.h\u003e\n #include \u003clinux/rseq_types.h\u003e\n@@ -1170,6 +1170,19 @@ typedef struct {\n \tDECLARE_BITMAP(__mm_flags, NUM_MM_FLAG_BITS);\n } __private mm_flags_t;\n \n+/*\n+ * The alignment of the mm_struct flexible array is based on the largest\n+ * alignment of its content:\n+ * __alignof__(struct percpu_counter_tree_level_item) provides a\n+ * cacheline aligned alignment on SMP systems, else alignment on\n+ * unsigned long on UP systems.\n+ */\n+#ifdef CONFIG_SMP\n+# define __mm_struct_flexible_array_aligned\t__aligned(__alignof__(struct percpu_counter_tree_level_item))\n+#else\n+# define __mm_struct_flexible_array_aligned\t__aligned(__alignof__(unsigned long))\n+#endif\n+\n struct kioctx_table;\n struct iommu_mm_data;\n struct mm_struct {\n@@ -1312,7 +1325,7 @@ struct mm_struct {\n \t\tunsigned long saved_e_flags;\n #endif\n \n-\t\tstruct percpu_counter rss_stat[NR_MM_COUNTERS];\n+\t\tstruct percpu_counter_tree rss_stat[NR_MM_COUNTERS];\n \n \t\tstruct linux_binfmt *binfmt;\n \n@@ -1422,10 +1435,14 @@ struct mm_struct {\n \t} __randomize_layout;\n \n \t/*\n-\t * The mm_cpumask needs to be at the end of mm_struct, because it\n-\t * is dynamically sized based on nr_cpu_ids.\n+\t * The mm_cpumask, mm_cid masks, and rss hierarchical counter\n+\t * items need to be at the end of mm_struct, because they are\n+\t * dynamically sized based on nr_cpu_ids.\n+\t * The HPCC counter tree items are placed last and aligned\n+\t * with PERCPU_COUNTER_TREE_ITEMS_ALIGN to satisfy their\n+\t * cacheline alignment requirement.\n \t */\n-\tchar flexible_array[] __aligned(__alignof__(unsigned long));\n+\tchar flexible_array[] __mm_struct_flexible_array_aligned;\n };\n \n /* Copy value to the first system word of mm flags, non-atomically. */\n@@ -1462,18 +1479,12 @@ static inline void __mm_flags_set_mask_bits_word(struct mm_struct *mm,\n \t\t\t MT_FLAGS_USE_RCU)\n extern struct mm_struct init_mm;\n \n-#define MM_STRUCT_FLEXIBLE_ARRAY_INIT\t\t\t\t\\\n-{\t\t\t\t\t\t\t\t\\\n-\t[0 ... sizeof(cpumask_t) + MM_CID_STATIC_SIZE - 1] = 0\t\\\n-}\n-\n-/* Pointer magic because the dynamic array size confuses some compilers. */\n-static inline void mm_init_cpumask(struct mm_struct *mm)\n-{\n-\tunsigned long cpu_bitmap = (unsigned long)mm;\n-\n-\tcpu_bitmap += offsetof(struct mm_struct, flexible_array);\n-\tcpumask_clear((struct cpumask *)cpu_bitmap);\n+#define MM_STRUCT_FLEXIBLE_ARRAY_INIT\t\t\t\t\t\t\\\n+{\t\t\t\t\t\t\t\t\t\t\\\n+\t[0 ... PERCPU_COUNTER_TREE_ITEMS_ALIGN(\t\t\t\t\t\\\n+\t\t\tsizeof(cpumask_t) + MM_CID_STATIC_SIZE)\t\t\t\\\n+\t       + (PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE * NR_MM_COUNTERS)\t\\\n+\t       - 1] = 0\t\t\t\t\t\t\t\t\\\n }\n \n /* Future-safe accessor for struct mm_struct's cpu_vm_mask. */\n@@ -1482,6 +1493,11 @@ static inline cpumask_t *mm_cpumask(struct mm_struct *mm)\n \treturn (struct cpumask *)\u0026mm-\u003eflexible_array;\n }\n \n+static inline void mm_init_cpumask(struct mm_struct *mm)\n+{\n+\tcpumask_clear((struct cpumask *)mm_cpumask(mm));\n+}\n+\n #ifdef CONFIG_LRU_GEN\n \n struct lru_gen_mm_list {\n@@ -1653,6 +1669,21 @@ static inline void mm_destroy_sched(struct mm_struct *mm) { }\n \n #endif /* CONFIG_SCHED_CACHE */\n \n+static inline size_t get_rss_stat_items_size(void)\n+{\n+\treturn percpu_counter_tree_items_size() * NR_MM_COUNTERS;\n+}\n+\n+/*\n+ * Return the offset of the RSS stat HPCC items within the mm_struct\n+ * flexible array. The items are placed after the cpumask and mm_cid,\n+ * aligned to the cacheline boundary required by the tree level items.\n+ */\n+static inline size_t get_rss_stat_items_offset(void)\n+{\n+\treturn PERCPU_COUNTER_TREE_ITEMS_ALIGN(cpumask_size() + mm_cid_size());\n+}\n+\n struct mmu_gather;\n extern void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm);\n extern void tlb_gather_mmu_fullmm(struct mmu_gather *tlb, struct mm_struct *mm);\ndiff --git a/include/linux/percpu_counter_tree.h b/include/linux/percpu_counter_tree.h\nnew file mode 100644\nindex 0000000000000..4095acdc879bf\n--- /dev/null\n+++ b/include/linux/percpu_counter_tree.h\n@@ -0,0 +1,387 @@\n+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */\n+/* SPDX-FileCopyrightText: 2025 Mathieu Desnoyers \u003cmathieu.desnoyers@efficios.com\u003e */\n+\n+#ifndef _PERCPU_COUNTER_TREE_H\n+#define _PERCPU_COUNTER_TREE_H\n+\n+#include \u003clinux/preempt.h\u003e\n+#include \u003clinux/atomic.h\u003e\n+#include \u003clinux/percpu.h\u003e\n+\n+#ifdef CONFIG_SMP\n+\n+#if NR_CPUS == (1U \u003c\u003c 0)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t0\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 1)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t1\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 2)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t3\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 3)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t7\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 4)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t7\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 5)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t11\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 6)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t21\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 7)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t21\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 8)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t37\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 9)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t73\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 10)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t149\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 11)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t293\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 12)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t585\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 13)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t1173\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 14)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t2341\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 15)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t4681\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 16)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t4681\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 17)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t8777\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 18)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t17481\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 19)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t34953\n+#elif NR_CPUS \u003c= (1U \u003c\u003c 20)\n+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t69905\n+#else\n+# error \"Unsupported number of CPUs.\"\n+#endif\n+\n+struct percpu_counter_tree_level_item {\n+\tatomic_long_t count;\t\t/*\n+\t\t\t\t\t * Count the number of carry for this tree item.\n+\t\t\t\t\t * The carry counter is kept at the order of the\n+\t\t\t\t\t * carry accounted for at this tree level.\n+\t\t\t\t\t */\n+} ____cacheline_aligned_in_smp;\n+\n+#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE\t\\\n+\t(PERCPU_COUNTER_TREE_STATIC_NR_ITEMS * sizeof(struct percpu_counter_tree_level_item))\n+#define PERCPU_COUNTER_TREE_ITEMS_ALIGN(offset)\t\\\n+\tALIGN((offset), __alignof__(struct percpu_counter_tree_level_item))\n+\n+struct percpu_counter_tree {\n+\t/* Fast-path fields. */\n+\tunsigned long __percpu *level0;\t/* Pointer to per-CPU split counters (tree level 0). */\n+\tunsigned long level0_bit_mask;\t/* Bit mask to apply to detect carry propagation from tree level 0. */\n+\tunion {\n+\t\tunsigned long *i;\t/* Approximate sum for single-CPU topology. */\n+\t\tatomic_long_t *a;\t/* Approximate sum for SMP topology.  */\n+\t} approx_sum;\n+\tlong bias;\t\t\t/* Bias to apply to counter precise and approximate values. */\n+\n+\t/* Slow-path fields. */\n+\tstruct percpu_counter_tree_level_item *items;\t/* Array of tree items for levels 1 to N. */\n+\tunsigned long batch_size;\t/*\n+\t\t\t\t\t * The batch size is the increment step at level 0 which\n+\t\t\t\t\t * triggers a carry propagation. The batch size is required\n+\t\t\t\t\t * to be greater than 1, and a power of 2.\n+\t\t\t\t\t */\n+\t/*\n+\t * The tree approximate sum is guaranteed to be within this accuracy range:\n+\t * (precise_sum - approx_accuracy_range.under) \u003c= approx_sum \u003c= (precise_sum + approx_accuracy_range.over).\n+\t * This accuracy is derived from the hardware topology and the tree batch_size.\n+\t * The \"under\" accuracy is larger than the \"over\" accuracy because the negative range of a\n+\t * two's complement signed integer is one unit larger than the positive range. This delta\n+\t * is summed for each tree item, which leads to a significantly larger \"under\" accuracy range\n+\t * compared to the \"over\" accuracy range.\n+\t */\n+\tstruct {\n+\t\tunsigned long under;\n+\t\tunsigned long over;\n+\t} approx_accuracy_range;\n+};\n+\n+extern size_t __percpu_counter_tree_items_size __ro_after_init;\n+\n+/*\n+ * percpu_counter_tree_items_size - Query the size required for counter tree items.\n+ *\n+ * Query the size of the memory area required to hold the counter tree\n+ * items. This depends on the hardware topology and is invariant after\n+ * boot.\n+ *\n+ * Return: Size required to hold tree items.\n+ */\n+static inline\n+size_t percpu_counter_tree_items_size(void)\n+{\n+\tWARN_ON_ONCE(__percpu_counter_tree_items_size == SIZE_MAX);\n+\treturn __percpu_counter_tree_items_size;\n+}\n+\n+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,\n+\t\t\t\t  unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags);\n+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,\n+\t\t\t     unsigned long batch_size, gfp_t gfp_flags);\n+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counter, unsigned int nr_counters);\n+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter);\n+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc);\n+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter);\n+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b);\n+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v);\n+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b);\n+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v);\n+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v);\n+int percpu_counter_tree_subsystem_init(void);\n+\n+/**\n+ * percpu_counter_tree_approximate_sum() - Return approximate counter sum.\n+ * @counter: The counter to sum.\n+ *\n+ * Querying the approximate sum is fast, but it is only accurate within\n+ * the bounds delimited by percpu_counter_tree_approximate_accuracy_range().\n+ * This is meant to be used when speed is preferred over accuracy.\n+ *\n+ * Return: The current approximate counter sum.\n+ */\n+static inline\n+long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)\n+{\n+\tunsigned long v;\n+\n+\tif (!counter-\u003elevel0_bit_mask)\n+\t\tv = READ_ONCE(*counter-\u003eapprox_sum.i);\n+\telse\n+\t\tv = atomic_long_read(counter-\u003eapprox_sum.a);\n+\treturn (long) (v + (unsigned long)READ_ONCE(counter-\u003ebias));\n+}\n+\n+/**\n+ * percpu_counter_tree_approximate_accuracy_range - Query the accuracy range for a counter tree.\n+ * @counter: Counter to query.\n+ * @under: Pointer to a variable to be incremented of the approximation\n+ *         accuracy range below the precise sum.\n+ * @over: Pointer to a variable to be incremented of the approximation\n+ *        accuracy range above the precise sum.\n+ *\n+ * Query the accuracy range limits for the counter.\n+ * Because of two's complement binary representation, the \"under\" range is typically\n+ * slightly larger than the \"over\" range.\n+ * Those values are derived from the hardware topology and the counter tree batch size.\n+ * They are invariant for a given counter tree.\n+ * Using this function should not be typically required, see the following functions instead:\n+ * * percpu_counter_tree_approximate_compare(),\n+ * * percpu_counter_tree_approximate_compare_value(),\n+ * * percpu_counter_tree_precise_compare(),\n+ * * percpu_counter_tree_precise_compare_value().\n+ */\n+static inline\n+void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *counter,\n+\t\t\t\t\t\t    unsigned long *under, unsigned long *over)\n+{\n+\t*under += counter-\u003eapprox_accuracy_range.under;\n+\t*over += counter-\u003eapprox_accuracy_range.over;\n+}\n+\n+#else\t/* !CONFIG_SMP */\n+\n+#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE\t0\n+#define PERCPU_COUNTER_TREE_ITEMS_ALIGN(offset)\t(offset)\n+\n+struct percpu_counter_tree_level_item;\n+\n+struct percpu_counter_tree {\n+\tatomic_long_t count;\n+};\n+\n+static inline\n+size_t percpu_counter_tree_items_size(void)\n+{\n+\treturn 0;\n+}\n+\n+static inline\n+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,\n+\t\t\t\t  unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags)\n+{\n+\tfor (unsigned int i = 0; i \u003c nr_counters; i++)\n+\t\tatomic_long_set(\u0026counters[i].count, 0);\n+\treturn 0;\n+}\n+\n+static inline\n+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,\n+\t\t\t     unsigned long batch_size, gfp_t gfp_flags)\n+{\n+\treturn percpu_counter_tree_init_many(counter, items, 1, batch_size, gfp_flags);\n+}\n+\n+static inline\n+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counter, unsigned int nr_counters)\n+{\n+}\n+\n+static inline\n+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter)\n+{\n+}\n+\n+static inline\n+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter)\n+{\n+\treturn atomic_long_read(\u0026counter-\u003ecount);\n+}\n+\n+static inline\n+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)\n+{\n+\tlong count_a = percpu_counter_tree_precise_sum(a),\n+\t     count_b = percpu_counter_tree_precise_sum(b);\n+\n+\tif (count_a == count_b)\n+\t\treturn 0;\n+\tif (count_a \u003c count_b)\n+\t\treturn -1;\n+\treturn 1;\n+}\n+\n+static inline\n+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v)\n+{\n+\tlong count = percpu_counter_tree_precise_sum(counter);\n+\n+\tif (count == v)\n+\t\treturn 0;\n+\tif (count \u003c v)\n+\t\treturn -1;\n+\treturn 1;\n+}\n+\n+static inline\n+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)\n+{\n+\treturn percpu_counter_tree_precise_compare(a, b);\n+}\n+\n+static inline\n+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v)\n+{\n+\treturn percpu_counter_tree_precise_compare_value(counter, v);\n+}\n+\n+static inline\n+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v)\n+{\n+\tatomic_long_set(\u0026counter-\u003ecount, v);\n+}\n+\n+static inline\n+void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *counter,\n+\t\t\t\t\t\t    unsigned long *under, unsigned long *over)\n+{\n+}\n+\n+static inline\n+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc)\n+{\n+\tatomic_long_add(inc, \u0026counter-\u003ecount);\n+}\n+\n+static inline\n+long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)\n+{\n+\treturn percpu_counter_tree_precise_sum(counter);\n+}\n+\n+static inline\n+int percpu_counter_tree_subsystem_init(void)\n+{\n+\treturn 0;\n+}\n+\n+#endif\t/* CONFIG_SMP */\n+\n+/**\n+ * percpu_counter_tree_approximate_sum_positive() - Return a positive approximate counter sum.\n+ * @counter: The counter to sum.\n+ *\n+ * Return an approximate counter sum which is guaranteed to be greater\n+ * or equal to 0.\n+ *\n+ * Return: The current positive approximate counter sum.\n+ */\n+static inline\n+long percpu_counter_tree_approximate_sum_positive(struct percpu_counter_tree *counter)\n+{\n+\tlong v = percpu_counter_tree_approximate_sum(counter);\n+\treturn v \u003e 0 ? v : 0;\n+}\n+\n+/**\n+ * percpu_counter_tree_precise_sum_positive() - Return a positive precise counter sum.\n+ * @counter: The counter to sum.\n+ *\n+ * Return a precise counter sum which is guaranteed to be greater\n+ * or equal to 0.\n+ *\n+ * Return: The current positive precise counter sum.\n+ */\n+static inline\n+long percpu_counter_tree_precise_sum_positive(struct percpu_counter_tree *counter)\n+{\n+\tlong v = percpu_counter_tree_precise_sum(counter);\n+\treturn v \u003e 0 ? v : 0;\n+}\n+\n+/**\n+ * percpu_counter_tree_approximate_min_max_range() - Return the approximation min and max precise values.\n+ * @approx_sum: Approximated sum.\n+ * @under: Tree accuracy range (under).\n+ * @over: Tree accuracy range (over).\n+ * @precise_min: Minimum possible value for precise sum (output).\n+ * @precise_max: Maximum possible value for precise sum (output).\n+ *\n+ * Calculate the minimum and maximum precise values for a given\n+ * approximation and (under, over) accuracy range.\n+ *\n+ * The range of the approximation as a function of the precise sum is expressed as:\n+ *\n+ *   approx_sum \u003e= precise_sum - approx_accuracy_range.under\n+ *   approx_sum \u003c= precise_sum + approx_accuracy_range.over\n+ *\n+ * Therefore, the range of the precise sum as a function of the approximation is expressed as:\n+ *\n+ *   precise_sum \u003c= approx_sum + approx_accuracy_range.under\n+ *   precise_sum \u003e= approx_sum - approx_accuracy_range.over\n+ */\n+static inline\n+void percpu_counter_tree_approximate_min_max_range(long approx_sum, unsigned long under, unsigned long over,\n+\t\t\t\t\t\t   long *precise_min, long *precise_max)\n+{\n+\t*precise_min = approx_sum - over;\n+\t*precise_max = approx_sum + under;\n+}\n+\n+/**\n+ * percpu_counter_tree_approximate_min_max() - Return the tree approximation, min and max possible precise values.\n+ * @counter: The counter to sum.\n+ * @approx_sum: Approximate sum (output).\n+ * @precise_min: Minimum possible value for precise sum (output).\n+ * @precise_max: Maximum possible value for precise sum (output).\n+ *\n+ * Return the approximate sum, minimum and maximum precise values for\n+ * a counter.\n+ */\n+static inline\n+void percpu_counter_tree_approximate_min_max(struct percpu_counter_tree *counter,\n+\t\t\t\t\t     long *approx_sum, long *precise_min, long *precise_max)\n+{\n+\tunsigned long under = 0, over = 0;\n+\tlong v = percpu_counter_tree_approximate_sum(counter);\n+\n+\tpercpu_counter_tree_approximate_accuracy_range(counter, \u0026under, \u0026over);\n+\tpercpu_counter_tree_approximate_min_max_range(v, under, over, precise_min, precise_max);\n+\t*approx_sum = v;\n+}\n+\n+#endif  /* _PERCPU_COUNTER_TREE_H */\ndiff --git a/include/trace/events/kmem.h b/include/trace/events/kmem.h\nindex cd7920c81f85b..290ccb9fd25dd 100644\n--- a/include/trace/events/kmem.h\n+++ b/include/trace/events/kmem.h\n@@ -448,7 +448,7 @@ TRACE_EVENT(rss_stat,\n \t\t */\n \t\t__entry-\u003ecurr = current-\u003emm == mm \u0026\u0026 !(current-\u003eflags \u0026 PF_KTHREAD);\n \t\t__entry-\u003emember = member;\n-\t\t__entry-\u003esize = (percpu_counter_sum_positive(\u0026mm-\u003erss_stat[member])\n+\t\t__entry-\u003esize = (percpu_counter_tree_approximate_sum_positive(\u0026mm-\u003erss_stat[member])\n \t\t\t\t\t\t\t    \u003c\u003c PAGE_SHIFT);\n \t),\n \ndiff --git a/init/main.c b/init/main.c\nindex 2613d3f9b3ce9..845cb57e90965 100644\n--- a/init/main.c\n+++ b/init/main.c\n@@ -108,6 +108,7 @@\n #include \u003clinux/time_namespace.h\u003e\n #include \u003clinux/unaligned.h\u003e\n #include \u003clinux/vdso_datastore.h\u003e\n+#include \u003clinux/percpu_counter_tree.h\u003e\n #include \u003cnet/net_namespace.h\u003e\n \n #include \u003casm/io.h\u003e\n@@ -1010,6 +1011,7 @@ void start_kernel(void)\n \tsetup_boot_config();\n \tsetup_command_line(command_line);\n \tsetup_nr_cpu_ids();\n+\tpercpu_counter_tree_subsystem_init();\n \tsetup_per_cpu_areas();\n \tsmp_prepare_boot_cpu();\t/* arch-specific boot-cpu hooks */\n \tearly_numa_node_init();\ndiff --git a/kernel/fork.c b/kernel/fork.c\nindex 416758c8a3d43..db398b6c52886 100644\n--- a/kernel/fork.c\n+++ b/kernel/fork.c\n@@ -137,6 +137,11 @@\n  */\n #define MAX_THREADS FUTEX_TID_MASK\n \n+/*\n+ * Batch size of rss stat approximation\n+ */\n+#define RSS_STAT_BATCH_SIZE\t32\n+\n /*\n  * Protected counters by write_lock_irq(\u0026tasklist_lock)\n  */\n@@ -633,14 +638,12 @@ static void check_mm(struct mm_struct *mm)\n \t\t\t \"Please make sure 'struct resident_page_types[]' is updated as well\");\n \n \tfor (i = 0; i \u003c NR_MM_COUNTERS; i++) {\n-\t\tlong x = percpu_counter_sum(\u0026mm-\u003erss_stat[i]);\n-\n-\t\tif (unlikely(x)) {\n+\t\tif (unlikely(percpu_counter_tree_precise_compare_value(\u0026mm-\u003erss_stat[i], 0) != 0))\n \t\t\tpr_alert(\"BUG: Bad rss-counter state mm:%p type:%s val:%ld Comm:%s Pid:%d\\n\",\n-\t\t\t\t mm, resident_page_types[i], x,\n+\t\t\t\t mm, resident_page_types[i],\n+\t\t\t\t percpu_counter_tree_precise_sum(\u0026mm-\u003erss_stat[i]),\n \t\t\t\t current-\u003ecomm,\n \t\t\t\t task_pid_nr(current));\n-\t\t}\n \t}\n \n \tif (mm_pgtables_bytes(mm))\n@@ -738,7 +741,7 @@ void __mmdrop(struct mm_struct *mm)\n \tcheck_mm(mm);\n \tmm_pasid_drop(mm);\n \tmm_destroy_cid(mm);\n-\tpercpu_counter_destroy_many(mm-\u003erss_stat, NR_MM_COUNTERS);\n+\tpercpu_counter_tree_destroy_many(mm-\u003erss_stat, NR_MM_COUNTERS);\n \n \tfree_mm(mm);\n }\n@@ -1144,8 +1147,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)\n \tif (mm_alloc_sched(mm))\n \t\tgoto fail_sched;\n \n-\tif (percpu_counter_init_many(mm-\u003erss_stat, 0, GFP_KERNEL_ACCOUNT,\n-\t\t\t\t     NR_MM_COUNTERS))\n+\tif (percpu_counter_tree_init_many(mm-\u003erss_stat, get_rss_stat_items(mm),\n+\t\t\t\t\t  NR_MM_COUNTERS, RSS_STAT_BATCH_SIZE,\n+\t\t\t\t\t  GFP_KERNEL_ACCOUNT))\n \t\tgoto fail_pcpu;\n \n \tlru_gen_init_mm(mm);\n@@ -3122,7 +3126,9 @@ void __init mm_cache_init(void)\n \t * dynamically sized based on the maximum CPU number this system\n \t * can have, taking hotplug into account (nr_cpu_ids).\n \t */\n-\tmm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size();\n+\tmm_size = sizeof(struct mm_struct) +\n+\t\tPERCPU_COUNTER_TREE_ITEMS_ALIGN(cpumask_size() + mm_cid_size()) +\n+\t\tget_rss_stat_items_size();\n \n \tmm_cachep = kmem_cache_create_usercopy(\"mm_struct\",\n \t\t\tmm_size, ARCH_MIN_MMSTRUCT_ALIGN,\ndiff --git a/lib/Kconfig b/lib/Kconfig\nindex 4e6b34c3346d5..c0524258b2058 100644\n--- a/lib/Kconfig\n+++ b/lib/Kconfig\n@@ -41,6 +41,18 @@ config PACKING_KUNIT_TEST\n \n \t  When in doubt, say N.\n \n+config PERCPU_COUNTER_TREE_KUNIT_TEST\n+\ttristate \"KUnit tests for hierarchical per-cpu counters\" if !KUNIT_ALL_TESTS\n+\tdepends on KUNIT\n+\tdefault KUNIT_ALL_TESTS\n+\thelp\n+\t  This builds Kunit tests for the hierarchical per-cpu counters.\n+\n+\t  For more information on KUnit and unit tests in general,\n+\t  please refer to the KUnit documentation in Documentation/dev-tools/kunit/.\n+\n+\t  When in doubt, say N.\n+\n config BITREVERSE\n \ttristate\n \tselect GENERIC_BITREVERSE if !HAVE_ARCH_BITREVERSE\ndiff --git a/lib/Makefile b/lib/Makefile\nindex dfab958327c5c..f1d0cb831630b 100644\n--- a/lib/Makefile\n+++ b/lib/Makefile\n@@ -182,6 +182,7 @@ obj-$(CONFIG_TEXTSEARCH_KMP) += ts_kmp.o\n obj-$(CONFIG_TEXTSEARCH_BM) += ts_bm.o\n obj-$(CONFIG_TEXTSEARCH_FSM) += ts_fsm.o\n obj-$(CONFIG_SMP) += percpu_counter.o\n+obj-$(CONFIG_SMP) += percpu_counter_tree.o\n obj-$(CONFIG_AUDIT_GENERIC) += audit.o\n obj-$(CONFIG_AUDIT_COMPAT_GENERIC) += compat_audit.o\n \ndiff --git a/lib/percpu_counter_tree.c b/lib/percpu_counter_tree.c\nnew file mode 100644\nindex 0000000000000..cfa5b04e05d7e\n--- /dev/null\n+++ b/lib/percpu_counter_tree.c\n@@ -0,0 +1,694 @@\n+// SPDX-License-Identifier: GPL-2.0+ OR MIT\n+// SPDX-FileCopyrightText: 2025 Mathieu Desnoyers \u003cmathieu.desnoyers@efficios.com\u003e\n+\n+/*\n+ * Split Counters With Tree Approximation Propagation\n+ *\n+ * * Propagation diagram when reaching batch size thresholds (± batch size):\n+ *\n+ * Example diagram for 8 CPUs:\n+ *\n+ * log2(8) = 3 levels\n+ *\n+ * At each level, each pair propagates its values to the next level when\n+ * reaching the batch size thresholds.\n+ *\n+ * Counters at levels 0, 1, 2 can be kept on a single byte ([-128 .. +127] range),\n+ * although it may be relevant to keep them on \"long\" counters for\n+ * simplicity. (complexity vs memory footprint tradeoff)\n+ *\n+ * Counter at level 3 can be kept on a \"long\" counter.\n+ *\n+ * Level 0:  0    1    2    3    4    5    6    7\n+ *           |   /     |   /     |   /     |   /\n+ *           |  /      |  /      |  /      |  /\n+ *           | /       | /       | /       | /\n+ * Level 1:  0         1         2         3\n+ *           |       /           |       /\n+ *           |    /              |    /\n+ *           | /                 | /\n+ * Level 2:  0                   1\n+ *           |               /\n+ *           |         /\n+ *           |   /\n+ * Level 3:  0\n+ *\n+ * * Approximation accuracy:\n+ *\n+ * BATCH(level N): Level N batch size.\n+ *\n+ * Example for BATCH(level 0) = 32.\n+ *\n+ * BATCH(level 0) =  32\n+ * BATCH(level 1) =  64\n+ * BATCH(level 2) = 128\n+ * BATCH(level N) = BATCH(level 0) * 2^N\n+ *\n+ *            per-counter     global\n+ *            accuracy        accuracy\n+ * Level 0:   [ -32 ..  +31]  ±256  (8 * 32)\n+ * Level 1:   [ -64 ..  +63]  ±256  (4 * 64)\n+ * Level 2:   [-128 .. +127]  ±256  (2 * 128)\n+ * Total:      ------         ±768  (log2(nr_cpu_ids) * BATCH(level 0) * nr_cpu_ids)\n+ *\n+ * Note that the global accuracy can be calculated more precisely\n+ * by taking into account that the positive accuracy range is\n+ * 31 rather than 32.\n+ *\n+ * -----\n+ *\n+ * Approximate Sum Carry Propagation\n+ *\n+ * Let's define a number of counter bits for each level, e.g.:\n+ *\n+ * log2(BATCH(level 0)) = log2(32) = 5\n+ * Let's assume, for this example, a 32-bit architecture (sizeof(long) == 4).\n+ *\n+ *               nr_bit        value_mask                      range\n+ * Level 0:      5 bits        v                             0 ..  +31\n+ * Level 1:      1 bit        (v \u0026 ~((1UL \u003c\u003c 5) - 1))        0 ..  +63\n+ * Level 2:      1 bit        (v \u0026 ~((1UL \u003c\u003c 6) - 1))        0 .. +127\n+ * Level 3:     25 bits       (v \u0026 ~((1UL \u003c\u003c 7) - 1))        0 .. 2^32-1\n+ *\n+ * Note: Use a \"long\" per-cpu counter at level 0 to allow precise sum.\n+ *\n+ * Note: Use cacheline aligned counters at levels above 0 to prevent false sharing.\n+ *       If memory footprint is an issue, a specialized allocator could be used\n+ *       to eliminate padding.\n+ *\n+ * Example with expanded values:\n+ *\n+ * counter_add(counter, inc):\n+ *\n+ *         if (!inc)\n+ *                 return;\n+ *\n+ *         res = percpu_add_return(counter @ Level 0, inc);\n+ *         orig = res - inc;\n+ *         if (inc \u003c 0) {\n+ *                 inc = -(-inc \u0026 ~0b00011111);  // Clear used bits\n+ *                 // xor bit 5: underflow\n+ *                 if ((inc ^ orig ^ res) \u0026 0b00100000)\n+ *                         inc -= 0b00100000;\n+ *         } else {\n+ *                 inc \u0026= ~0b00011111;           // Clear used bits\n+ *                 // xor bit 5: overflow\n+ *                 if ((inc ^ orig ^ res) \u0026 0b00100000)\n+ *                         inc += 0b00100000;\n+ *         }\n+ *         if (!inc)\n+ *                 return;\n+ *\n+ *         res = atomic_long_add_return(counter @ Level 1, inc);\n+ *         orig = res - inc;\n+ *         if (inc \u003c 0) {\n+ *                 inc = -(-inc \u0026 ~0b00111111);  // Clear used bits\n+ *                 // xor bit 6: underflow\n+ *                 if ((inc ^ orig ^ res) \u0026 0b01000000)\n+ *                         inc -= 0b01000000;\n+ *         } else {\n+ *                 inc \u0026= ~0b00111111;           // Clear used bits\n+ *                 // xor bit 6: overflow\n+ *                 if ((inc ^ orig ^ res) \u0026 0b01000000)\n+ *                         inc += 0b01000000;\n+ *         }\n+ *         if (!inc)\n+ *                 return;\n+ *\n+ *         res = atomic_long_add_return(counter @ Level 2, inc);\n+ *         orig = res - inc;\n+ *         if (inc \u003c 0) {\n+ *                 inc = -(-inc \u0026 ~0b01111111);  // Clear used bits\n+ *                 // xor bit 7: underflow\n+ *                 if ((inc ^ orig ^ res) \u0026 0b10000000)\n+ *                         inc -= 0b10000000;\n+ *         } else {\n+ *                 inc \u0026= ~0b01111111;           // Clear used bits\n+ *                 // xor bit 7: overflow\n+ *                 if ((inc ^ orig ^ res) \u0026 0b10000000)\n+ *                         inc += 0b10000000;\n+ *         }\n+ *         if (!inc)\n+ *                 return;\n+ *\n+ *         atomic_long_add(counter @ Level 3, inc);\n+ */\n+\n+#include \u003clinux/percpu_counter_tree.h\u003e\n+#include \u003clinux/cpumask.h\u003e\n+#include \u003clinux/atomic.h\u003e\n+#include \u003clinux/export.h\u003e\n+#include \u003clinux/percpu.h\u003e\n+#include \u003clinux/errno.h\u003e\n+#include \u003clinux/slab.h\u003e\n+#include \u003clinux/math.h\u003e\n+\n+#define MAX_NR_LEVELS 5\n+\n+/*\n+ * The counter configuration is selected at boot time based on the\n+ * hardware topology.\n+ */\n+struct counter_config {\n+\tunsigned int nr_items;\t\t\t\t/*\n+\t\t\t\t\t\t\t * nr_items is the number of items in the tree for levels 1\n+\t\t\t\t\t\t\t * up to and including the final level (approximate sum).\n+\t\t\t\t\t\t\t * It excludes the level 0 per-CPU counters.\n+\t\t\t\t\t\t\t */\n+\tunsigned char nr_levels;\t\t\t/*\n+\t\t\t\t\t\t\t * nr_levels is the number of hierarchical counter tree levels.\n+\t\t\t\t\t\t\t * It excludes the final level (approximate sum).\n+\t\t\t\t\t\t\t */\n+\tunsigned char n_arity_order[MAX_NR_LEVELS];\t/*\n+\t\t\t\t\t\t\t * n-arity of tree nodes for each level from\n+\t\t\t\t\t\t\t * 0 to (nr_levels - 1).\n+\t\t\t\t\t\t\t */\n+};\n+\n+static const struct counter_config per_nr_cpu_order_config[] = {\n+\t[0] =\t{ .nr_items = 0,\t.nr_levels = 0,\t\t.n_arity_order = { 0 } },\n+\t[1] =\t{ .nr_items = 1,\t.nr_levels = 1,\t\t.n_arity_order = { 1 } },\n+\t[2] =\t{ .nr_items = 3,\t.nr_levels = 2,\t\t.n_arity_order = { 1, 1 } },\n+\t[3] =\t{ .nr_items = 7,\t.nr_levels = 3,\t\t.n_arity_order = { 1, 1, 1 } },\n+\t[4] =\t{ .nr_items = 7,\t.nr_levels = 3,\t\t.n_arity_order = { 2, 1, 1 } },\n+\t[5] =\t{ .nr_items = 11,\t.nr_levels = 3,\t\t.n_arity_order = { 2, 2, 1 } },\n+\t[6] =\t{ .nr_items = 21,\t.nr_levels = 3,\t\t.n_arity_order = { 2, 2, 2 } },\n+\t[7] =\t{ .nr_items = 21,\t.nr_levels = 3,\t\t.n_arity_order = { 3, 2, 2 } },\n+\t[8] =\t{ .nr_items = 37,\t.nr_levels = 3,\t\t.n_arity_order = { 3, 3, 2 } },\n+\t[9] =\t{ .nr_items = 73,\t.nr_levels = 3,\t\t.n_arity_order = { 3, 3, 3 } },\n+\t[10] =\t{ .nr_items = 149,\t.nr_levels = 4,\t\t.n_arity_order = { 3, 3, 2, 2 } },\n+\t[11] =\t{ .nr_items = 293,\t.nr_levels = 4,\t\t.n_arity_order = { 3, 3, 3, 2 } },\n+\t[12] =\t{ .nr_items = 585,\t.nr_levels = 4,\t\t.n_arity_order = { 3, 3, 3, 3 } },\n+\t[13] =\t{ .nr_items = 1173,\t.nr_levels = 5,\t\t.n_arity_order = { 3, 3, 3, 2, 2 } },\n+\t[14] =\t{ .nr_items = 2341,\t.nr_levels = 5,\t\t.n_arity_order = { 3, 3, 3, 3, 2 } },\n+\t[15] =\t{ .nr_items = 4681,\t.nr_levels = 5,\t\t.n_arity_order = { 3, 3, 3, 3, 3 } },\n+\t[16] =\t{ .nr_items = 4681,\t.nr_levels = 5,\t\t.n_arity_order = { 4, 3, 3, 3, 3 } },\n+\t[17] =\t{ .nr_items = 8777,\t.nr_levels = 5,\t\t.n_arity_order = { 4, 4, 3, 3, 3 } },\n+\t[18] =\t{ .nr_items = 17481,\t.nr_levels = 5,\t\t.n_arity_order = { 4, 4, 4, 3, 3 } },\n+\t[19] =\t{ .nr_items = 34953,\t.nr_levels = 5,\t\t.n_arity_order = { 4, 4, 4, 4, 3 } },\n+\t[20] =\t{ .nr_items = 69905,\t.nr_levels = 5,\t\t.n_arity_order = { 4, 4, 4, 4, 4 } },\n+};\n+\n+static const struct counter_config *counter_config;\t/* Hierarchical counter configuration for the hardware topology. */\n+static unsigned int nr_cpus_order;\t\t\t/* Order of nr_cpu_ids. */\n+static unsigned long accuracy_multiplier;\t\t/* Calculate accuracy for a given batch size (multiplication factor). */\n+\n+static\n+int __percpu_counter_tree_init(struct percpu_counter_tree *counter,\n+\t\t\t       unsigned long batch_size, gfp_t gfp_flags,\n+\t\t\t       unsigned long __percpu *level0,\n+\t\t\t       struct percpu_counter_tree_level_item *items)\n+{\n+\t/* Batch size must be greater than 1, and a power of 2. */\n+\tif (WARN_ON(batch_size \u003c= 1 || (batch_size \u0026 (batch_size - 1))))\n+\t\treturn -EINVAL;\n+\tcounter-\u003ebatch_size = batch_size;\n+\tcounter-\u003ebias = 0;\n+\tcounter-\u003elevel0 = level0;\n+\tcounter-\u003eitems = items;\n+\tif (!nr_cpus_order) {\n+\t\tcounter-\u003eapprox_sum.i = per_cpu_ptr(counter-\u003elevel0, 0);\n+\t\tcounter-\u003elevel0_bit_mask = 0;\n+\t} else {\n+\t\tcounter-\u003eapprox_sum.a = \u0026counter-\u003eitems[counter_config-\u003enr_items - 1].count;\n+\t\tcounter-\u003elevel0_bit_mask = 1UL \u003c\u003c get_count_order(batch_size);\n+\t}\n+\t/*\n+\t * Each tree item signed integer has a negative range which is\n+\t * one unit greater than the positive range.\n+\t */\n+\tcounter-\u003eapprox_accuracy_range.under = batch_size * accuracy_multiplier;\n+\tcounter-\u003eapprox_accuracy_range.over = (batch_size - 1) * accuracy_multiplier;\n+\treturn 0;\n+}\n+\n+/**\n+ * percpu_counter_tree_init_many() - Initialize many per-CPU counter trees.\n+ * @counters: An array of @nr_counters counters to initialize.\n+ *\t      Their memory is provided by the caller.\n+ * @items: Pointer to memory area where to store tree items.\n+ *\t   This memory is provided by the caller.\n+ *\t   Its size needs to be at least @nr_counters * percpu_counter_tree_items_size().\n+ * @nr_counters: The number of counter trees to initialize\n+ * @batch_size: The batch size is the increment step at level 0 which triggers a\n+ * \t\tcarry propagation.\n+ *\t\tThe batch size is required to be greater than 1, and a power of 2.\n+ * @gfp_flags: gfp flags to pass to the per-CPU allocator.\n+ *\n+ * Initialize many per-CPU counter trees using a single per-CPU\n+ * allocator invocation for @nr_counters counters.\n+ *\n+ * Return:\n+ * * %0: Success\n+ * * %-EINVAL:\t\t- Invalid @batch_size argument\n+ * * %-ENOMEM:\t\t- Out of memory\n+ */\n+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,\n+\t\t\t\t  unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags)\n+{\n+\tvoid __percpu *level0, *level0_iter;\n+\tsize_t counter_size = sizeof(*counters-\u003elevel0),\n+\t       items_size = percpu_counter_tree_items_size();\n+\tvoid *items_iter;\n+\tunsigned int i;\n+\tint ret;\n+\n+\tmemset(items, 0, items_size * nr_counters);\n+\tlevel0 = __alloc_percpu_gfp(nr_counters * counter_size,\n+\t\t\t\t    __alignof__(*counters-\u003elevel0), gfp_flags);\n+\tif (!level0)\n+\t\treturn -ENOMEM;\n+\tlevel0_iter = level0;\n+\titems_iter = items;\n+\tfor (i = 0; i \u003c nr_counters; i++) {\n+\t\tret = __percpu_counter_tree_init(\u0026counters[i], batch_size, gfp_flags, level0_iter, items_iter);\n+\t\tif (ret)\n+\t\t\tgoto free_level0;\n+\t\tlevel0_iter += counter_size;\n+\t\titems_iter += items_size;\n+\t}\n+\treturn 0;\n+\n+free_level0:\n+\tfree_percpu(level0);\n+\treturn ret;\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_init_many);\n+\n+/**\n+ * percpu_counter_tree_init() - Initialize one per-CPU counter tree.\n+ * @counter: Counter to initialize.\n+ *\t     Its memory is provided by the caller.\n+ * @items: Pointer to memory area where to store tree items.\n+ *\t   This memory is provided by the caller.\n+ *\t   Its size needs to be at least percpu_counter_tree_items_size().\n+ * @batch_size: The batch size is the increment step at level 0 which triggers a\n+ * \t\tcarry propagation.\n+ *\t\tThe batch size is required to be greater than 1, and a power of 2.\n+ * @gfp_flags: gfp flags to pass to the per-CPU allocator.\n+ *\n+ * Initialize one per-CPU counter tree.\n+ *\n+ * Return:\n+ * * %0: Success\n+ * * %-EINVAL:\t\t- Invalid @batch_size argument\n+ * * %-ENOMEM:\t\t- Out of memory\n+ */\n+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,\n+\t\t\t     unsigned long batch_size, gfp_t gfp_flags)\n+{\n+\treturn percpu_counter_tree_init_many(counter, items, 1, batch_size, gfp_flags);\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_init);\n+\n+/**\n+ * percpu_counter_tree_destroy_many() - Destroy many per-CPU counter trees.\n+ * @counters: Array of counters trees to destroy.\n+ * @nr_counters: The number of counter trees to destroy.\n+ *\n+ * Release internal resources allocated for @nr_counters per-CPU counter trees.\n+ */\n+\n+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counters, unsigned int nr_counters)\n+{\n+\tfree_percpu(counters-\u003elevel0);\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_destroy_many);\n+\n+/**\n+ * percpu_counter_tree_destroy() - Destroy one per-CPU counter tree.\n+ * @counter: Counter to destroy.\n+ *\n+ * Release internal resources allocated for one per-CPU counter tree.\n+ */\n+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter)\n+{\n+\treturn percpu_counter_tree_destroy_many(counter, 1);\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_destroy);\n+\n+static\n+long percpu_counter_tree_carry(long orig, long res, long inc, unsigned long bit_mask)\n+{\n+\tif (inc \u003c 0) {\n+\t\tinc = -(-inc \u0026 ~(bit_mask - 1));\n+\t\t/*\n+\t\t * xor bit_mask: underflow.\n+\t\t *\n+\t\t * If inc has bit set, decrement an additional bit if\n+\t\t * there is _no_ bit transition between orig and res.\n+\t\t * Else, inc has bit cleared, decrement an additional\n+\t\t * bit if there is a bit transition between orig and\n+\t\t * res.\n+\t\t */\n+\t\tif ((inc ^ orig ^ res) \u0026 bit_mask)\n+\t\t\tinc -= bit_mask;\n+\t} else {\n+\t\tinc \u0026= ~(bit_mask - 1);\n+\t\t/*\n+\t\t * xor bit_mask: overflow.\n+\t\t *\n+\t\t * If inc has bit set, increment an additional bit if\n+\t\t * there is _no_ bit transition between orig and res.\n+\t\t * Else, inc has bit cleared, increment an additional\n+\t\t * bit if there is a bit transition between orig and\n+\t\t * res.\n+\t\t */\n+\t\tif ((inc ^ orig ^ res) \u0026 bit_mask)\n+\t\t\tinc += bit_mask;\n+\t}\n+\treturn inc;\n+}\n+\n+/*\n+ * It does not matter through which path the carry propagates up the\n+ * tree, therefore there is no need to disable preemption because the\n+ * cpu number is only used to favor cache locality.\n+ */\n+static\n+void percpu_counter_tree_add_slowpath(struct percpu_counter_tree *counter, long inc)\n+{\n+\tunsigned int level_items, nr_levels = counter_config-\u003enr_levels,\n+\t\t     level, n_arity_order;\n+\tunsigned long bit_mask;\n+\tstruct percpu_counter_tree_level_item *item = counter-\u003eitems;\n+\tunsigned int cpu = raw_smp_processor_id();\n+\n+\tWARN_ON_ONCE(!nr_cpus_order);\t/* Should never be called for 1 cpu. */\n+\n+\tn_arity_order = counter_config-\u003en_arity_order[0];\n+\tbit_mask = counter-\u003elevel0_bit_mask \u003c\u003c n_arity_order;\n+\tlevel_items = 1U \u003c\u003c (nr_cpus_order - n_arity_order);\n+\n+\tfor (level = 1; level \u003c nr_levels; level++) {\n+\t\t/*\n+\t\t * For the purpose of carry propagation, the\n+\t\t * intermediate level counters only need to keep track\n+\t\t * of the bits relevant for carry propagation. We\n+\t\t * therefore don't care about higher order bits.\n+\t\t * Note that this optimization is unwanted if the\n+\t\t * intended use is to track counters within intermediate\n+\t\t * levels of the topology.\n+\t\t */\n+\t\tif (abs(inc) \u0026 (bit_mask - 1)) {\n+\t\t\tatomic_long_t *count = \u0026item[cpu \u0026 (level_items - 1)].count;\n+\t\t\tunsigned long orig, res;\n+\n+\t\t\tres = atomic_long_add_return_relaxed(inc, count);\n+\t\t\torig = res - inc;\n+\t\t\tinc = percpu_counter_tree_carry(orig, res, inc, bit_mask);\n+\t\t\tif (likely(!inc))\n+\t\t\t\treturn;\n+\t\t}\n+\t\titem += level_items;\n+\t\tn_arity_order = counter_config-\u003en_arity_order[level];\n+\t\tlevel_items \u003e\u003e= n_arity_order;\n+\t\tbit_mask \u003c\u003c= n_arity_order;\n+\t}\n+\tatomic_long_add(inc, counter-\u003eapprox_sum.a);\n+}\n+\n+/**\n+ * percpu_counter_tree_add() - Add to a per-CPU counter tree.\n+ * @counter: Counter added to.\n+ * @inc: Increment value (either positive or negative).\n+ *\n+ * Add @inc to a per-CPU counter tree. This is a fast-path which will\n+ * typically increment per-CPU counters as long as there is no carry\n+ * greater or equal to the counter tree batch size.\n+ */\n+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc)\n+{\n+\tunsigned long bit_mask = counter-\u003elevel0_bit_mask, orig, res;\n+\n+\tres = this_cpu_add_return(*counter-\u003elevel0, inc);\n+\torig = res - inc;\n+\tinc = percpu_counter_tree_carry(orig, res, inc, bit_mask);\n+\tif (likely(!inc))\n+\t\treturn;\n+\tpercpu_counter_tree_add_slowpath(counter, inc);\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_add);\n+\n+static\n+long percpu_counter_tree_precise_sum_unbiased(struct percpu_counter_tree *counter)\n+{\n+\tunsigned long sum = 0;\n+\tint cpu;\n+\n+\tfor_each_possible_cpu(cpu)\n+\t\tsum += *per_cpu_ptr(counter-\u003elevel0, cpu);\n+\treturn (long) sum;\n+}\n+\n+/**\n+ * percpu_counter_tree_precise_sum() - Return precise counter sum.\n+ * @counter: The counter to sum.\n+ *\n+ * Querying the precise sum is relatively expensive because it needs to\n+ * iterate over all CPUs.\n+ * This is meant to be used when accuracy is preferred over speed.\n+ *\n+ * Return: The current precise counter sum.\n+ */\n+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter)\n+{\n+\treturn percpu_counter_tree_precise_sum_unbiased(counter) + READ_ONCE(counter-\u003ebias);\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_sum);\n+\n+static\n+int compare_delta(long delta, unsigned long accuracy_neg, unsigned long accuracy_pos)\n+{\n+\tif (delta \u003e= 0) {\n+\t\tif (delta \u003c= accuracy_pos)\n+\t\t\treturn 0;\n+\t\telse\n+\t\t\treturn 1;\n+\t} else {\n+\t\tif (-delta \u003c= accuracy_neg)\n+\t\t\treturn 0;\n+\t\telse\n+\t\t\treturn -1;\n+\t}\n+}\n+\n+/**\n+ * percpu_counter_tree_approximate_compare - Approximated comparison of two counter trees.\n+ * @a: First counter to compare.\n+ * @b: Second counter to compare.\n+ *\n+ * Evaluate an approximate comparison of two counter trees.\n+ * This approximation comparison is fast, and provides an accurate\n+ * answer if the counters are found to be either less than or greater\n+ * than the other. However, if the approximated comparison returns\n+ * 0, the counters respective sums are found to be within the two\n+ * counters accuracy range.\n+ *\n+ * Return:\n+ * * %0\t\t- Counters @a and @b do not differ by more than the sum of their respective\n+ *                accuracy ranges.\n+ * * %-1\t- Counter @a less than counter @b.\n+ * * %1\t\t- Counter @a is greater than counter @b.\n+ */\n+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)\n+{\n+\treturn compare_delta(percpu_counter_tree_approximate_sum(a) - percpu_counter_tree_approximate_sum(b),\n+\t\t\t     a-\u003eapprox_accuracy_range.over + b-\u003eapprox_accuracy_range.under,\n+\t\t\t     a-\u003eapprox_accuracy_range.under + b-\u003eapprox_accuracy_range.over);\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_approximate_compare);\n+\n+/**\n+ * percpu_counter_tree_approximate_compare_value - Approximated comparison of a counter tree against a given value.\n+ * @counter: Counter to compare.\n+ * @v: Value to compare.\n+ *\n+ * Evaluate an approximate comparison of a counter tree against a given value.\n+ * This approximation comparison is fast, and provides an accurate\n+ * answer if the counter is found to be either less than or greater\n+ * than the value. However, if the approximated comparison returns\n+ * 0, the value is within the counter accuracy range.\n+ *\n+ * Return:\n+ * * %0\t\t- The value @v is within the accuracy range of the counter.\n+ * * %-1\t- The value @v is less than the counter.\n+ * * %1\t\t- The value @v is greater than the counter.\n+ */\n+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v)\n+{\n+\treturn compare_delta(v - percpu_counter_tree_approximate_sum(counter),\n+\t\t\t     counter-\u003eapprox_accuracy_range.under,\n+\t\t\t     counter-\u003eapprox_accuracy_range.over);\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_approximate_compare_value);\n+\n+/**\n+ * percpu_counter_tree_precise_compare - Precise comparison of two counter trees.\n+ * @a: First counter to compare.\n+ * @b: Second counter to compare.\n+ *\n+ * Evaluate a precise comparison of two counter trees.\n+ * As an optimization, it uses the approximate counter comparison\n+ * to quickly compare counters which are far apart. Only cases where\n+ * counter sums are within the accuracy range require precise counter\n+ * sums.\n+ *\n+ * Return:\n+ * * %0\t\t- Counters are equal.\n+ * * %-1\t- Counter @a less than counter @b.\n+ * * %1\t\t- Counter @a is greater than counter @b.\n+ */\n+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)\n+{\n+\tlong count_a = percpu_counter_tree_approximate_sum(a),\n+\t     count_b = percpu_counter_tree_approximate_sum(b);\n+\tunsigned long accuracy_a, accuracy_b;\n+\tlong delta = count_a - count_b;\n+\tint res;\n+\n+\tres = compare_delta(delta,\n+\t\t\t    a-\u003eapprox_accuracy_range.over + b-\u003eapprox_accuracy_range.under,\n+\t\t\t    a-\u003eapprox_accuracy_range.under + b-\u003eapprox_accuracy_range.over);\n+\t/* The values are distanced enough for an accurate approximated comparison. */\n+\tif (res)\n+\t\treturn res;\n+\n+\t/*\n+\t * The approximated comparison is within the accuracy range, therefore at least one\n+\t * precise sum is needed. Sum the counter which has the largest accuracy first.\n+\t */\n+\tif (delta \u003e= 0) {\n+\t\taccuracy_a = a-\u003eapprox_accuracy_range.under;\n+\t\taccuracy_b = b-\u003eapprox_accuracy_range.over;\n+\t} else {\n+\t\taccuracy_a = a-\u003eapprox_accuracy_range.over;\n+\t\taccuracy_b = b-\u003eapprox_accuracy_range.under;\n+\t}\n+\tif (accuracy_b \u003c accuracy_a) {\n+\t\tcount_a = percpu_counter_tree_precise_sum(a);\n+\t\tres = compare_delta(count_a - count_b,\n+\t\t\t\t    b-\u003eapprox_accuracy_range.under,\n+\t\t\t\t    b-\u003eapprox_accuracy_range.over);\n+\t\tif (res)\n+\t\t\treturn res;\n+\t\t/* Precise sum of second counter is required. */\n+\t\tcount_b = percpu_counter_tree_precise_sum(b);\n+\t} else {\n+\t\tcount_b = percpu_counter_tree_precise_sum(b);\n+\t\tres = compare_delta(count_a - count_b,\n+\t\t\t\t    a-\u003eapprox_accuracy_range.over,\n+\t\t\t\t    a-\u003eapprox_accuracy_range.under);\n+\t\tif (res)\n+\t\t\treturn res;\n+\t\t/* Precise sum of second counter is required. */\n+\t\tcount_a = percpu_counter_tree_precise_sum(a);\n+\t}\n+\tif (count_a - count_b \u003c 0)\n+\t\treturn -1;\n+\tif (count_a - count_b \u003e 0)\n+\t\treturn 1;\n+\treturn 0;\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_compare);\n+\n+/**\n+ * percpu_counter_tree_precise_compare_value - Precise comparison of a counter tree against a given value.\n+ * @counter: Counter to compare.\n+ * @v: Value to compare.\n+ *\n+ * Evaluate a precise comparison of a counter tree against a given value.\n+ * As an optimization, it uses the approximate counter comparison\n+ * to quickly identify whether the counter and value are far apart.\n+ * Only cases where the value is within the counter accuracy range\n+ * require a precise counter sum.\n+ *\n+ * Return:\n+ * * %0\t\t- The value @v is equal to the counter.\n+ * * %-1\t- The value @v is less than the counter.\n+ * * %1\t\t- The value @v is greater than the counter.\n+ */\n+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v)\n+{\n+\tlong count = percpu_counter_tree_approximate_sum(counter);\n+\tint res;\n+\n+\tres = compare_delta(v - count,\n+\t\t\t    counter-\u003eapprox_accuracy_range.under,\n+\t\t\t    counter-\u003eapprox_accuracy_range.over);\n+\t/* The values are distanced enough for an accurate approximated comparison. */\n+\tif (res)\n+\t\treturn res;\n+\n+\t/* Precise sum is required. */\n+\tcount = percpu_counter_tree_precise_sum(counter);\n+\tif (v - count \u003c 0)\n+\t\treturn -1;\n+\tif (v - count \u003e 0)\n+\t\treturn 1;\n+\treturn 0;\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_compare_value);\n+\n+static\n+void percpu_counter_tree_set_bias(struct percpu_counter_tree *counter, long bias)\n+{\n+\tWRITE_ONCE(counter-\u003ebias, bias);\n+}\n+\n+/**\n+ * percpu_counter_tree_set - Set the counter tree sum to a given value.\n+ * @counter: Counter to set.\n+ * @v: Value to set.\n+ *\n+ * Set the counter sum to a given value. It can be useful for instance\n+ * to reset the counter sum to 0. Note that even after setting the\n+ * counter sum to a given value, the counter sum approximation can\n+ * return any value within the accuracy range around that value.\n+ */\n+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v)\n+{\n+\tpercpu_counter_tree_set_bias(counter,\n+\t\t\t\t     v - percpu_counter_tree_precise_sum_unbiased(counter));\n+}\n+EXPORT_SYMBOL_GPL(percpu_counter_tree_set);\n+\n+/* Initialize to SIZE_MAX to catch early boot misuses. */\n+size_t __percpu_counter_tree_items_size __ro_after_init = SIZE_MAX;\n+EXPORT_SYMBOL_GPL(__percpu_counter_tree_items_size);\n+\n+static void __init calculate_accuracy_topology(void)\n+{\n+\tunsigned int nr_levels = counter_config-\u003enr_levels, level;\n+\tunsigned int level_items = 1U \u003c\u003c nr_cpus_order;\n+\tunsigned long batch_size = 1;\n+\n+\tfor (level = 0; level \u003c nr_levels; level++) {\n+\t\tunsigned int n_arity_order = counter_config-\u003en_arity_order[level];\n+\n+\t\t/*\n+\t\t * The accuracy multiplier is derived from a batch size of 1\n+\t\t * to speed up calculating the accuracy at tree initialization.\n+\t\t */\n+\t\taccuracy_multiplier += batch_size * level_items;\n+\t\tbatch_size \u003c\u003c= n_arity_order;\n+\t\tlevel_items \u003e\u003e= n_arity_order;\n+\t}\n+}\n+\n+int __init percpu_counter_tree_subsystem_init(void)\n+{\n+\tnr_cpus_order = get_count_order(nr_cpu_ids);\n+\tif (WARN_ON_ONCE(nr_cpus_order \u003e= ARRAY_SIZE(per_nr_cpu_order_config))) {\n+\t\tprintk(KERN_ERR \"Unsupported number of CPUs (%u)\\n\", nr_cpu_ids);\n+\t\treturn -1;\n+\t}\n+\tcounter_config = \u0026per_nr_cpu_order_config[nr_cpus_order];\n+\tif (!nr_cpus_order)\n+\t\t__percpu_counter_tree_items_size = 0;\n+\telse\n+\t\t__percpu_counter_tree_items_size = counter_config-\u003enr_items *\n+\t\t\tsizeof(struct percpu_counter_tree_level_item);\n+\tcalculate_accuracy_topology();\n+\treturn 0;\n+}\ndiff --git a/lib/tests/Makefile b/lib/tests/Makefile\nindex 3cac3b63a7522..051e73705977b 100644\n--- a/lib/tests/Makefile\n+++ b/lib/tests/Makefile\n@@ -58,4 +58,6 @@ obj-$(CONFIG_UTIL_MACROS_KUNIT) += util_macros_kunit.o\n obj-$(CONFIG_RATELIMIT_KUNIT_TEST) += test_ratelimit.o\n obj-$(CONFIG_UUID_KUNIT_TEST) += uuid_kunit.o\n \n+obj-$(CONFIG_PERCPU_COUNTER_TREE_KUNIT_TEST) += percpu_counter_tree_kunit.o\n+\n obj-$(CONFIG_TEST_RUNTIME_MODULE)\t\t+= module/\ndiff --git a/lib/tests/percpu_counter_tree_kunit.c b/lib/tests/percpu_counter_tree_kunit.c\nnew file mode 100644\nindex 0000000000000..a79176655c4b0\n--- /dev/null\n+++ b/lib/tests/percpu_counter_tree_kunit.c\n@@ -0,0 +1,399 @@\n+// SPDX-License-Identifier: GPL-2.0+ OR MIT\n+// SPDX-FileCopyrightText: 2026 Mathieu Desnoyers \u003cmathieu.desnoyers@efficios.com\u003e\n+\n+#include \u003ckunit/test.h\u003e\n+#include \u003clinux/percpu_counter_tree.h\u003e\n+#include \u003clinux/kthread.h\u003e\n+#include \u003clinux/wait.h\u003e\n+#include \u003clinux/random.h\u003e\n+\n+struct multi_thread_test_data {\n+\tlong increment;\n+\tint nr_inc;\n+\tint counter_index;\n+};\n+\n+#define NR_COUNTERS\t2\n+\n+/* Hierarchical per-CPU counter instances. */\n+static struct percpu_counter_tree counter[NR_COUNTERS];\n+static struct percpu_counter_tree_level_item *items;\n+\n+/* Global atomic counters for validation. */\n+static atomic_long_t global_counter[NR_COUNTERS];\n+\n+static DECLARE_WAIT_QUEUE_HEAD(kernel_threads_wq);\n+static atomic_t kernel_threads_to_run;\n+\n+static void complete_work(void)\n+{\n+\tif (atomic_dec_and_test(\u0026kernel_threads_to_run))\n+\t\twake_up(\u0026kernel_threads_wq);\n+}\n+\n+static void hpcc_print_info(struct kunit *test)\n+{\n+\tkunit_info(test, \"Running test with %d CPUs\\n\", num_online_cpus());\n+}\n+\n+static void add_to_counter(int counter_index, unsigned int nr_inc, long increment)\n+{\n+\tunsigned int i;\n+\n+\tfor (i = 0; i \u003c nr_inc; i++) {\n+\t\tpercpu_counter_tree_add(\u0026counter[counter_index], increment);\n+\t\tatomic_long_add(increment, \u0026global_counter[counter_index]);\n+\t}\n+}\n+\n+static void check_counters(struct kunit *test)\n+{\n+\tint counter_index;\n+\n+\t/* Compare each counter with its global counter. */\n+\tfor (counter_index = 0; counter_index \u003c NR_COUNTERS; counter_index++) {\n+\t\tlong v = atomic_long_read(\u0026global_counter[counter_index]);\n+\t\tlong approx_sum = percpu_counter_tree_approximate_sum(\u0026counter[counter_index]);\n+\t\tunsigned long under_accuracy = 0, over_accuracy = 0;\n+\t\tlong precise_min, precise_max;\n+\n+\t\t/* Precise comparison. */\n+\t\tKUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(\u0026counter[counter_index]), v);\n+\t\tKUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_precise_compare_value(\u0026counter[counter_index], v));\n+\n+\t\t/* Approximate comparison. */\n+\t\tKUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(\u0026counter[counter_index], v));\n+\n+\t\t/* Accuracy limits checks. */\n+\t\tpercpu_counter_tree_approximate_accuracy_range(\u0026counter[counter_index], \u0026under_accuracy, \u0026over_accuracy);\n+\n+\t\tKUNIT_EXPECT_GE(test, (long)(approx_sum - (v - under_accuracy)), 0);\n+\t\tKUNIT_EXPECT_LE(test, (long)(approx_sum - (v + over_accuracy)), 0);\n+\t\tKUNIT_EXPECT_GT(test, (long)(approx_sum - (v - under_accuracy - 1)), 0);\n+\t\tKUNIT_EXPECT_LT(test, (long)(approx_sum - (v + over_accuracy + 1)), 0);\n+\n+\t\t/* Precise min/max range check. */\n+\t\tpercpu_counter_tree_approximate_min_max_range(approx_sum, under_accuracy, over_accuracy, \u0026precise_min, \u0026precise_max);\n+\n+\t\tKUNIT_EXPECT_GE(test, v - precise_min, 0);\n+\t\tKUNIT_EXPECT_LE(test, v - precise_max, 0);\n+\t\tKUNIT_EXPECT_GT(test, v - (precise_min - 1), 0);\n+\t\tKUNIT_EXPECT_LT(test, v - (precise_max + 1), 0);\n+\t}\n+\t/* Compare each counter with the second counter. */\n+\tKUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(\u0026counter[0]), percpu_counter_tree_precise_sum(\u0026counter[1]));\n+\tKUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_precise_compare(\u0026counter[0], \u0026counter[1]));\n+\tKUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare(\u0026counter[0], \u0026counter[1]));\n+}\n+\n+static int multi_thread_worker_fn(void *data)\n+{\n+\tstruct multi_thread_test_data *td = data;\n+\n+\tadd_to_counter(td-\u003ecounter_index, td-\u003enr_inc, td-\u003eincrement);\n+\tcomplete_work();\n+\tkfree(td);\n+\treturn 0;\n+}\n+\n+static void test_run_on_specific_cpu(struct kunit *test, int target_cpu, int counter_index, unsigned int nr_inc, long increment)\n+{\n+\tstruct task_struct *task;\n+\tstruct multi_thread_test_data *td = kzalloc(sizeof(struct multi_thread_test_data), GFP_KERNEL);\n+\n+\tKUNIT_EXPECT_PTR_NE(test, td, NULL);\n+\ttd-\u003eincrement = increment;\n+\ttd-\u003enr_inc = nr_inc;\n+\ttd-\u003ecounter_index = counter_index;\n+\tatomic_inc(\u0026kernel_threads_to_run);\n+\ttask = kthread_run_on_cpu(multi_thread_worker_fn, td, target_cpu, \"kunit_multi_thread_worker\");\n+\tKUNIT_ASSERT_NOT_ERR_OR_NULL(test, task);\n+}\n+\n+static void init_kthreads(void)\n+{\n+\tatomic_set(\u0026kernel_threads_to_run, 1);\n+}\n+\n+static void fini_kthreads(void)\n+{\n+\t/* Release our own reference. */\n+\tcomplete_work();\n+\t/* Wait for all others threads to run. */\n+\twait_event(kernel_threads_wq, (atomic_read(\u0026kernel_threads_to_run) == 0));\n+}\n+\n+static void test_sync_kthreads(void)\n+{\n+\tfini_kthreads();\n+\tinit_kthreads();\n+}\n+\n+static void init_counters(struct kunit *test, unsigned long batch_size)\n+{\n+\tint i, ret;\n+\n+\titems = kzalloc(percpu_counter_tree_items_size() * NR_COUNTERS, GFP_KERNEL);\n+\tKUNIT_EXPECT_PTR_NE(test, items, NULL);\n+\tret = percpu_counter_tree_init_many(counter, items, NR_COUNTERS, batch_size, GFP_KERNEL);\n+\tKUNIT_EXPECT_EQ(test, ret, 0);\n+\n+\tfor (i = 0; i \u003c NR_COUNTERS; i++)\n+\t\tatomic_long_set(\u0026global_counter[i], 0);\n+}\n+\n+static void fini_counters(void)\n+{\n+\tpercpu_counter_tree_destroy_many(counter, NR_COUNTERS);\n+\tkfree(items);\n+}\n+\n+enum up_test_inc_type {\n+\tINC_ONE,\n+\tINC_MINUS_ONE,\n+\tINC_RANDOM,\n+};\n+\n+/*\n+ * Single-threaded tests. Those use many threads to run on various CPUs,\n+ * but synchronize for completion of each thread before running the\n+ * next, effectively making sure there are no concurrent updates.\n+ */\n+static void do_hpcc_test_single_thread(struct kunit *test, int _cpu0, int _cpu1, enum up_test_inc_type type)\n+{\n+\tunsigned long batch_size_order = 5;\n+\tint cpu0 = _cpu0;\n+\tint cpu1 = _cpu1;\n+\tint i;\n+\n+\tinit_counters(test, 1UL \u003c\u003c batch_size_order);\n+\tinit_kthreads();\n+\tfor (i = 0; i \u003c 10000; i++) {\n+\t\tlong increment;\n+\n+\t\tswitch (type) {\n+\t\tcase INC_ONE:\n+\t\t\tincrement = 1;\n+\t\t\tbreak;\n+\t\tcase INC_MINUS_ONE:\n+\t\t\tincrement = -1;\n+\t\t\tbreak;\n+\t\tcase INC_RANDOM:\n+\t\t\tincrement = (long) get_random_long() % 50000;\n+\t\t\tbreak;\n+\t\t}\n+\t\tif (_cpu0 \u003c 0)\n+\t\t\tcpu0 = cpumask_any_distribute(cpu_online_mask);\n+\t\tif (_cpu1 \u003c 0)\n+\t\t\tcpu1 = cpumask_any_distribute(cpu_online_mask);\n+\t\ttest_run_on_specific_cpu(test, cpu0, 0, 1, increment);\n+\t\ttest_sync_kthreads();\n+\t\ttest_run_on_specific_cpu(test, cpu1, 1, 1, increment);\n+\t\ttest_sync_kthreads();\n+\t\tcheck_counters(test);\n+\t}\n+\tfini_kthreads();\n+\tfini_counters();\n+}\n+\n+static void hpcc_test_single_thread_first(struct kunit *test)\n+{\n+\tint cpu = cpumask_first(cpu_online_mask);\n+\n+\tdo_hpcc_test_single_thread(test, cpu, cpu, INC_ONE);\n+\tdo_hpcc_test_single_thread(test, cpu, cpu, INC_MINUS_ONE);\n+\tdo_hpcc_test_single_thread(test, cpu, cpu, INC_RANDOM);\n+}\n+\n+static void hpcc_test_single_thread_first_random(struct kunit *test)\n+{\n+\tint cpu = cpumask_first(cpu_online_mask);\n+\n+\tdo_hpcc_test_single_thread(test, cpu, -1, INC_ONE);\n+\tdo_hpcc_test_single_thread(test, cpu, -1, INC_MINUS_ONE);\n+\tdo_hpcc_test_single_thread(test, cpu, -1, INC_RANDOM);\n+}\n+\n+static void hpcc_test_single_thread_random(struct kunit *test)\n+{\n+\tdo_hpcc_test_single_thread(test, -1, -1, INC_ONE);\n+\tdo_hpcc_test_single_thread(test, -1, -1, INC_MINUS_ONE);\n+\tdo_hpcc_test_single_thread(test, -1, -1, INC_RANDOM);\n+}\n+\n+/* Multi-threaded SMP tests. */\n+\n+static void do_hpcc_multi_thread_increment_each_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)\n+{\n+\tint cpu;\n+\n+\tinit_counters(test, batch_size);\n+\tinit_kthreads();\n+\tfor_each_online_cpu(cpu) {\n+\t\ttest_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);\n+\t\ttest_run_on_specific_cpu(test, cpu, 1, nr_inc, increment);\n+\t}\n+\tfini_kthreads();\n+\tcheck_counters(test);\n+\tfini_counters();\n+}\n+\n+static void do_hpcc_multi_thread_increment_even_cpus(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)\n+{\n+\tint cpu;\n+\n+\tinit_counters(test, batch_size);\n+\tinit_kthreads();\n+\tfor_each_online_cpu(cpu) {\n+\t\ttest_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);\n+\t\ttest_run_on_specific_cpu(test, cpu \u0026 ~1, 1, nr_inc, increment); /* even cpus. */\n+\t}\n+\tfini_kthreads();\n+\tcheck_counters(test);\n+\tfini_counters();\n+}\n+\n+static void do_hpcc_multi_thread_increment_single_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)\n+{\n+\tint cpu;\n+\n+\tinit_counters(test, batch_size);\n+\tinit_kthreads();\n+\tfor_each_online_cpu(cpu) {\n+\t\ttest_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);\n+\t\ttest_run_on_specific_cpu(test, cpumask_first(cpu_online_mask), 1, nr_inc, increment);\n+\t}\n+\tfini_kthreads();\n+\tcheck_counters(test);\n+\tfini_counters();\n+}\n+\n+static void do_hpcc_multi_thread_increment_random_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)\n+{\n+\tint cpu;\n+\n+\tinit_counters(test, batch_size);\n+\tinit_kthreads();\n+\tfor_each_online_cpu(cpu) {\n+\t\ttest_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);\n+\t\ttest_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);\n+\t}\n+\tfini_kthreads();\n+\tcheck_counters(test);\n+\tfini_counters();\n+}\n+\n+static void hpcc_test_multi_thread_batch_increment(struct kunit *test)\n+{\n+\tunsigned long batch_size_order;\n+\n+\tfor (batch_size_order = 2; batch_size_order \u003c 10; batch_size_order++) {\n+\t\tunsigned int nr_inc;\n+\n+\t\tfor (nr_inc = 1; nr_inc \u003c 1024; nr_inc *= 2) {\n+\t\t\tlong increment;\n+\n+\t\t\tfor (increment = 1; increment \u003c 100000; increment *= 10) {\n+\t\t\t\tdo_hpcc_multi_thread_increment_each_cpu(test, 1UL \u003c\u003c batch_size_order, nr_inc, increment);\n+\t\t\t\tdo_hpcc_multi_thread_increment_even_cpus(test, 1UL \u003c\u003c batch_size_order, nr_inc, increment);\n+\t\t\t\tdo_hpcc_multi_thread_increment_single_cpu(test, 1UL \u003c\u003c batch_size_order, nr_inc, increment);\n+\t\t\t\tdo_hpcc_multi_thread_increment_random_cpu(test, 1UL \u003c\u003c batch_size_order, nr_inc, increment);\n+\t\t\t}\n+\t\t}\n+\t}\n+}\n+\n+static void hpcc_test_multi_thread_random_walk(struct kunit *test)\n+{\n+\tunsigned long batch_size_order = 5;\n+\tint loop;\n+\n+\tfor (loop = 0; loop \u003c 100; loop++) {\n+\t\tint i;\n+\n+\t\tinit_counters(test, 1UL \u003c\u003c batch_size_order);\n+\t\tinit_kthreads();\n+\t\tfor (i = 0; i \u003c 1000; i++) {\n+\t\t\tlong increment = (long) get_random_long() % 512;\n+\t\t\tunsigned int nr_inc = ((unsigned long) get_random_long()) % 1024;\n+\n+\t\t\ttest_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 0, nr_inc, increment);\n+\t\t\ttest_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);\n+\t\t}\n+\t\tfini_kthreads();\n+\t\tcheck_counters(test);\n+\t\tfini_counters();\n+\t}\n+}\n+\n+static void hpcc_test_init_one(struct kunit *test)\n+{\n+\tstruct percpu_counter_tree pct;\n+\tstruct percpu_counter_tree_level_item *counter_items;\n+\tint ret;\n+\n+\tcounter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);\n+\tKUNIT_EXPECT_PTR_NE(test, counter_items, NULL);\n+\tret = percpu_counter_tree_init(\u0026pct, counter_items, 32, GFP_KERNEL);\n+\tKUNIT_EXPECT_EQ(test, ret, 0);\n+\n+\tpercpu_counter_tree_destroy(\u0026pct);\n+\tkfree(counter_items);\n+}\n+\n+static void hpcc_test_set(struct kunit *test)\n+{\n+\tstatic long values[] = {\n+\t\t5, 100, 127, 128, 255, 256, 4095, 4096, 500000, 0,\n+\t\t-5, -100, -127, -128, -255, -256, -4095, -4096, -500000,\n+\t};\n+\tstruct percpu_counter_tree pct;\n+\tstruct percpu_counter_tree_level_item *counter_items;\n+\tint i, ret;\n+\n+\tcounter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);\n+\tKUNIT_EXPECT_PTR_NE(test, counter_items, NULL);\n+\tret = percpu_counter_tree_init(\u0026pct, counter_items, 32, GFP_KERNEL);\n+\tKUNIT_EXPECT_EQ(test, ret, 0);\n+\n+\tfor (i = 0; i \u003c ARRAY_SIZE(values); i++) {\n+\t\tlong v = values[i];\n+\n+\t\tpercpu_counter_tree_set(\u0026pct, v);\n+\t\tKUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(\u0026pct), v);\n+\t\tKUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(\u0026pct, v));\n+\n+\t\tpercpu_counter_tree_add(\u0026pct, v);\n+\t\tKUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(\u0026pct), 2 * v);\n+\t\tKUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(\u0026pct, 2 * v));\n+\n+\t\tpercpu_counter_tree_add(\u0026pct, -2 * v);\n+\t\tKUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(\u0026pct), 0);\n+\t\tKUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(\u0026pct, 0));\n+\t}\n+\n+\tpercpu_counter_tree_destroy(\u0026pct);\n+\tkfree(counter_items);\n+}\n+\n+static struct kunit_case hpcc_test_cases[] = {\n+\tKUNIT_CASE(hpcc_print_info),\n+\tKUNIT_CASE(hpcc_test_single_thread_first),\n+\tKUNIT_CASE(hpcc_test_single_thread_first_random),\n+\tKUNIT_CASE(hpcc_test_single_thread_random),\n+\tKUNIT_CASE(hpcc_test_multi_thread_batch_increment),\n+\tKUNIT_CASE(hpcc_test_multi_thread_random_walk),\n+\tKUNIT_CASE(hpcc_test_init_one),\n+\tKUNIT_CASE(hpcc_test_set),\n+\t{}\n+};\n+\n+static struct kunit_suite hpcc_test_suite = {\n+\t.name = \"percpu_counter_tree\",\n+\t.test_cases = hpcc_test_cases,\n+};\n+\n+kunit_test_suite(hpcc_test_suite);\n+\n+MODULE_DESCRIPTION(\"Test cases for hierarchical per-CPU counters\");\n+MODULE_LICENSE(\"Dual MIT/GPL\");\n"
}

2/1 2026/09/02 08:37 agent patch-evaluator
0m Model:
core

Args:
null

Results:
{
  "EnableConfigs": [
    "SMP"
  ],
  "FocusSymbols": [
    "percpu_counter_tree_init_many",
    "percpu_counter_tree_destroy_many",
    "percpu_counter_tree_precise_sum",
    "percpu_counter_tree_approximate_compare",
    "percpu_counter_tree_approximate_compare_value",
    "percpu_counter_tree_precise_compare",
    "percpu_counter_tree_precise_compare_value",
    "percpu_counter_tree_set"
  ],
  "Reasoning": "The patch introduces Hierarchical Per-CPU Counters (HPCC) for scalable approximate/precise counter aggregation and integrates them into core memory management (struct mm_struct RSS accounting). This introduces complex concurrency, carry propagation, and comparison logic in reachable core kernel paths on SMP systems.",
  "WorthFuzzing": true
}

Instruction:
You are an expert Linux kernel maintainer.
Your job is to review a provided patch series and determine
if it makes functional changes to the kernel that should be fuzzed.

IMPORTANT: The changes have ALREADY been applied and committed as the HEAD commit in
your workspace. Do NOT rely on your internal knowledge of the kernel. You must actively
use your code access tools to examine the actual source code and confirm any assumptions.

Return WorthFuzzing=false if the patch only contains:
- Modifications to Documentation/, Kconfig files, or code comments.
- Purely decorative changes, such as logging (e.g., pr_err, printk) or tracepoints.
- Changes to numeric constants or macros that do not functionally alter execution flow.
- Code paths that are impossible to reach in virtualized environments like GCE or QEMU,
  even when utilizing software-emulated hardware (e.g., usb gadget, mac80211_hwsim).
- Code in vendor-specific PCIe switch, SmartNIC, or GPU drivers (e.g., mlxsw, pds_core, qed,
  ionic, amdgpu) that require physical PCIe hardware cards not emulated in standard QEMU.
- Driver .remove, .shutdown, or pci_unregister_driver teardown callbacks (e.g., igb_remove)
  that are executed only during PCI hot-unplug or sysfs driver unbind operations.

If it modifies reachable core kernel logic, drivers, or architectures, use your code search
tools to verify the code can be executed, then return WorthFuzzing=true.

When returning WorthFuzzing=true, you MUST ALSO:
1. Extract any specific kernel functions that should be heavily fuzzed into FocusSymbols.
   Avoid listing generic hot-path functions to prevent skewed test distributions.
   Prefer non-static, non-inlined API entrypoint functions over internal static helper functions
   (which are inlined by the compiler and do not have distinct symbol addresses).
2. Identify any specific CONFIG_ options required to properly test this new/modified feature.
   Go and look into the Kconfig files and check for ifdefs around the code, do not make assumptions.
   Also check "depends on" lines in Kconfig to include any non-standard parent subsystem configs
   needed for Kbuild to compile the code statically into vmlinux. List them in the EnableConfigs
   output array, and DO NOT add a 'CONFIG_' prefix (e.g., return "NET_IPV4" instead of "CONFIG_NET_IPV4").
Prefer calling several tools at the same time to save round-trips.


Use set-results tool to provide results of the analysis.
It must be called exactly once before the final reply.
Ignore results of this tool.

Prompt:
For your convenience, here is the diff of the changes:
commit 016f492f9418f19378197191c764e46711442f39
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Sep 2 08:37:00 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/core-api/percpu-counter-tree.rst b/Documentation/core-api/percpu-counter-tree.rst
new file mode 100644
index 0000000000000..196da056e7b42
--- /dev/null
+++ b/Documentation/core-api/percpu-counter-tree.rst
@@ -0,0 +1,75 @@
+========================================
+The Hierarchical Per-CPU Counters (HPCC)
+========================================
+
+:Author: Mathieu Desnoyers
+
+Introduction
+============
+
+Counters come in many varieties, each with their own trade offs:
+
+ * A global atomic counter provides a fast read access to the current
+   sum, at the expense of cache-line bouncing on updates. This leads to
+   poor performance of frequent updates from various cores on large SMP
+   systems.
+
+ * A per-cpu split counter provides fast updates to per-cpu counters,
+   at the expense of a slower aggregation (sum). The sum operation needs
+   to iterate over all per-cpu counters to calculate the current total.
+
+The hierarchical per-cpu counters attempt to provide the best of both
+worlds (fast updates, and fast sum) by relaxing requirements on the sum
+accuracy. It allows quickly querying an approximated sum value, along
+with the possible min/max ranges of the associated precise sum. The
+exact precise sum can still be calculated with an iteration on all
+per-cpu counter, but the availability of an approximated sum value with
+possible precise sum min/max ranges allows eliminating candidates which
+are certainly outside of a known target range without the overhead of
+precise sums.
+
+Overview
+========
+
+The herarchical per-cpu counters are organized as a tree with the tree
+root at the bottom (last level) and the first level of the tree
+consisting of per-cpu counters.
+
+The intermediate tree levels contain carry propagation counters. When
+reaching a threshold (batch size), the carry is propagated down the
+tree.
+
+This allows reading an approximated value at the root, which has a
+bounded accuracy (minimum/maximum possible precise sum range) determined
+by the tree topology.
+
+Use Cases
+=========
+
+Use cases HPCC is meant to handle invove tracking resources which are
+used across many CPUs to quickly sum as feedback for decision making to
+apply throttling, quota limits, sort tasks, and perform memory or task
+migration decisions. When considering approximated sums within the
+accuracy range of the decision threshold, the user can either:
+
+ * Be conservative and fast: Consider that the sum has reached the
+   limit as soon as the given limit is within the approximation range.
+
+ * Be aggressive and fast: Consider that the sum is over the
+   limit only when the approximation range is over the given limit.
+
+ * Be precise and slow: Do a precise comparison with the limit, which
+   requires a precise sum when the limit is within the approximated
+   range.
+
+One use-case for these hierarchical counters is to implement a two-pass
+algorithm to speed up sorting picking a maximum/minimunm sum value from
+a set. A first pass compares the approximated values, and then a second
+pass only needs the precise sum for counter trees which are within the
+possible precise sum range of the counter tree chosen by the first pass.
+
+Functions and structures
+========================
+
+.. kernel-doc:: include/linux/percpu_counter_tree.h
+.. kernel-doc:: lib/percpu_counter_tree.c
diff --git a/include/linux/mm.h b/include/linux/mm.h
index dd09c438fa23e..ffbcd18c4ecb3 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -3447,38 +3447,48 @@ static inline bool get_user_page_fast_only(unsigned long addr,
 {
 	return get_user_pages_fast_only(addr, 1, gup_flags, pagep) == 1;
 }
+
+static inline struct percpu_counter_tree_level_item *get_rss_stat_items(struct mm_struct *mm)
+{
+	unsigned long ptr = (unsigned long)mm;
+
+	ptr += offsetof(struct mm_struct, flexible_array);
+	ptr += get_rss_stat_items_offset();
+	return (struct percpu_counter_tree_level_item *)ptr;
+}
+
 /*
  * per-process(per-mm_struct) statistics.
  */
 static inline unsigned long get_mm_counter(struct mm_struct *mm, int member)
 {
-	return percpu_counter_read_positive(&mm->rss_stat[member]);
+	return percpu_counter_tree_approximate_sum_positive(&mm->rss_stat[member]);
 }
 
 static inline unsigned long get_mm_counter_sum(struct mm_struct *mm, int member)
 {
-	return percpu_counter_sum_positive(&mm->rss_stat[member]);
+	return percpu_counter_tree_precise_sum_positive(&mm->rss_stat[member]);
 }
 
 void mm_trace_rss_stat(struct mm_struct *mm, int member);
 
 static inline void add_mm_counter(struct mm_struct *mm, int member, long value)
 {
-	percpu_counter_add(&mm->rss_stat[member], value);
+	percpu_counter_tree_add(&mm->rss_stat[member], value);
 
 	mm_trace_rss_stat(mm, member);
 }
 
 static inline void inc_mm_counter(struct mm_struct *mm, int member)
 {
-	percpu_counter_inc(&mm->rss_stat[member]);
+	percpu_counter_tree_add(&mm->rss_stat[member], 1);
 
 	mm_trace_rss_stat(mm, member);
 }
 
 static inline void dec_mm_counter(struct mm_struct *mm, int member)
 {
-	percpu_counter_dec(&mm->rss_stat[member]);
+	percpu_counter_tree_add(&mm->rss_stat[member], -1);
 
 	mm_trace_rss_stat(mm, member);
 }
diff --git a/include/linux/mm_types.h b/include/linux/mm_types.h
index 6d815f6440c94..b26160b85f93a 100644
--- a/include/linux/mm_types.h
+++ b/include/linux/mm_types.h
@@ -18,7 +18,7 @@
 #include <linux/page-flags-layout.h>
 #include <linux/workqueue.h>
 #include <linux/seqlock.h>
-#include <linux/percpu_counter.h>
+#include <linux/percpu_counter_tree.h>
 #include <linux/types.h>
 #include <linux/futex_types.h>
 #include <linux/rseq_types.h>
@@ -1170,6 +1170,19 @@ typedef struct {
 	DECLARE_BITMAP(__mm_flags, NUM_MM_FLAG_BITS);
 } __private mm_flags_t;
 
+/*
+ * The alignment of the mm_struct flexible array is based on the largest
+ * alignment of its content:
+ * __alignof__(struct percpu_counter_tree_level_item) provides a
+ * cacheline aligned alignment on SMP systems, else alignment on
+ * unsigned long on UP systems.
+ */
+#ifdef CONFIG_SMP
+# define __mm_struct_flexible_array_aligned	__aligned(__alignof__(struct percpu_counter_tree_level_item))
+#else
+# define __mm_struct_flexible_array_aligned	__aligned(__alignof__(unsigned long))
+#endif
+
 struct kioctx_table;
 struct iommu_mm_data;
 struct mm_struct {
@@ -1312,7 +1325,7 @@ struct mm_struct {
 		unsigned long saved_e_flags;
 #endif
 
-		struct percpu_counter rss_stat[NR_MM_COUNTERS];
+		struct percpu_counter_tree rss_stat[NR_MM_COUNTERS];
 
 		struct linux_binfmt *binfmt;
 
@@ -1422,10 +1435,14 @@ struct mm_struct {
 	} __randomize_layout;
 
 	/*
-	 * The mm_cpumask needs to be at the end of mm_struct, because it
-	 * is dynamically sized based on nr_cpu_ids.
+	 * The mm_cpumask, mm_cid masks, and rss hierarchical counter
+	 * items need to be at the end of mm_struct, because they are
+	 * dynamically sized based on nr_cpu_ids.
+	 * The HPCC counter tree items are placed last and aligned
+	 * with PERCPU_COUNTER_TREE_ITEMS_ALIGN to satisfy their
+	 * cacheline alignment requirement.
 	 */
-	char flexible_array[] __aligned(__alignof__(unsigned long));
+	char flexible_array[] __mm_struct_flexible_array_aligned;
 };
 
 /* Copy value to the first system word of mm flags, non-atomically. */
@@ -1462,18 +1479,12 @@ static inline void __mm_flags_set_mask_bits_word(struct mm_struct *mm,
 			 MT_FLAGS_USE_RCU)
 extern struct mm_struct init_mm;
 
-#define MM_STRUCT_FLEXIBLE_ARRAY_INIT				\
-{								\
-	[0 ... sizeof(cpumask_t) + MM_CID_STATIC_SIZE - 1] = 0	\
-}
-
-/* Pointer magic because the dynamic array size confuses some compilers. */
-static inline void mm_init_cpumask(struct mm_struct *mm)
-{
-	unsigned long cpu_bitmap = (unsigned long)mm;
-
-	cpu_bitmap += offsetof(struct mm_struct, flexible_array);
-	cpumask_clear((struct cpumask *)cpu_bitmap);
+#define MM_STRUCT_FLEXIBLE_ARRAY_INIT						\
+{										\
+	[0 ... PERCPU_COUNTER_TREE_ITEMS_ALIGN(					\
+			sizeof(cpumask_t) + MM_CID_STATIC_SIZE)			\
+	       + (PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE * NR_MM_COUNTERS)	\
+	       - 1] = 0								\
 }
 
 /* Future-safe accessor for struct mm_struct's cpu_vm_mask. */
@@ -1482,6 +1493,11 @@ static inline cpumask_t *mm_cpumask(struct mm_struct *mm)
 	return (struct cpumask *)&mm->flexible_array;
 }
 
+static inline void mm_init_cpumask(struct mm_struct *mm)
+{
+	cpumask_clear((struct cpumask *)mm_cpumask(mm));
+}
+
 #ifdef CONFIG_LRU_GEN
 
 struct lru_gen_mm_list {
@@ -1653,6 +1669,21 @@ static inline void mm_destroy_sched(struct mm_struct *mm) { }
 
 #endif /* CONFIG_SCHED_CACHE */
 
+static inline size_t get_rss_stat_items_size(void)
+{
+	return percpu_counter_tree_items_size() * NR_MM_COUNTERS;
+}
+
+/*
+ * Return the offset of the RSS stat HPCC items within the mm_struct
+ * flexible array. The items are placed after the cpumask and mm_cid,
+ * aligned to the cacheline boundary required by the tree level items.
+ */
+static inline size_t get_rss_stat_items_offset(void)
+{
+	return PERCPU_COUNTER_TREE_ITEMS_ALIGN(cpumask_size() + mm_cid_size());
+}
+
 struct mmu_gather;
 extern void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm);
 extern void tlb_gather_mmu_fullmm(struct mmu_gather *tlb, struct mm_struct *mm);
diff --git a/include/linux/percpu_counter_tree.h b/include/linux/percpu_counter_tree.h
new file mode 100644
index 0000000000000..4095acdc879bf
--- /dev/null
+++ b/include/linux/percpu_counter_tree.h
@@ -0,0 +1,387 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+/* SPDX-FileCopyrightText: 2025 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> */
+
+#ifndef _PERCPU_COUNTER_TREE_H
+#define _PERCPU_COUNTER_TREE_H
+
+#include <linux/preempt.h>
+#include <linux/atomic.h>
+#include <linux/percpu.h>
+
+#ifdef CONFIG_SMP
+
+#if NR_CPUS == (1U << 0)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	0
+#elif NR_CPUS <= (1U << 1)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	1
+#elif NR_CPUS <= (1U << 2)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	3
+#elif NR_CPUS <= (1U << 3)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	7
+#elif NR_CPUS <= (1U << 4)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	7
+#elif NR_CPUS <= (1U << 5)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	11
+#elif NR_CPUS <= (1U << 6)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	21
+#elif NR_CPUS <= (1U << 7)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	21
+#elif NR_CPUS <= (1U << 8)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	37
+#elif NR_CPUS <= (1U << 9)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	73
+#elif NR_CPUS <= (1U << 10)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	149
+#elif NR_CPUS <= (1U << 11)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	293
+#elif NR_CPUS <= (1U << 12)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	585
+#elif NR_CPUS <= (1U << 13)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	1173
+#elif NR_CPUS <= (1U << 14)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	2341
+#elif NR_CPUS <= (1U << 15)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	4681
+#elif NR_CPUS <= (1U << 16)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	4681
+#elif NR_CPUS <= (1U << 17)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	8777
+#elif NR_CPUS <= (1U << 18)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	17481
+#elif NR_CPUS <= (1U << 19)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	34953
+#elif NR_CPUS <= (1U << 20)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	69905
+#else
+# error "Unsupported number of CPUs."
+#endif
+
+struct percpu_counter_tree_level_item {
+	atomic_long_t count;		/*
+					 * Count the number of carry for this tree item.
+					 * The carry counter is kept at the order of the
+					 * carry accounted for at this tree level.
+					 */
+} ____cacheline_aligned_in_smp;
+
+#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE	\
+	(PERCPU_COUNTER_TREE_STATIC_NR_ITEMS * sizeof(struct percpu_counter_tree_level_item))
+#define PERCPU_COUNTER_TREE_ITEMS_ALIGN(offset)	\
+	ALIGN((offset), __alignof__(struct percpu_counter_tree_level_item))
+
+struct percpu_counter_tree {
+	/* Fast-path fields. */
+	unsigned long __percpu *level0;	/* Pointer to per-CPU split counters (tree level 0). */
+	unsigned long level0_bit_mask;	/* Bit mask to apply to detect carry propagation from tree level 0. */
+	union {
+		unsigned long *i;	/* Approximate sum for single-CPU topology. */
+		atomic_long_t *a;	/* Approximate sum for SMP topology.  */
+	} approx_sum;
+	long bias;			/* Bias to apply to counter precise and approximate values. */
+
+	/* Slow-path fields. */
+	struct percpu_counter_tree_level_item *items;	/* Array of tree items for levels 1 to N. */
+	unsigned long batch_size;	/*
+					 * The batch size is the increment step at level 0 which
+					 * triggers a carry propagation. The batch size is required
+					 * to be greater than 1, and a power of 2.
+					 */
+	/*
+	 * The tree approximate sum is guaranteed to be within this accuracy range:
+	 * (precise_sum - approx_accuracy_range.under) <= approx_sum <= (precise_sum + approx_accuracy_range.over).
+	 * This accuracy is derived from the hardware topology and the tree batch_size.
+	 * The "under" accuracy is larger than the "over" accuracy because the negative range of a
+	 * two's complement signed integer is one unit larger than the positive range. This delta
+	 * is summed for each tree item, which leads to a significantly larger "under" accuracy range
+	 * compared to the "over" accuracy range.
+	 */
+	struct {
+		unsigned long under;
+		unsigned long over;
+	} approx_accuracy_range;
+};
+
+extern size_t __percpu_counter_tree_items_size __ro_after_init;
+
+/*
+ * percpu_counter_tree_items_size - Query the size required for counter tree items.
+ *
+ * Query the size of the memory area required to hold the counter tree
+ * items. This depends on the hardware topology and is invariant after
+ * boot.
+ *
+ * Return: Size required to hold tree items.
+ */
+static inline
+size_t percpu_counter_tree_items_size(void)
+{
+	WARN_ON_ONCE(__percpu_counter_tree_items_size == SIZE_MAX);
+	return __percpu_counter_tree_items_size;
+}
+
+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,
+				  unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags);
+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,
+			     unsigned long batch_size, gfp_t gfp_flags);
+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counter, unsigned int nr_counters);
+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter);
+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc);
+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter);
+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b);
+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v);
+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b);
+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v);
+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v);
+int percpu_counter_tree_subsystem_init(void);
+
+/**
+ * percpu_counter_tree_approximate_sum() - Return approximate counter sum.
+ * @counter: The counter to sum.
+ *
+ * Querying the approximate sum is fast, but it is only accurate within
+ * the bounds delimited by percpu_counter_tree_approximate_accuracy_range().
+ * This is meant to be used when speed is preferred over accuracy.
+ *
+ * Return: The current approximate counter sum.
+ */
+static inline
+long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)
+{
+	unsigned long v;
+
+	if (!counter->level0_bit_mask)
+		v = READ_ONCE(*counter->approx_sum.i);
+	else
+		v = atomic_long_read(counter->approx_sum.a);
+	return (long) (v + (unsigned long)READ_ONCE(counter->bias));
+}
+
+/**
+ * percpu_counter_tree_approximate_accuracy_range - Query the accuracy range for a counter tree.
+ * @counter: Counter to query.
+ * @under: Pointer to a variable to be incremented of the approximation
+ *         accuracy range below the precise sum.
+ * @over: Pointer to a variable to be incremented of the approximation
+ *        accuracy range above the precise sum.
+ *
+ * Query the accuracy range limits for the counter.
+ * Because of two's complement binary representation, the "under" range is typically
+ * slightly larger than the "over" range.
+ * Those values are derived from the hardware topology and the counter tree batch size.
+ * They are invariant for a given counter tree.
+ * Using this function should not be typically required, see the following functions instead:
+ * * percpu_counter_tree_approximate_compare(),
+ * * percpu_counter_tree_approximate_compare_value(),
+ * * percpu_counter_tree_precise_compare(),
+ * * percpu_counter_tree_precise_compare_value().
+ */
+static inline
+void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *counter,
+						    unsigned long *under, unsigned long *over)
+{
+	*under += counter->approx_accuracy_range.under;
+	*over += counter->approx_accuracy_range.over;
+}
+
+#else	/* !CONFIG_SMP */
+
+#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE	0
+#define PERCPU_COUNTER_TREE_ITEMS_ALIGN(offset)	(offset)
+
+struct percpu_counter_tree_level_item;
+
+struct percpu_counter_tree {
+	atomic_long_t count;
+};
+
+static inline
+size_t percpu_counter_tree_items_size(void)
+{
+	return 0;
+}
+
+static inline
+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,
+				  unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags)
+{
+	for (unsigned int i = 0; i < nr_counters; i++)
+		atomic_long_set(&counters[i].count, 0);
+	return 0;
+}
+
+static inline
+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,
+			     unsigned long batch_size, gfp_t gfp_flags)
+{
+	return percpu_counter_tree_init_many(counter, items, 1, batch_size, gfp_flags);
+}
+
+static inline
+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counter, unsigned int nr_counters)
+{
+}
+
+static inline
+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter)
+{
+}
+
+static inline
+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter)
+{
+	return atomic_long_read(&counter->count);
+}
+
+static inline
+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+	long count_a = percpu_counter_tree_precise_sum(a),
+	     count_b = percpu_counter_tree_precise_sum(b);
+
+	if (count_a == count_b)
+		return 0;
+	if (count_a < count_b)
+		return -1;
+	return 1;
+}
+
+static inline
+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v)
+{
+	long count = percpu_counter_tree_precise_sum(counter);
+
+	if (count == v)
+		return 0;
+	if (count < v)
+		return -1;
+	return 1;
+}
+
+static inline
+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+	return percpu_counter_tree_precise_compare(a, b);
+}
+
+static inline
+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v)
+{
+	return percpu_counter_tree_precise_compare_value(counter, v);
+}
+
+static inline
+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v)
+{
+	atomic_long_set(&counter->count, v);
+}
+
+static inline
+void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *counter,
+						    unsigned long *under, unsigned long *over)
+{
+}
+
+static inline
+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc)
+{
+	atomic_long_add(inc, &counter->count);
+}
+
+static inline
+long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)
+{
+	return percpu_counter_tree_precise_sum(counter);
+}
+
+static inline
+int percpu_counter_tree_subsystem_init(void)
+{
+	return 0;
+}
+
+#endif	/* CONFIG_SMP */
+
+/**
+ * percpu_counter_tree_approximate_sum_positive() - Return a positive approximate counter sum.
+ * @counter: The counter to sum.
+ *
+ * Return an approximate counter sum which is guaranteed to be greater
+ * or equal to 0.
+ *
+ * Return: The current positive approximate counter sum.
+ */
+static inline
+long percpu_counter_tree_approximate_sum_positive(struct percpu_counter_tree *counter)
+{
+	long v = percpu_counter_tree_approximate_sum(counter);
+	return v > 0 ? v : 0;
+}
+
+/**
+ * percpu_counter_tree_precise_sum_positive() - Return a positive precise counter sum.
+ * @counter: The counter to sum.
+ *
+ * Return a precise counter sum which is guaranteed to be greater
+ * or equal to 0.
+ *
+ * Return: The current positive precise counter sum.
+ */
+static inline
+long percpu_counter_tree_precise_sum_positive(struct percpu_counter_tree *counter)
+{
+	long v = percpu_counter_tree_precise_sum(counter);
+	return v > 0 ? v : 0;
+}
+
+/**
+ * percpu_counter_tree_approximate_min_max_range() - Return the approximation min and max precise values.
+ * @approx_sum: Approximated sum.
+ * @under: Tree accuracy range (under).
+ * @over: Tree accuracy range (over).
+ * @precise_min: Minimum possible value for precise sum (output).
+ * @precise_max: Maximum possible value for precise sum (output).
+ *
+ * Calculate the minimum and maximum precise values for a given
+ * approximation and (under, over) accuracy range.
+ *
+ * The range of the approximation as a function of the precise sum is expressed as:
+ *
+ *   approx_sum >= precise_sum - approx_accuracy_range.under
+ *   approx_sum <= precise_sum + approx_accuracy_range.over
+ *
+ * Therefore, the range of the precise sum as a function of the approximation is expressed as:
+ *
+ *   precise_sum <= approx_sum + approx_accuracy_range.under
+ *   precise_sum >= approx_sum - approx_accuracy_range.over
+ */
+static inline
+void percpu_counter_tree_approximate_min_max_range(long approx_sum, unsigned long under, unsigned long over,
+						   long *precise_min, long *precise_max)
+{
+	*precise_min = approx_sum - over;
+	*precise_max = approx_sum + under;
+}
+
+/**
+ * percpu_counter_tree_approximate_min_max() - Return the tree approximation, min and max possible precise values.
+ * @counter: The counter to sum.
+ * @approx_sum: Approximate sum (output).
+ * @precise_min: Minimum possible value for precise sum (output).
+ * @precise_max: Maximum possible value for precise sum (output).
+ *
+ * Return the approximate sum, minimum and maximum precise values for
+ * a counter.
+ */
+static inline
+void percpu_counter_tree_approximate_min_max(struct percpu_counter_tree *counter,
+					     long *approx_sum, long *precise_min, long *precise_max)
+{
+	unsigned long under = 0, over = 0;
+	long v = percpu_counter_tree_approximate_sum(counter);
+
+	percpu_counter_tree_approximate_accuracy_range(counter, &under, &over);
+	percpu_counter_tree_approximate_min_max_range(v, under, over, precise_min, precise_max);
+	*approx_sum = v;
+}
+
+#endif  /* _PERCPU_COUNTER_TREE_H */
diff --git a/include/trace/events/kmem.h b/include/trace/events/kmem.h
index cd7920c81f85b..290ccb9fd25dd 100644
--- a/include/trace/events/kmem.h
+++ b/include/trace/events/kmem.h
@@ -448,7 +448,7 @@ TRACE_EVENT(rss_stat,
 		 */
 		__entry->curr = current->mm == mm && !(current->flags & PF_KTHREAD);
 		__entry->member = member;
-		__entry->size = (percpu_counter_sum_positive(&mm->rss_stat[member])
+		__entry->size = (percpu_counter_tree_approximate_sum_positive(&mm->rss_stat[member])
 							    << PAGE_SHIFT);
 	),
 
diff --git a/init/main.c b/init/main.c
index 2613d3f9b3ce9..845cb57e90965 100644
--- a/init/main.c
+++ b/init/main.c
@@ -108,6 +108,7 @@
 #include <linux/time_namespace.h>
 #include <linux/unaligned.h>
 #include <linux/vdso_datastore.h>
+#include <linux/percpu_counter_tree.h>
 #include <net/net_namespace.h>
 
 #include <asm/io.h>
@@ -1010,6 +1011,7 @@ void start_kernel(void)
 	setup_boot_config();
 	setup_command_line(command_line);
 	setup_nr_cpu_ids();
+	percpu_counter_tree_subsystem_init();
 	setup_per_cpu_areas();
 	smp_prepare_boot_cpu();	/* arch-specific boot-cpu hooks */
 	early_numa_node_init();
diff --git a/kernel/fork.c b/kernel/fork.c
index 416758c8a3d43..db398b6c52886 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -137,6 +137,11 @@
  */
 #define MAX_THREADS FUTEX_TID_MASK
 
+/*
+ * Batch size of rss stat approximation
+ */
+#define RSS_STAT_BATCH_SIZE	32
+
 /*
  * Protected counters by write_lock_irq(&tasklist_lock)
  */
@@ -633,14 +638,12 @@ static void check_mm(struct mm_struct *mm)
 			 "Please make sure 'struct resident_page_types[]' is updated as well");
 
 	for (i = 0; i < NR_MM_COUNTERS; i++) {
-		long x = percpu_counter_sum(&mm->rss_stat[i]);
-
-		if (unlikely(x)) {
+		if (unlikely(percpu_counter_tree_precise_compare_value(&mm->rss_stat[i], 0) != 0))
 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld Comm:%s Pid:%d\n",
-				 mm, resident_page_types[i], x,
+				 mm, resident_page_types[i],
+				 percpu_counter_tree_precise_sum(&mm->rss_stat[i]),
 				 current->comm,
 				 task_pid_nr(current));
-		}
 	}
 
 	if (mm_pgtables_bytes(mm))
@@ -738,7 +741,7 @@ void __mmdrop(struct mm_struct *mm)
 	check_mm(mm);
 	mm_pasid_drop(mm);
 	mm_destroy_cid(mm);
-	percpu_counter_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
+	percpu_counter_tree_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
 
 	free_mm(mm);
 }
@@ -1144,8 +1147,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
 	if (mm_alloc_sched(mm))
 		goto fail_sched;
 
-	if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT,
-				     NR_MM_COUNTERS))
+	if (percpu_counter_tree_init_many(mm->rss_stat, get_rss_stat_items(mm),
+					  NR_MM_COUNTERS, RSS_STAT_BATCH_SIZE,
+					  GFP_KERNEL_ACCOUNT))
 		goto fail_pcpu;
 
 	lru_gen_init_mm(mm);
@@ -3122,7 +3126,9 @@ void __init mm_cache_init(void)
 	 * dynamically sized based on the maximum CPU number this system
 	 * can have, taking hotplug into account (nr_cpu_ids).
 	 */
-	mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size();
+	mm_size = sizeof(struct mm_struct) +
+		PERCPU_COUNTER_TREE_ITEMS_ALIGN(cpumask_size() + mm_cid_size()) +
+		get_rss_stat_items_size();
 
 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
diff --git a/lib/Kconfig b/lib/Kconfig
index 4e6b34c3346d5..c0524258b2058 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -41,6 +41,18 @@ config PACKING_KUNIT_TEST
 
 	  When in doubt, say N.
 
+config PERCPU_COUNTER_TREE_KUNIT_TEST
+	tristate "KUnit tests for hierarchical per-cpu counters" if !KUNIT_ALL_TESTS
+	depends on KUNIT
+	default KUNIT_ALL_TESTS
+	help
+	  This builds Kunit tests for the hierarchical per-cpu counters.
+
+	  For more information on KUnit and unit tests in general,
+	  please refer to the KUnit documentation in Documentation/dev-tools/kunit/.
+
+	  When in doubt, say N.
+
 config BITREVERSE
 	tristate
 	select GENERIC_BITREVERSE if !HAVE_ARCH_BITREVERSE
diff --git a/lib/Makefile b/lib/Makefile
index dfab958327c5c..f1d0cb831630b 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -182,6 +182,7 @@ obj-$(CONFIG_TEXTSEARCH_KMP) += ts_kmp.o
 obj-$(CONFIG_TEXTSEARCH_BM) += ts_bm.o
 obj-$(CONFIG_TEXTSEARCH_FSM) += ts_fsm.o
 obj-$(CONFIG_SMP) += percpu_counter.o
+obj-$(CONFIG_SMP) += percpu_counter_tree.o
 obj-$(CONFIG_AUDIT_GENERIC) += audit.o
 obj-$(CONFIG_AUDIT_COMPAT_GENERIC) += compat_audit.o
 
diff --git a/lib/percpu_counter_tree.c b/lib/percpu_counter_tree.c
new file mode 100644
index 0000000000000..cfa5b04e05d7e
--- /dev/null
+++ b/lib/percpu_counter_tree.c
@@ -0,0 +1,694 @@
+// SPDX-License-Identifier: GPL-2.0+ OR MIT
+// SPDX-FileCopyrightText: 2025 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+
+/*
+ * Split Counters With Tree Approximation Propagation
+ *
+ * * Propagation diagram when reaching batch size thresholds (± batch size):
+ *
+ * Example diagram for 8 CPUs:
+ *
+ * log2(8) = 3 levels
+ *
+ * At each level, each pair propagates its values to the next level when
+ * reaching the batch size thresholds.
+ *
+ * Counters at levels 0, 1, 2 can be kept on a single byte ([-128 .. +127] range),
+ * although it may be relevant to keep them on "long" counters for
+ * simplicity. (complexity vs memory footprint tradeoff)
+ *
+ * Counter at level 3 can be kept on a "long" counter.
+ *
+ * Level 0:  0    1    2    3    4    5    6    7
+ *           |   /     |   /     |   /     |   /
+ *           |  /      |  /      |  /      |  /
+ *           | /       | /       | /       | /
+ * Level 1:  0         1         2         3
+ *           |       /           |       /
+ *           |    /              |    /
+ *           | /                 | /
+ * Level 2:  0                   1
+ *           |               /
+ *           |         /
+ *           |   /
+ * Level 3:  0
+ *
+ * * Approximation accuracy:
+ *
+ * BATCH(level N): Level N batch size.
+ *
+ * Example for BATCH(level 0) = 32.
+ *
+ * BATCH(level 0) =  32
+ * BATCH(level 1) =  64
+ * BATCH(level 2) = 128
+ * BATCH(level N) = BATCH(level 0) * 2^N
+ *
+ *            per-counter     global
+ *            accuracy        accuracy
+ * Level 0:   [ -32 ..  +31]  ±256  (8 * 32)
+ * Level 1:   [ -64 ..  +63]  ±256  (4 * 64)
+ * Level 2:   [-128 .. +127]  ±256  (2 * 128)
+ * Total:      ------         ±768  (log2(nr_cpu_ids) * BATCH(level 0) * nr_cpu_ids)
+ *
+ * Note that the global accuracy can be calculated more precisely
+ * by taking into account that the positive accuracy range is
+ * 31 rather than 32.
+ *
+ * -----
+ *
+ * Approximate Sum Carry Propagation
+ *
+ * Let's define a number of counter bits for each level, e.g.:
+ *
+ * log2(BATCH(level 0)) = log2(32) = 5
+ * Let's assume, for this example, a 32-bit architecture (sizeof(long) == 4).
+ *
+ *               nr_bit        value_mask                      range
+ * Level 0:      5 bits        v                             0 ..  +31
+ * Level 1:      1 bit        (v & ~((1UL << 5) - 1))        0 ..  +63
+ * Level 2:      1 bit        (v & ~((1UL << 6) - 1))        0 .. +127
+ * Level 3:     25 bits       (v & ~((1UL << 7) - 1))        0 .. 2^32-1
+ *
+ * Note: Use a "long" per-cpu counter at level 0 to allow precise sum.
+ *
+ * Note: Use cacheline aligned counters at levels above 0 to prevent false sharing.
+ *       If memory footprint is an issue, a specialized allocator could be used
+ *       to eliminate padding.
+ *
+ * Example with expanded values:
+ *
+ * counter_add(counter, inc):
+ *
+ *         if (!inc)
+ *                 return;
+ *
+ *         res = percpu_add_return(counter @ Level 0, inc);
+ *         orig = res - inc;
+ *         if (inc < 0) {
+ *                 inc = -(-inc & ~0b00011111);  // Clear used bits
+ *                 // xor bit 5: underflow
+ *                 if ((inc ^ orig ^ res) & 0b00100000)
+ *                         inc -= 0b00100000;
+ *         } else {
+ *                 inc &= ~0b00011111;           // Clear used bits
+ *                 // xor bit 5: overflow
+ *                 if ((inc ^ orig ^ res) & 0b00100000)
+ *                         inc += 0b00100000;
+ *         }
+ *         if (!inc)
+ *                 return;
+ *
+ *         res = atomic_long_add_return(counter @ Level 1, inc);
+ *         orig = res - inc;
+ *         if (inc < 0) {
+ *                 inc = -(-inc & ~0b00111111);  // Clear used bits
+ *                 // xor bit 6: underflow
+ *                 if ((inc ^ orig ^ res) & 0b01000000)
+ *                         inc -= 0b01000000;
+ *         } else {
+ *                 inc &= ~0b00111111;           // Clear used bits
+ *                 // xor bit 6: overflow
+ *                 if ((inc ^ orig ^ res) & 0b01000000)
+ *                         inc += 0b01000000;
+ *         }
+ *         if (!inc)
+ *                 return;
+ *
+ *         res = atomic_long_add_return(counter @ Level 2, inc);
+ *         orig = res - inc;
+ *         if (inc < 0) {
+ *                 inc = -(-inc & ~0b01111111);  // Clear used bits
+ *                 // xor bit 7: underflow
+ *                 if ((inc ^ orig ^ res) & 0b10000000)
+ *                         inc -= 0b10000000;
+ *         } else {
+ *                 inc &= ~0b01111111;           // Clear used bits
+ *                 // xor bit 7: overflow
+ *                 if ((inc ^ orig ^ res) & 0b10000000)
+ *                         inc += 0b10000000;
+ *         }
+ *         if (!inc)
+ *                 return;
+ *
+ *         atomic_long_add(counter @ Level 3, inc);
+ */
+
+#include <linux/percpu_counter_tree.h>
+#include <linux/cpumask.h>
+#include <linux/atomic.h>
+#include <linux/export.h>
+#include <linux/percpu.h>
+#include <linux/errno.h>
+#include <linux/slab.h>
+#include <linux/math.h>
+
+#define MAX_NR_LEVELS 5
+
+/*
+ * The counter configuration is selected at boot time based on the
+ * hardware topology.
+ */
+struct counter_config {
+	unsigned int nr_items;				/*
+							 * nr_items is the number of items in the tree for levels 1
+							 * up to and including the final level (approximate sum).
+							 * It excludes the level 0 per-CPU counters.
+							 */
+	unsigned char nr_levels;			/*
+							 * nr_levels is the number of hierarchical counter tree levels.
+							 * It excludes the final level (approximate sum).
+							 */
+	unsigned char n_arity_order[MAX_NR_LEVELS];	/*
+							 * n-arity of tree nodes for each level from
+							 * 0 to (nr_levels - 1).
+							 */
+};
+
+static const struct counter_config per_nr_cpu_order_config[] = {
+	[0] =	{ .nr_items = 0,	.nr_levels = 0,		.n_arity_order = { 0 } },
+	[1] =	{ .nr_items = 1,	.nr_levels = 1,		.n_arity_order = { 1 } },
+	[2] =	{ .nr_items = 3,	.nr_levels = 2,		.n_arity_order = { 1, 1 } },
+	[3] =	{ .nr_items = 7,	.nr_levels = 3,		.n_arity_order = { 1, 1, 1 } },
+	[4] =	{ .nr_items = 7,	.nr_levels = 3,		.n_arity_order = { 2, 1, 1 } },
+	[5] =	{ .nr_items = 11,	.nr_levels = 3,		.n_arity_order = { 2, 2, 1 } },
+	[6] =	{ .nr_items = 21,	.nr_levels = 3,		.n_arity_order = { 2, 2, 2 } },
+	[7] =	{ .nr_items = 21,	.nr_levels = 3,		.n_arity_order = { 3, 2, 2 } },
+	[8] =	{ .nr_items = 37,	.nr_levels = 3,		.n_arity_order = { 3, 3, 2 } },
+	[9] =	{ .nr_items = 73,	.nr_levels = 3,		.n_arity_order = { 3, 3, 3 } },
+	[10] =	{ .nr_items = 149,	.nr_levels = 4,		.n_arity_order = { 3, 3, 2, 2 } },
+	[11] =	{ .nr_items = 293,	.nr_levels = 4,		.n_arity_order = { 3, 3, 3, 2 } },
+	[12] =	{ .nr_items = 585,	.nr_levels = 4,		.n_arity_order = { 3, 3, 3, 3 } },
+	[13] =	{ .nr_items = 1173,	.nr_levels = 5,		.n_arity_order = { 3, 3, 3, 2, 2 } },
+	[14] =	{ .nr_items = 2341,	.nr_levels = 5,		.n_arity_order = { 3, 3, 3, 3, 2 } },
+	[15] =	{ .nr_items = 4681,	.nr_levels = 5,		.n_arity_order = { 3, 3, 3, 3, 3 } },
+	[16] =	{ .nr_items = 4681,	.nr_levels = 5,		.n_arity_order = { 4, 3, 3, 3, 3 } },
+	[17] =	{ .nr_items = 8777,	.nr_levels = 5,		.n_arity_order = { 4, 4, 3, 3, 3 } },
+	[18] =	{ .nr_items = 17481,	.nr_levels = 5,		.n_arity_order = { 4, 4, 4, 3, 3 } },
+	[19] =	{ .nr_items = 34953,	.nr_levels = 5,		.n_arity_order = { 4, 4, 4, 4, 3 } },
+	[20] =	{ .nr_items = 69905,	.nr_levels = 5,		.n_arity_order = { 4, 4, 4, 4, 4 } },
+};
+
+static const struct counter_config *counter_config;	/* Hierarchical counter configuration for the hardware topology. */
+static unsigned int nr_cpus_order;			/* Order of nr_cpu_ids. */
+static unsigned long accuracy_multiplier;		/* Calculate accuracy for a given batch size (multiplication factor). */
+
+static
+int __percpu_counter_tree_init(struct percpu_counter_tree *counter,
+			       unsigned long batch_size, gfp_t gfp_flags,
+			       unsigned long __percpu *level0,
+			       struct percpu_counter_tree_level_item *items)
+{
+	/* Batch size must be greater than 1, and a power of 2. */
+	if (WARN_ON(batch_size <= 1 || (batch_size & (batch_size - 1))))
+		return -EINVAL;
+	counter->batch_size = batch_size;
+	counter->bias = 0;
+	counter->level0 = level0;
+	counter->items = items;
+	if (!nr_cpus_order) {
+		counter->approx_sum.i = per_cpu_ptr(counter->level0, 0);
+		counter->level0_bit_mask = 0;
+	} else {
+		counter->approx_sum.a = &counter->items[counter_config->nr_items - 1].count;
+		counter->level0_bit_mask = 1UL << get_count_order(batch_size);
+	}
+	/*
+	 * Each tree item signed integer has a negative range which is
+	 * one unit greater than the positive range.
+	 */
+	counter->approx_accuracy_range.under = batch_size * accuracy_multiplier;
+	counter->approx_accuracy_range.over = (batch_size - 1) * accuracy_multiplier;
+	return 0;
+}
+
+/**
+ * percpu_counter_tree_init_many() - Initialize many per-CPU counter trees.
+ * @counters: An array of @nr_counters counters to initialize.
+ *	      Their memory is provided by the caller.
+ * @items: Pointer to memory area where to store tree items.
+ *	   This memory is provided by the caller.
+ *	   Its size needs to be at least @nr_counters * percpu_counter_tree_items_size().
+ * @nr_counters: The number of counter trees to initialize
+ * @batch_size: The batch size is the increment step at level 0 which triggers a
+ * 		carry propagation.
+ *		The batch size is required to be greater than 1, and a power of 2.
+ * @gfp_flags: gfp flags to pass to the per-CPU allocator.
+ *
+ * Initialize many per-CPU counter trees using a single per-CPU
+ * allocator invocation for @nr_counters counters.
+ *
+ * Return:
+ * * %0: Success
+ * * %-EINVAL:		- Invalid @batch_size argument
+ * * %-ENOMEM:		- Out of memory
+ */
+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,
+				  unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags)
+{
+	void __percpu *level0, *level0_iter;
+	size_t counter_size = sizeof(*counters->level0),
+	       items_size = percpu_counter_tree_items_size();
+	void *items_iter;
+	unsigned int i;
+	int ret;
+
+	memset(items, 0, items_size * nr_counters);
+	level0 = __alloc_percpu_gfp(nr_counters * counter_size,
+				    __alignof__(*counters->level0), gfp_flags);
+	if (!level0)
+		return -ENOMEM;
+	level0_iter = level0;
+	items_iter = items;
+	for (i = 0; i < nr_counters; i++) {
+		ret = __percpu_counter_tree_init(&counters[i], batch_size, gfp_flags, level0_iter, items_iter);
+		if (ret)
+			goto free_level0;
+		level0_iter += counter_size;
+		items_iter += items_size;
+	}
+	return 0;
+
+free_level0:
+	free_percpu(level0);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_init_many);
+
+/**
+ * percpu_counter_tree_init() - Initialize one per-CPU counter tree.
+ * @counter: Counter to initialize.
+ *	     Its memory is provided by the caller.
+ * @items: Pointer to memory area where to store tree items.
+ *	   This memory is provided by the caller.
+ *	   Its size needs to be at least percpu_counter_tree_items_size().
+ * @batch_size: The batch size is the increment step at level 0 which triggers a
+ * 		carry propagation.
+ *		The batch size is required to be greater than 1, and a power of 2.
+ * @gfp_flags: gfp flags to pass to the per-CPU allocator.
+ *
+ * Initialize one per-CPU counter tree.
+ *
+ * Return:
+ * * %0: Success
+ * * %-EINVAL:		- Invalid @batch_size argument
+ * * %-ENOMEM:		- Out of memory
+ */
+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,
+			     unsigned long batch_size, gfp_t gfp_flags)
+{
+	return percpu_counter_tree_init_many(counter, items, 1, batch_size, gfp_flags);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_init);
+
+/**
+ * percpu_counter_tree_destroy_many() - Destroy many per-CPU counter trees.
+ * @counters: Array of counters trees to destroy.
+ * @nr_counters: The number of counter trees to destroy.
+ *
+ * Release internal resources allocated for @nr_counters per-CPU counter trees.
+ */
+
+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counters, unsigned int nr_counters)
+{
+	free_percpu(counters->level0);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_destroy_many);
+
+/**
+ * percpu_counter_tree_destroy() - Destroy one per-CPU counter tree.
+ * @counter: Counter to destroy.
+ *
+ * Release internal resources allocated for one per-CPU counter tree.
+ */
+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter)
+{
+	return percpu_counter_tree_destroy_many(counter, 1);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_destroy);
+
+static
+long percpu_counter_tree_carry(long orig, long res, long inc, unsigned long bit_mask)
+{
+	if (inc < 0) {
+		inc = -(-inc & ~(bit_mask - 1));
+		/*
+		 * xor bit_mask: underflow.
+		 *
+		 * If inc has bit set, decrement an additional bit if
+		 * there is _no_ bit transition between orig and res.
+		 * Else, inc has bit cleared, decrement an additional
+		 * bit if there is a bit transition between orig and
+		 * res.
+		 */
+		if ((inc ^ orig ^ res) & bit_mask)
+			inc -= bit_mask;
+	} else {
+		inc &= ~(bit_mask - 1);
+		/*
+		 * xor bit_mask: overflow.
+		 *
+		 * If inc has bit set, increment an additional bit if
+		 * there is _no_ bit transition between orig and res.
+		 * Else, inc has bit cleared, increment an additional
+		 * bit if there is a bit transition between orig and
+		 * res.
+		 */
+		if ((inc ^ orig ^ res) & bit_mask)
+			inc += bit_mask;
+	}
+	return inc;
+}
+
+/*
+ * It does not matter through which path the carry propagates up the
+ * tree, therefore there is no need to disable preemption because the
+ * cpu number is only used to favor cache locality.
+ */
+static
+void percpu_counter_tree_add_slowpath(struct percpu_counter_tree *counter, long inc)
+{
+	unsigned int level_items, nr_levels = counter_config->nr_levels,
+		     level, n_arity_order;
+	unsigned long bit_mask;
+	struct percpu_counter_tree_level_item *item = counter->items;
+	unsigned int cpu = raw_smp_processor_id();
+
+	WARN_ON_ONCE(!nr_cpus_order);	/* Should never be called for 1 cpu. */
+
+	n_arity_order = counter_config->n_arity_order[0];
+	bit_mask = counter->level0_bit_mask << n_arity_order;
+	level_items = 1U << (nr_cpus_order - n_arity_order);
+
+	for (level = 1; level < nr_levels; level++) {
+		/*
+		 * For the purpose of carry propagation, the
+		 * intermediate level counters only need to keep track
+		 * of the bits relevant for carry propagation. We
+		 * therefore don't care about higher order bits.
+		 * Note that this optimization is unwanted if the
+		 * intended use is to track counters within intermediate
+		 * levels of the topology.
+		 */
+		if (abs(inc) & (bit_mask - 1)) {
+			atomic_long_t *count = &item[cpu & (level_items - 1)].count;
+			unsigned long orig, res;
+
+			res = atomic_long_add_return_relaxed(inc, count);
+			orig = res - inc;
+			inc = percpu_counter_tree_carry(orig, res, inc, bit_mask);
+			if (likely(!inc))
+				return;
+		}
+		item += level_items;
+		n_arity_order = counter_config->n_arity_order[level];
+		level_items >>= n_arity_order;
+		bit_mask <<= n_arity_order;
+	}
+	atomic_long_add(inc, counter->approx_sum.a);
+}
+
+/**
+ * percpu_counter_tree_add() - Add to a per-CPU counter tree.
+ * @counter: Counter added to.
+ * @inc: Increment value (either positive or negative).
+ *
+ * Add @inc to a per-CPU counter tree. This is a fast-path which will
+ * typically increment per-CPU counters as long as there is no carry
+ * greater or equal to the counter tree batch size.
+ */
+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc)
+{
+	unsigned long bit_mask = counter->level0_bit_mask, orig, res;
+
+	res = this_cpu_add_return(*counter->level0, inc);
+	orig = res - inc;
+	inc = percpu_counter_tree_carry(orig, res, inc, bit_mask);
+	if (likely(!inc))
+		return;
+	percpu_counter_tree_add_slowpath(counter, inc);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_add);
+
+static
+long percpu_counter_tree_precise_sum_unbiased(struct percpu_counter_tree *counter)
+{
+	unsigned long sum = 0;
+	int cpu;
+
+	for_each_possible_cpu(cpu)
+		sum += *per_cpu_ptr(counter->level0, cpu);
+	return (long) sum;
+}
+
+/**
+ * percpu_counter_tree_precise_sum() - Return precise counter sum.
+ * @counter: The counter to sum.
+ *
+ * Querying the precise sum is relatively expensive because it needs to
+ * iterate over all CPUs.
+ * This is meant to be used when accuracy is preferred over speed.
+ *
+ * Return: The current precise counter sum.
+ */
+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter)
+{
+	return percpu_counter_tree_precise_sum_unbiased(counter) + READ_ONCE(counter->bias);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_sum);
+
+static
+int compare_delta(long delta, unsigned long accuracy_neg, unsigned long accuracy_pos)
+{
+	if (delta >= 0) {
+		if (delta <= accuracy_pos)
+			return 0;
+		else
+			return 1;
+	} else {
+		if (-delta <= accuracy_neg)
+			return 0;
+		else
+			return -1;
+	}
+}
+
+/**
+ * percpu_counter_tree_approximate_compare - Approximated comparison of two counter trees.
+ * @a: First counter to compare.
+ * @b: Second counter to compare.
+ *
+ * Evaluate an approximate comparison of two counter trees.
+ * This approximation comparison is fast, and provides an accurate
+ * answer if the counters are found to be either less than or greater
+ * than the other. However, if the approximated comparison returns
+ * 0, the counters respective sums are found to be within the two
+ * counters accuracy range.
+ *
+ * Return:
+ * * %0		- Counters @a and @b do not differ by more than the sum of their respective
+ *                accuracy ranges.
+ * * %-1	- Counter @a less than counter @b.
+ * * %1		- Counter @a is greater than counter @b.
+ */
+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+	return compare_delta(percpu_counter_tree_approximate_sum(a) - percpu_counter_tree_approximate_sum(b),
+			     a->approx_accuracy_range.over + b->approx_accuracy_range.under,
+			     a->approx_accuracy_range.under + b->approx_accuracy_range.over);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_approximate_compare);
+
+/**
+ * percpu_counter_tree_approximate_compare_value - Approximated comparison of a counter tree against a given value.
+ * @counter: Counter to compare.
+ * @v: Value to compare.
+ *
+ * Evaluate an approximate comparison of a counter tree against a given value.
+ * This approximation comparison is fast, and provides an accurate
+ * answer if the counter is found to be either less than or greater
+ * than the value. However, if the approximated comparison returns
+ * 0, the value is within the counter accuracy range.
+ *
+ * Return:
+ * * %0		- The value @v is within the accuracy range of the counter.
+ * * %-1	- The value @v is less than the counter.
+ * * %1		- The value @v is greater than the counter.
+ */
+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v)
+{
+	return compare_delta(v - percpu_counter_tree_approximate_sum(counter),
+			     counter->approx_accuracy_range.under,
+			     counter->approx_accuracy_range.over);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_approximate_compare_value);
+
+/**
+ * percpu_counter_tree_precise_compare - Precise comparison of two counter trees.
+ * @a: First counter to compare.
+ * @b: Second counter to compare.
+ *
+ * Evaluate a precise comparison of two counter trees.
+ * As an optimization, it uses the approximate counter comparison
+ * to quickly compare counters which are far apart. Only cases where
+ * counter sums are within the accuracy range require precise counter
+ * sums.
+ *
+ * Return:
+ * * %0		- Counters are equal.
+ * * %-1	- Counter @a less than counter @b.
+ * * %1		- Counter @a is greater than counter @b.
+ */
+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+	long count_a = percpu_counter_tree_approximate_sum(a),
+	     count_b = percpu_counter_tree_approximate_sum(b);
+	unsigned long accuracy_a, accuracy_b;
+	long delta = count_a - count_b;
+	int res;
+
+	res = compare_delta(delta,
+			    a->approx_accuracy_range.over + b->approx_accuracy_range.under,
+			    a->approx_accuracy_range.under + b->approx_accuracy_range.over);
+	/* The values are distanced enough for an accurate approximated comparison. */
+	if (res)
+		return res;
+
+	/*
+	 * The approximated comparison is within the accuracy range, therefore at least one
+	 * precise sum is needed. Sum the counter which has the largest accuracy first.
+	 */
+	if (delta >= 0) {
+		accuracy_a = a->approx_accuracy_range.under;
+		accuracy_b = b->approx_accuracy_range.over;
+	} else {
+		accuracy_a = a->approx_accuracy_range.over;
+		accuracy_b = b->approx_accuracy_range.under;
+	}
+	if (accuracy_b < accuracy_a) {
+		count_a = percpu_counter_tree_precise_sum(a);
+		res = compare_delta(count_a - count_b,
+				    b->approx_accuracy_range.under,
+				    b->approx_accuracy_range.over);
+		if (res)
+			return res;
+		/* Precise sum of second counter is required. */
+		count_b = percpu_counter_tree_precise_sum(b);
+	} else {
+		count_b = percpu_counter_tree_precise_sum(b);
+		res = compare_delta(count_a - count_b,
+				    a->approx_accuracy_range.over,
+				    a->approx_accuracy_range.under);
+		if (res)
+			return res;
+		/* Precise sum of second counter is required. */
+		count_a = percpu_counter_tree_precise_sum(a);
+	}
+	if (count_a - count_b < 0)
+		return -1;
+	if (count_a - count_b > 0)
+		return 1;
+	return 0;
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_compare);
+
+/**
+ * percpu_counter_tree_precise_compare_value - Precise comparison of a counter tree against a given value.
+ * @counter: Counter to compare.
+ * @v: Value to compare.
+ *
+ * Evaluate a precise comparison of a counter tree against a given value.
+ * As an optimization, it uses the approximate counter comparison
+ * to quickly identify whether the counter and value are far apart.
+ * Only cases where the value is within the counter accuracy range
+ * require a precise counter sum.
+ *
+ * Return:
+ * * %0		- The value @v is equal to the counter.
+ * * %-1	- The value @v is less than the counter.
+ * * %1		- The value @v is greater than the counter.
+ */
+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v)
+{
+	long count = percpu_counter_tree_approximate_sum(counter);
+	int res;
+
+	res = compare_delta(v - count,
+			    counter->approx_accuracy_range.under,
+			    counter->approx_accuracy_range.over);
+	/* The values are distanced enough for an accurate approximated comparison. */
+	if (res)
+		return res;
+
+	/* Precise sum is required. */
+	count = percpu_counter_tree_precise_sum(counter);
+	if (v - count < 0)
+		return -1;
+	if (v - count > 0)
+		return 1;
+	return 0;
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_compare_value);
+
+static
+void percpu_counter_tree_set_bias(struct percpu_counter_tree *counter, long bias)
+{
+	WRITE_ONCE(counter->bias, bias);
+}
+
+/**
+ * percpu_counter_tree_set - Set the counter tree sum to a given value.
+ * @counter: Counter to set.
+ * @v: Value to set.
+ *
+ * Set the counter sum to a given value. It can be useful for instance
+ * to reset the counter sum to 0. Note that even after setting the
+ * counter sum to a given value, the counter sum approximation can
+ * return any value within the accuracy range around that value.
+ */
+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v)
+{
+	percpu_counter_tree_set_bias(counter,
+				     v - percpu_counter_tree_precise_sum_unbiased(counter));
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_set);
+
+/* Initialize to SIZE_MAX to catch early boot misuses. */
+size_t __percpu_counter_tree_items_size __ro_after_init = SIZE_MAX;
+EXPORT_SYMBOL_GPL(__percpu_counter_tree_items_size);
+
+static void __init calculate_accuracy_topology(void)
+{
+	unsigned int nr_levels = counter_config->nr_levels, level;
+	unsigned int level_items = 1U << nr_cpus_order;
+	unsigned long batch_size = 1;
+
+	for (level = 0; level < nr_levels; level++) {
+		unsigned int n_arity_order = counter_config->n_arity_order[level];
+
+		/*
+		 * The accuracy multiplier is derived from a batch size of 1
+		 * to speed up calculating the accuracy at tree initialization.
+		 */
+		accuracy_multiplier += batch_size * level_items;
+		batch_size <<= n_arity_order;
+		level_items >>= n_arity_order;
+	}
+}
+
+int __init percpu_counter_tree_subsystem_init(void)
+{
+	nr_cpus_order = get_count_order(nr_cpu_ids);
+	if (WARN_ON_ONCE(nr_cpus_order >= ARRAY_SIZE(per_nr_cpu_order_config))) {
+		printk(KERN_ERR "Unsupported number of CPUs (%u)\n", nr_cpu_ids);
+		return -1;
+	}
+	counter_config = &per_nr_cpu_order_config[nr_cpus_order];
+	if (!nr_cpus_order)
+		__percpu_counter_tree_items_size = 0;
+	else
+		__percpu_counter_tree_items_size = counter_config->nr_items *
+			sizeof(struct percpu_counter_tree_level_item);
+	calculate_accuracy_topology();
+	return 0;
+}
diff --git a/lib/tests/Makefile b/lib/tests/Makefile
index 3cac3b63a7522..051e73705977b 100644
--- a/lib/tests/Makefile
+++ b/lib/tests/Makefile
@@ -58,4 +58,6 @@ obj-$(CONFIG_UTIL_MACROS_KUNIT) += util_macros_kunit.o
 obj-$(CONFIG_RATELIMIT_KUNIT_TEST) += test_ratelimit.o
 obj-$(CONFIG_UUID_KUNIT_TEST) += uuid_kunit.o
 
+obj-$(CONFIG_PERCPU_COUNTER_TREE_KUNIT_TEST) += percpu_counter_tree_kunit.o
+
 obj-$(CONFIG_TEST_RUNTIME_MODULE)		+= module/
diff --git a/lib/tests/percpu_counter_tree_kunit.c b/lib/tests/percpu_counter_tree_kunit.c
new file mode 100644
index 0000000000000..a79176655c4b0
--- /dev/null
+++ b/lib/tests/percpu_counter_tree_kunit.c
@@ -0,0 +1,399 @@
+// SPDX-License-Identifier: GPL-2.0+ OR MIT
+// SPDX-FileCopyrightText: 2026 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+
+#include <kunit/test.h>
+#include <linux/percpu_counter_tree.h>
+#include <linux/kthread.h>
+#include <linux/wait.h>
+#include <linux/random.h>
+
+struct multi_thread_test_data {
+	long increment;
+	int nr_inc;
+	int counter_index;
+};
+
+#define NR_COUNTERS	2
+
+/* Hierarchical per-CPU counter instances. */
+static struct percpu_counter_tree counter[NR_COUNTERS];
+static struct percpu_counter_tree_level_item *items;
+
+/* Global atomic counters for validation. */
+static atomic_long_t global_counter[NR_COUNTERS];
+
+static DECLARE_WAIT_QUEUE_HEAD(kernel_threads_wq);
+static atomic_t kernel_threads_to_run;
+
+static void complete_work(void)
+{
+	if (atomic_dec_and_test(&kernel_threads_to_run))
+		wake_up(&kernel_threads_wq);
+}
+
+static void hpcc_print_info(struct kunit *test)
+{
+	kunit_info(test, "Running test with %d CPUs\n", num_online_cpus());
+}
+
+static void add_to_counter(int counter_index, unsigned int nr_inc, long increment)
+{
+	unsigned int i;
+
+	for (i = 0; i < nr_inc; i++) {
+		percpu_counter_tree_add(&counter[counter_index], increment);
+		atomic_long_add(increment, &global_counter[counter_index]);
+	}
+}
+
+static void check_counters(struct kunit *test)
+{
+	int counter_index;
+
+	/* Compare each counter with its global counter. */
+	for (counter_index = 0; counter_index < NR_COUNTERS; counter_index++) {
+		long v = atomic_long_read(&global_counter[counter_index]);
+		long approx_sum = percpu_counter_tree_approximate_sum(&counter[counter_index]);
+		unsigned long under_accuracy = 0, over_accuracy = 0;
+		long precise_min, precise_max;
+
+		/* Precise comparison. */
+		KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&counter[counter_index]), v);
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_precise_compare_value(&counter[counter_index], v));
+
+		/* Approximate comparison. */
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&counter[counter_index], v));
+
+		/* Accuracy limits checks. */
+		percpu_counter_tree_approximate_accuracy_range(&counter[counter_index], &under_accuracy, &over_accuracy);
+
+		KUNIT_EXPECT_GE(test, (long)(approx_sum - (v - under_accuracy)), 0);
+		KUNIT_EXPECT_LE(test, (long)(approx_sum - (v + over_accuracy)), 0);
+		KUNIT_EXPECT_GT(test, (long)(approx_sum - (v - under_accuracy - 1)), 0);
+		KUNIT_EXPECT_LT(test, (long)(approx_sum - (v + over_accuracy + 1)), 0);
+
+		/* Precise min/max range check. */
+		percpu_counter_tree_approximate_min_max_range(approx_sum, under_accuracy, over_accuracy, &precise_min, &precise_max);
+
+		KUNIT_EXPECT_GE(test, v - precise_min, 0);
+		KUNIT_EXPECT_LE(test, v - precise_max, 0);
+		KUNIT_EXPECT_GT(test, v - (precise_min - 1), 0);
+		KUNIT_EXPECT_LT(test, v - (precise_max + 1), 0);
+	}
+	/* Compare each counter with the second counter. */
+	KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&counter[0]), percpu_counter_tree_precise_sum(&counter[1]));
+	KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_precise_compare(&counter[0], &counter[1]));
+	KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare(&counter[0], &counter[1]));
+}
+
+static int multi_thread_worker_fn(void *data)
+{
+	struct multi_thread_test_data *td = data;
+
+	add_to_counter(td->counter_index, td->nr_inc, td->increment);
+	complete_work();
+	kfree(td);
+	return 0;
+}
+
+static void test_run_on_specific_cpu(struct kunit *test, int target_cpu, int counter_index, unsigned int nr_inc, long increment)
+{
+	struct task_struct *task;
+	struct multi_thread_test_data *td = kzalloc(sizeof(struct multi_thread_test_data), GFP_KERNEL);
+
+	KUNIT_EXPECT_PTR_NE(test, td, NULL);
+	td->increment = increment;
+	td->nr_inc = nr_inc;
+	td->counter_index = counter_index;
+	atomic_inc(&kernel_threads_to_run);
+	task = kthread_run_on_cpu(multi_thread_worker_fn, td, target_cpu, "kunit_multi_thread_worker");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, task);
+}
+
+static void init_kthreads(void)
+{
+	atomic_set(&kernel_threads_to_run, 1);
+}
+
+static void fini_kthreads(void)
+{
+	/* Release our own reference. */
+	complete_work();
+	/* Wait for all others threads to run. */
+	wait_event(kernel_threads_wq, (atomic_read(&kernel_threads_to_run) == 0));
+}
+
+static void test_sync_kthreads(void)
+{
+	fini_kthreads();
+	init_kthreads();
+}
+
+static void init_counters(struct kunit *test, unsigned long batch_size)
+{
+	int i, ret;
+
+	items = kzalloc(percpu_counter_tree_items_size() * NR_COUNTERS, GFP_KERNEL);
+	KUNIT_EXPECT_PTR_NE(test, items, NULL);
+	ret = percpu_counter_tree_init_many(counter, items, NR_COUNTERS, batch_size, GFP_KERNEL);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+
+	for (i = 0; i < NR_COUNTERS; i++)
+		atomic_long_set(&global_counter[i], 0);
+}
+
+static void fini_counters(void)
+{
+	percpu_counter_tree_destroy_many(counter, NR_COUNTERS);
+	kfree(items);
+}
+
+enum up_test_inc_type {
+	INC_ONE,
+	INC_MINUS_ONE,
+	INC_RANDOM,
+};
+
+/*
+ * Single-threaded tests. Those use many threads to run on various CPUs,
+ * but synchronize for completion of each thread before running the
+ * next, effectively making sure there are no concurrent updates.
+ */
+static void do_hpcc_test_single_thread(struct kunit *test, int _cpu0, int _cpu1, enum up_test_inc_type type)
+{
+	unsigned long batch_size_order = 5;
+	int cpu0 = _cpu0;
+	int cpu1 = _cpu1;
+	int i;
+
+	init_counters(test, 1UL << batch_size_order);
+	init_kthreads();
+	for (i = 0; i < 10000; i++) {
+		long increment;
+
+		switch (type) {
+		case INC_ONE:
+			increment = 1;
+			break;
+		case INC_MINUS_ONE:
+			increment = -1;
+			break;
+		case INC_RANDOM:
+			increment = (long) get_random_long() % 50000;
+			break;
+		}
+		if (_cpu0 < 0)
+			cpu0 = cpumask_any_distribute(cpu_online_mask);
+		if (_cpu1 < 0)
+			cpu1 = cpumask_any_distribute(cpu_online_mask);
+		test_run_on_specific_cpu(test, cpu0, 0, 1, increment);
+		test_sync_kthreads();
+		test_run_on_specific_cpu(test, cpu1, 1, 1, increment);
+		test_sync_kthreads();
+		check_counters(test);
+	}
+	fini_kthreads();
+	fini_counters();
+}
+
+static void hpcc_test_single_thread_first(struct kunit *test)
+{
+	int cpu = cpumask_first(cpu_online_mask);
+
+	do_hpcc_test_single_thread(test, cpu, cpu, INC_ONE);
+	do_hpcc_test_single_thread(test, cpu, cpu, INC_MINUS_ONE);
+	do_hpcc_test_single_thread(test, cpu, cpu, INC_RANDOM);
+}
+
+static void hpcc_test_single_thread_first_random(struct kunit *test)
+{
+	int cpu = cpumask_first(cpu_online_mask);
+
+	do_hpcc_test_single_thread(test, cpu, -1, INC_ONE);
+	do_hpcc_test_single_thread(test, cpu, -1, INC_MINUS_ONE);
+	do_hpcc_test_single_thread(test, cpu, -1, INC_RANDOM);
+}
+
+static void hpcc_test_single_thread_random(struct kunit *test)
+{
+	do_hpcc_test_single_thread(test, -1, -1, INC_ONE);
+	do_hpcc_test_single_thread(test, -1, -1, INC_MINUS_ONE);
+	do_hpcc_test_single_thread(test, -1, -1, INC_RANDOM);
+}
+
+/* Multi-threaded SMP tests. */
+
+static void do_hpcc_multi_thread_increment_each_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+	int cpu;
+
+	init_counters(test, batch_size);
+	init_kthreads();
+	for_each_online_cpu(cpu) {
+		test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+		test_run_on_specific_cpu(test, cpu, 1, nr_inc, increment);
+	}
+	fini_kthreads();
+	check_counters(test);
+	fini_counters();
+}
+
+static void do_hpcc_multi_thread_increment_even_cpus(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+	int cpu;
+
+	init_counters(test, batch_size);
+	init_kthreads();
+	for_each_online_cpu(cpu) {
+		test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+		test_run_on_specific_cpu(test, cpu & ~1, 1, nr_inc, increment); /* even cpus. */
+	}
+	fini_kthreads();
+	check_counters(test);
+	fini_counters();
+}
+
+static void do_hpcc_multi_thread_increment_single_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+	int cpu;
+
+	init_counters(test, batch_size);
+	init_kthreads();
+	for_each_online_cpu(cpu) {
+		test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+		test_run_on_specific_cpu(test, cpumask_first(cpu_online_mask), 1, nr_inc, increment);
+	}
+	fini_kthreads();
+	check_counters(test);
+	fini_counters();
+}
+
+static void do_hpcc_multi_thread_increment_random_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+	int cpu;
+
+	init_counters(test, batch_size);
+	init_kthreads();
+	for_each_online_cpu(cpu) {
+		test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+		test_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);
+	}
+	fini_kthreads();
+	check_counters(test);
+	fini_counters();
+}
+
+static void hpcc_test_multi_thread_batch_increment(struct kunit *test)
+{
+	unsigned long batch_size_order;
+
+	for (batch_size_order = 2; batch_size_order < 10; batch_size_order++) {
+		unsigned int nr_inc;
+
+		for (nr_inc = 1; nr_inc < 1024; nr_inc *= 2) {
+			long increment;
+
+			for (increment = 1; increment < 100000; increment *= 10) {
+				do_hpcc_multi_thread_increment_each_cpu(test, 1UL << batch_size_order, nr_inc, increment);
+				do_hpcc_multi_thread_increment_even_cpus(test, 1UL << batch_size_order, nr_inc, increment);
+				do_hpcc_multi_thread_increment_single_cpu(test, 1UL << batch_size_order, nr_inc, increment);
+				do_hpcc_multi_thread_increment_random_cpu(test, 1UL << batch_size_order, nr_inc, increment);
+			}
+		}
+	}
+}
+
+static void hpcc_test_multi_thread_random_walk(struct kunit *test)
+{
+	unsigned long batch_size_order = 5;
+	int loop;
+
+	for (loop = 0; loop < 100; loop++) {
+		int i;
+
+		init_counters(test, 1UL << batch_size_order);
+		init_kthreads();
+		for (i = 0; i < 1000; i++) {
+			long increment = (long) get_random_long() % 512;
+			unsigned int nr_inc = ((unsigned long) get_random_long()) % 1024;
+
+			test_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 0, nr_inc, increment);
+			test_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);
+		}
+		fini_kthreads();
+		check_counters(test);
+		fini_counters();
+	}
+}
+
+static void hpcc_test_init_one(struct kunit *test)
+{
+	struct percpu_counter_tree pct;
+	struct percpu_counter_tree_level_item *counter_items;
+	int ret;
+
+	counter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);
+	KUNIT_EXPECT_PTR_NE(test, counter_items, NULL);
+	ret = percpu_counter_tree_init(&pct, counter_items, 32, GFP_KERNEL);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+
+	percpu_counter_tree_destroy(&pct);
+	kfree(counter_items);
+}
+
+static void hpcc_test_set(struct kunit *test)
+{
+	static long values[] = {
+		5, 100, 127, 128, 255, 256, 4095, 4096, 500000, 0,
+		-5, -100, -127, -128, -255, -256, -4095, -4096, -500000,
+	};
+	struct percpu_counter_tree pct;
+	struct percpu_counter_tree_level_item *counter_items;
+	int i, ret;
+
+	counter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);
+	KUNIT_EXPECT_PTR_NE(test, counter_items, NULL);
+	ret = percpu_counter_tree_init(&pct, counter_items, 32, GFP_KERNEL);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+
+	for (i = 0; i < ARRAY_SIZE(values); i++) {
+		long v = values[i];
+
+		percpu_counter_tree_set(&pct, v);
+		KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&pct), v);
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&pct, v));
+
+		percpu_counter_tree_add(&pct, v);
+		KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&pct), 2 * v);
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&pct, 2 * v));
+
+		percpu_counter_tree_add(&pct, -2 * v);
+		KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&pct), 0);
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&pct, 0));
+	}
+
+	percpu_counter_tree_destroy(&pct);
+	kfree(counter_items);
+}
+
+static struct kunit_case hpcc_test_cases[] = {
+	KUNIT_CASE(hpcc_print_info),
+	KUNIT_CASE(hpcc_test_single_thread_first),
+	KUNIT_CASE(hpcc_test_single_thread_first_random),
+	KUNIT_CASE(hpcc_test_single_thread_random),
+	KUNIT_CASE(hpcc_test_multi_thread_batch_increment),
+	KUNIT_CASE(hpcc_test_multi_thread_random_walk),
+	KUNIT_CASE(hpcc_test_init_one),
+	KUNIT_CASE(hpcc_test_set),
+	{}
+};
+
+static struct kunit_suite hpcc_test_suite = {
+	.name = "percpu_counter_tree",
+	.test_cases = hpcc_test_cases,
+};
+
+kunit_test_suite(hpcc_test_suite);
+
+MODULE_DESCRIPTION("Test cases for hierarchical per-CPU counters");
+MODULE_LICENSE("Dual MIT/GPL");

3/2 2026/09/02 08:37 llm patch-evaluator
0m Model:
gemini-3.7-flash

Args:
null

Results:
null

Tokens:
							input: 26137
							output: 20
							thoughts: 1272
						

Thoughts:
**Fuzzing Analysis of the Hierarchical Per-CPU Counters Patch**

Alright, let's dive into this patch. It introduces Hierarchical Per-CPU Counters (HPCC) into the Linux kernel, specifically within `lib/percpu_counter_tree.c` and associated header and other files. My initial impression is that this is significant, especially given its integration into core memory management.

I'm seeing that the patch replaces the existing `struct percpu_counter` in `struct mm_struct` with `struct percpu_counter_tree` across multiple files, including critical ones like `mm_types.h`, `mm.h`, and `fork.c`. Functions like `get_mm_counter`, `add_mm_counter`, etc., are now leveraging the new `percpu_counter_tree_*` functions. This means every process's RSS stats are now being managed by this new tree structure. `mm_init()` now calls `percpu_counter_tree_init_many()` as well, further reinforcing its pervasiveness. This seems like a complete overhaul of RSS stat tracking in the kernel.

Given the potential for complex concurrency and carry propagation within the counter tree logic, this screams "high-priority fuzzing target." The `percpu_counter_tree_add`, `percpu_counter_tree_add_slowpath`, `percpu_counter_tree_carry`, and other functions in `lib/percpu_counter_tree.c` are where the real complexity lies.

Now, let's focus on identifying the most relevant symbols for fuzzing. According to my guidelines, I want to prioritize non-static, non-inlined API entrypoints over internal helper functions.

Scanning through `lib/percpu_counter_tree.c`, I'm looking at functions like:

*   `percpu_counter_tree_init_many`, `percpu_counter_tree_init`, `percpu_counter_tree_destroy_many`, `percpu_counter_tree_destroy`, `percpu_counter_tree_precise_sum`, `percpu_counter_tree_approximate_compare`, `percpu_counter_tree_approximate_compare_value`, `percpu_counter_tree_precise_compare`, `percpu_counter_tree_precise_compare_value`, and `percpu_counter_tree_set`.

Crucially, `percpu_counter_tree_add` is a hot-path function; it's being called on every memory allocation, deallocation, and page fault, which means the kernel is using it extensively. Although `percpu_counter_tree_add_slowpath` exists, it's static and likely inlined, so it's less of a target.

Finally, I need to check the Kconfig settings. The `obj-$(CONFIG_SMP) += percpu_counter_tree.o` line in `lib/Makefile` indicates that this is enabled when SMP (symmetric multiprocessing) is configured. SMP is pretty much standard, so it's not a special configuration. I should probably do a quick grep through `lib/Kconfig` or `lib/Makefile` to make sure there aren't any other critical configurations to be aware of, but I can't imagine this being the case.



4/2 2026/09/02 08:37 tool grepper
0m Args:
{
  "Expression": "PERCPU_COUNTER_TREE"
}

Results:
{
  "Output": "include/linux/mm_types.h=1188=struct mm_struct {\n--\ninclude/linux/mm_types.h-1441-\t * The HPCC counter tree items are placed last and aligned\ninclude/linux/mm_types.h:1442:\t * with PERCPU_COUNTER_TREE_ITEMS_ALIGN to satisfy their\ninclude/linux/mm_types.h-1443-\t * cacheline alignment requirement.\n--\ninclude/linux/mm_types.h=1480=extern struct mm_struct init_mm;\n--\ninclude/linux/mm_types.h-1483-{\t\t\t\t\t\t\t\t\t\t\\\ninclude/linux/mm_types.h:1484:\t[0 ... PERCPU_COUNTER_TREE_ITEMS_ALIGN(\t\t\t\t\t\\\ninclude/linux/mm_types.h-1485-\t\t\tsizeof(cpumask_t) + MM_CID_STATIC_SIZE)\t\t\t\\\ninclude/linux/mm_types.h:1486:\t       + (PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE * NR_MM_COUNTERS)\t\\\ninclude/linux/mm_types.h-1487-\t       - 1] = 0\t\t\t\t\t\t\t\t\\\n--\ninclude/linux/mm_types.h=1682=static inline size_t get_rss_stat_items_offset(void)\ninclude/linux/mm_types.h-1683-{\ninclude/linux/mm_types.h:1684:\treturn PERCPU_COUNTER_TREE_ITEMS_ALIGN(cpumask_size() + mm_cid_size());\ninclude/linux/mm_types.h-1685-}\n--\ninclude/linux/percpu_counter_tree.h-3-\ninclude/linux/percpu_counter_tree.h:4:#ifndef _PERCPU_COUNTER_TREE_H\ninclude/linux/percpu_counter_tree.h:5:#define _PERCPU_COUNTER_TREE_H\ninclude/linux/percpu_counter_tree.h-6-\n--\ninclude/linux/percpu_counter_tree.h-13-#if NR_CPUS == (1U \u003c\u003c 0)\ninclude/linux/percpu_counter_tree.h:14:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t0\ninclude/linux/percpu_counter_tree.h-15-#elif NR_CPUS \u003c= (1U \u003c\u003c 1)\ninclude/linux/percpu_counter_tree.h:16:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t1\ninclude/linux/percpu_counter_tree.h-17-#elif NR_CPUS \u003c= (1U \u003c\u003c 2)\ninclude/linux/percpu_counter_tree.h:18:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t3\ninclude/linux/percpu_counter_tree.h-19-#elif NR_CPUS \u003c= (1U \u003c\u003c 3)\ninclude/linux/percpu_counter_tree.h:20:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t7\ninclude/linux/percpu_counter_tree.h-21-#elif NR_CPUS \u003c= (1U \u003c\u003c 4)\ninclude/linux/percpu_counter_tree.h:22:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t7\ninclude/linux/percpu_counter_tree.h-23-#elif NR_CPUS \u003c= (1U \u003c\u003c 5)\ninclude/linux/percpu_counter_tree.h:24:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t11\ninclude/linux/percpu_counter_tree.h-25-#elif NR_CPUS \u003c= (1U \u003c\u003c 6)\ninclude/linux/percpu_counter_tree.h:26:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t21\ninclude/linux/percpu_counter_tree.h-27-#elif NR_CPUS \u003c= (1U \u003c\u003c 7)\ninclude/linux/percpu_counter_tree.h:28:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t21\ninclude/linux/percpu_counter_tree.h-29-#elif NR_CPUS \u003c= (1U \u003c\u003c 8)\ninclude/linux/percpu_counter_tree.h:30:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t37\ninclude/linux/percpu_counter_tree.h-31-#elif NR_CPUS \u003c= (1U \u003c\u003c 9)\ninclude/linux/percpu_counter_tree.h:32:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t73\ninclude/linux/percpu_counter_tree.h-33-#elif NR_CPUS \u003c= (1U \u003c\u003c 10)\ninclude/linux/percpu_counter_tree.h:34:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t149\ninclude/linux/percpu_counter_tree.h-35-#elif NR_CPUS \u003c= (1U \u003c\u003c 11)\ninclude/linux/percpu_counter_tree.h:36:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t293\ninclude/linux/percpu_counter_tree.h-37-#elif NR_CPUS \u003c= (1U \u003c\u003c 12)\ninclude/linux/percpu_counter_tree.h:38:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t585\ninclude/linux/percpu_counter_tree.h-39-#elif NR_CPUS \u003c= (1U \u003c\u003c 13)\ninclude/linux/percpu_counter_tree.h:40:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t1173\ninclude/linux/percpu_counter_tree.h-41-#elif NR_CPUS \u003c= (1U \u003c\u003c 14)\ninclude/linux/percpu_counter_tree.h:42:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t2341\ninclude/linux/percpu_counter_tree.h-43-#elif NR_CPUS \u003c= (1U \u003c\u003c 15)\ninclude/linux/percpu_counter_tree.h:44:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t4681\ninclude/linux/percpu_counter_tree.h-45-#elif NR_CPUS \u003c= (1U \u003c\u003c 16)\ninclude/linux/percpu_counter_tree.h:46:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t4681\ninclude/linux/percpu_counter_tree.h-47-#elif NR_CPUS \u003c= (1U \u003c\u003c 17)\ninclude/linux/percpu_counter_tree.h:48:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t8777\ninclude/linux/percpu_counter_tree.h-49-#elif NR_CPUS \u003c= (1U \u003c\u003c 18)\ninclude/linux/percpu_counter_tree.h:50:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t17481\ninclude/linux/percpu_counter_tree.h-51-#elif NR_CPUS \u003c= (1U \u003c\u003c 19)\ninclude/linux/percpu_counter_tree.h:52:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t34953\ninclude/linux/percpu_counter_tree.h-53-#elif NR_CPUS \u003c= (1U \u003c\u003c 20)\ninclude/linux/percpu_counter_tree.h:54:# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS\t69905\ninclude/linux/percpu_counter_tree.h-55-#else\n--\ninclude/linux/percpu_counter_tree.h=59=struct percpu_counter_tree_level_item {\n--\ninclude/linux/percpu_counter_tree.h-66-\ninclude/linux/percpu_counter_tree.h:67:#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE\t\\\ninclude/linux/percpu_counter_tree.h:68:\t(PERCPU_COUNTER_TREE_STATIC_NR_ITEMS * sizeof(struct percpu_counter_tree_level_item))\ninclude/linux/percpu_counter_tree.h:69:#define PERCPU_COUNTER_TREE_ITEMS_ALIGN(offset)\t\\\ninclude/linux/percpu_counter_tree.h-70-\tALIGN((offset), __alignof__(struct percpu_counter_tree_level_item))\n--\ninclude/linux/percpu_counter_tree.h=179=void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *counter,\n--\ninclude/linux/percpu_counter_tree.h-187-\ninclude/linux/percpu_counter_tree.h:188:#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE\t0\ninclude/linux/percpu_counter_tree.h:189:#define PERCPU_COUNTER_TREE_ITEMS_ALIGN(offset)\t(offset)\ninclude/linux/percpu_counter_tree.h-190-\n--\ninclude/linux/percpu_counter_tree.h=376=void percpu_counter_tree_approximate_min_max(struct percpu_counter_tree *counter,\n--\ninclude/linux/percpu_counter_tree.h-386-\ninclude/linux/percpu_counter_tree.h:387:#endif  /* _PERCPU_COUNTER_TREE_H */\n--\nkernel/fork.c=3120=void __init mm_cache_init(void)\n--\nkernel/fork.c-3129-\tmm_size = sizeof(struct mm_struct) +\nkernel/fork.c:3130:\t\tPERCPU_COUNTER_TREE_ITEMS_ALIGN(cpumask_size() + mm_cid_size()) +\nkernel/fork.c-3131-\t\tget_rss_stat_items_size();\n--\nlib/Kconfig=32=config PACKING_KUNIT_TEST\n--\nlib/Kconfig-43-\nlib/Kconfig:44:config PERCPU_COUNTER_TREE_KUNIT_TEST\nlib/Kconfig-45-\ttristate \"KUnit tests for hierarchical per-cpu counters\" if !KUNIT_ALL_TESTS\n--\nlib/tests/Makefile=59=obj-$(CONFIG_UUID_KUNIT_TEST) += uuid_kunit.o\nlib/tests/Makefile-60-\nlib/tests/Makefile:61:obj-$(CONFIG_PERCPU_COUNTER_TREE_KUNIT_TEST) += percpu_counter_tree_kunit.o\nlib/tests/Makefile-62-\n"
}

5/2 2026/09/02 08:37 llm patch-evaluator
0m Model:
gemini-3.7-flash

Args:
null

Results:
null

Tokens:
							input: 30739
							output: 196
							thoughts: 806
						

Thoughts:
**Analyzing the percpu_counter_tree Implementation**

Okay, let's break this down. First, I need to confirm the core enabling configuration. Looks like `CONFIG_SMP` is the key. The `lib/Makefile` shows `percpu_counter_tree.o` being included only when `CONFIG_SMP` is defined.  And looking at `include/linux/percpu_counter_tree.h`, the hierarchical counter implementation is gated by `#ifdef CONFIG_SMP`. Otherwise, we just get dummy inline wrappers. So, `SMP` it is, that's the primary enabler.

Now, let's identify the specific functions. I'll pull the important function names from `lib/percpu_counter_tree.c`. Let's see... we have: `percpu_counter_tree_init_many`, `percpu_counter_tree_init`, `percpu_counter_tree_destroy_many`, `percpu_counter_tree_destroy`, `percpu_counter_tree_precise_sum`, `percpu_counter_tree_approximate_compare`, `percpu_counter_tree_approximate_compare_value`, `percpu_counter_tree_precise_compare`, `percpu_counter_tree_precise_compare_value`, and `percpu_counter_tree_set`. These are the functions involved. I'll be sure to verify which are actually exported symbols or non-static functions as well.

I need to confirm there are no significant changes elsewhere, especially in something like `kernel/fork.c`. Quick glance indicates that the fork and memory management code is standard. `check_mm`, `__mmdrop`, `mm_init`, `mm_cache_init` are there, but they seem to be standard fork/mm. The main area of new code is centered on `percpu_counter_tree`.

Alright, I'm ready to formalize this for the fuzzing analysis. I've got the required parameters: `WorthFuzzing` is definitely `true`, given the core memory management and concurrency changes. The `Reasoning` should highlight the introduction of Hierarchical Per-CPU Counters (HPCC) for scalability and their integration into `struct mm_struct`, specifically `rss_stat`. We're talking about modifications to core memory management and fork/teardown logic on SMP kernels, including concurrent carry propagation arithmetic and comparisons. `EnableConfigs` is just `["SMP"]`, and the `FocusSymbols` is that full list of function names from above.

I'm double-checking the tool call format. Looks good: `set-results`, with the `WorthFuzzing`, `Reasoning`, `EnableConfigs`, and the `FocusSymbols`. Okay, I'm ready to execute `set-results`.



6/2 2026/09/02 08:37 tool set-results
0m Args:
{
  "EnableConfigs": [
    "SMP"
  ],
  "FocusSymbols": [
    "percpu_counter_tree_init_many",
    "percpu_counter_tree_destroy_many",
    "percpu_counter_tree_precise_sum",
    "percpu_counter_tree_approximate_compare",
    "percpu_counter_tree_approximate_compare_value",
    "percpu_counter_tree_precise_compare",
    "percpu_counter_tree_precise_compare_value",
    "percpu_counter_tree_set"
  ],
  "Reasoning": "The patch introduces Hierarchical Per-CPU Counters (HPCC) for scalable approximate/precise counter aggregation and integrates them into core memory management (struct mm_struct RSS accounting). This introduces complex concurrency, carry propagation, and comparison logic in reachable core kernel paths on SMP systems.",
  "WorthFuzzing": true
}

Results:
{
  "EnableConfigs": [
    "SMP"
  ],
  "FocusSymbols": [
    "percpu_counter_tree_init_many",
    "percpu_counter_tree_destroy_many",
    "percpu_counter_tree_precise_sum",
    "percpu_counter_tree_approximate_compare",
    "percpu_counter_tree_approximate_compare_value",
    "percpu_counter_tree_precise_compare",
    "percpu_counter_tree_precise_compare_value",
    "percpu_counter_tree_set"
  ],
  "Reasoning": "The patch introduces Hierarchical Per-CPU Counters (HPCC) for scalable approximate/precise counter aggregation and integrates them into core memory management (struct mm_struct RSS accounting). This introduces complex concurrency, carry propagation, and comparison logic in reachable core kernel paths on SMP systems.",
  "WorthFuzzing": true
}

7/1 2026/09/02 08:37 action If
1m Args:
{
  "WorthFuzzing": true
}

Results:
null

8/2 2026/09/02 08:37 agent kmsan-evaluator
1m Model:
core

Args:
null

Results:
{
  "KMSANReasoning": "The patch introduces Hierarchical Per-CPU Counters (HPCC / percpu_counter_tree) and transitions `mm_struct`'s RSS accounting (`rss_stat`) to use this new counter tree mechanism with storage placed in the flexible array of `mm_struct`.\n\nAnalyzing the changes for uninitialized memory risks and applicability of KMSAN vs KASAN:\n1. Initialization: All `percpu_counter_tree` structures and their associated tree items are explicitly initialized via `percpu_counter_tree_init_many()` (using `memset` to zero out the items buffer, zero-initialized per-cpu memory via `__alloc_percpu_gfp`, and explicit field initialization in `__percpu_counter_tree_init()`). On UP builds, `count` is initialized with `atomic_long_set(\u0026counters[i].count, 0)`.\n2. Userspace info-leaks: RSS statistics are numeric values accessed via `get_mm_counter()` and exposed as formatted integers (e.g. in `/proc/$pid/status` via `seq_printf`), rather than direct structure copies or uninitialized padding copies to user space.\n3. Memory safety risks: The primary potential risks in this patch involve memory sizing of the flexible array at the end of `mm_struct`, array index calculations during carry propagation, or concurrency issues. These classes of bugs (such as out-of-bounds reads/writes or use-after-free) are monitored and detected by KASAN and standard sanitizers.\n\nBecause no uninitialized memory branches or kernel-to-userspace leaks are introduced or exposed, a dedicated KMSAN fuzzing session is not warranted.",
  "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:
For your convenience, here is the diff of the changes:
commit 016f492f9418f19378197191c764e46711442f39
Author: syz-cluster <triage@syzkaller.com>
Date:   Wed Sep 2 08:37:00 2026 +0000

    syz-cluster: applied patch under review

diff --git a/Documentation/core-api/percpu-counter-tree.rst b/Documentation/core-api/percpu-counter-tree.rst
new file mode 100644
index 0000000000000..196da056e7b42
--- /dev/null
+++ b/Documentation/core-api/percpu-counter-tree.rst
@@ -0,0 +1,75 @@
+========================================
+The Hierarchical Per-CPU Counters (HPCC)
+========================================
+
+:Author: Mathieu Desnoyers
+
+Introduction
+============
+
+Counters come in many varieties, each with their own trade offs:
+
+ * A global atomic counter provides a fast read access to the current
+   sum, at the expense of cache-line bouncing on updates. This leads to
+   poor performance of frequent updates from various cores on large SMP
+   systems.
+
+ * A per-cpu split counter provides fast updates to per-cpu counters,
+   at the expense of a slower aggregation (sum). The sum operation needs
+   to iterate over all per-cpu counters to calculate the current total.
+
+The hierarchical per-cpu counters attempt to provide the best of both
+worlds (fast updates, and fast sum) by relaxing requirements on the sum
+accuracy. It allows quickly querying an approximated sum value, along
+with the possible min/max ranges of the associated precise sum. The
+exact precise sum can still be calculated with an iteration on all
+per-cpu counter, but the availability of an approximated sum value with
+possible precise sum min/max ranges allows eliminating candidates which
+are certainly outside of a known target range without the overhead of
+precise sums.
+
+Overview
+========
+
+The herarchical per-cpu counters are organized as a tree with the tree
+root at the bottom (last level) and the first level of the tree
+consisting of per-cpu counters.
+
+The intermediate tree levels contain carry propagation counters. When
+reaching a threshold (batch size), the carry is propagated down the
+tree.
+
+This allows reading an approximated value at the root, which has a
+bounded accuracy (minimum/maximum possible precise sum range) determined
+by the tree topology.
+
+Use Cases
+=========
+
+Use cases HPCC is meant to handle invove tracking resources which are
+used across many CPUs to quickly sum as feedback for decision making to
+apply throttling, quota limits, sort tasks, and perform memory or task
+migration decisions. When considering approximated sums within the
+accuracy range of the decision threshold, the user can either:
+
+ * Be conservative and fast: Consider that the sum has reached the
+   limit as soon as the given limit is within the approximation range.
+
+ * Be aggressive and fast: Consider that the sum is over the
+   limit only when the approximation range is over the given limit.
+
+ * Be precise and slow: Do a precise comparison with the limit, which
+   requires a precise sum when the limit is within the approximated
+   range.
+
+One use-case for these hierarchical counters is to implement a two-pass
+algorithm to speed up sorting picking a maximum/minimunm sum value from
+a set. A first pass compares the approximated values, and then a second
+pass only needs the precise sum for counter trees which are within the
+possible precise sum range of the counter tree chosen by the first pass.
+
+Functions and structures
+========================
+
+.. kernel-doc:: include/linux/percpu_counter_tree.h
+.. kernel-doc:: lib/percpu_counter_tree.c
diff --git a/include/linux/mm.h b/include/linux/mm.h
index dd09c438fa23e..ffbcd18c4ecb3 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -3447,38 +3447,48 @@ static inline bool get_user_page_fast_only(unsigned long addr,
 {
 	return get_user_pages_fast_only(addr, 1, gup_flags, pagep) == 1;
 }
+
+static inline struct percpu_counter_tree_level_item *get_rss_stat_items(struct mm_struct *mm)
+{
+	unsigned long ptr = (unsigned long)mm;
+
+	ptr += offsetof(struct mm_struct, flexible_array);
+	ptr += get_rss_stat_items_offset();
+	return (struct percpu_counter_tree_level_item *)ptr;
+}
+
 /*
  * per-process(per-mm_struct) statistics.
  */
 static inline unsigned long get_mm_counter(struct mm_struct *mm, int member)
 {
-	return percpu_counter_read_positive(&mm->rss_stat[member]);
+	return percpu_counter_tree_approximate_sum_positive(&mm->rss_stat[member]);
 }
 
 static inline unsigned long get_mm_counter_sum(struct mm_struct *mm, int member)
 {
-	return percpu_counter_sum_positive(&mm->rss_stat[member]);
+	return percpu_counter_tree_precise_sum_positive(&mm->rss_stat[member]);
 }
 
 void mm_trace_rss_stat(struct mm_struct *mm, int member);
 
 static inline void add_mm_counter(struct mm_struct *mm, int member, long value)
 {
-	percpu_counter_add(&mm->rss_stat[member], value);
+	percpu_counter_tree_add(&mm->rss_stat[member], value);
 
 	mm_trace_rss_stat(mm, member);
 }
 
 static inline void inc_mm_counter(struct mm_struct *mm, int member)
 {
-	percpu_counter_inc(&mm->rss_stat[member]);
+	percpu_counter_tree_add(&mm->rss_stat[member], 1);
 
 	mm_trace_rss_stat(mm, member);
 }
 
 static inline void dec_mm_counter(struct mm_struct *mm, int member)
 {
-	percpu_counter_dec(&mm->rss_stat[member]);
+	percpu_counter_tree_add(&mm->rss_stat[member], -1);
 
 	mm_trace_rss_stat(mm, member);
 }
diff --git a/include/linux/mm_types.h b/include/linux/mm_types.h
index 6d815f6440c94..b26160b85f93a 100644
--- a/include/linux/mm_types.h
+++ b/include/linux/mm_types.h
@@ -18,7 +18,7 @@
 #include <linux/page-flags-layout.h>
 #include <linux/workqueue.h>
 #include <linux/seqlock.h>
-#include <linux/percpu_counter.h>
+#include <linux/percpu_counter_tree.h>
 #include <linux/types.h>
 #include <linux/futex_types.h>
 #include <linux/rseq_types.h>
@@ -1170,6 +1170,19 @@ typedef struct {
 	DECLARE_BITMAP(__mm_flags, NUM_MM_FLAG_BITS);
 } __private mm_flags_t;
 
+/*
+ * The alignment of the mm_struct flexible array is based on the largest
+ * alignment of its content:
+ * __alignof__(struct percpu_counter_tree_level_item) provides a
+ * cacheline aligned alignment on SMP systems, else alignment on
+ * unsigned long on UP systems.
+ */
+#ifdef CONFIG_SMP
+# define __mm_struct_flexible_array_aligned	__aligned(__alignof__(struct percpu_counter_tree_level_item))
+#else
+# define __mm_struct_flexible_array_aligned	__aligned(__alignof__(unsigned long))
+#endif
+
 struct kioctx_table;
 struct iommu_mm_data;
 struct mm_struct {
@@ -1312,7 +1325,7 @@ struct mm_struct {
 		unsigned long saved_e_flags;
 #endif
 
-		struct percpu_counter rss_stat[NR_MM_COUNTERS];
+		struct percpu_counter_tree rss_stat[NR_MM_COUNTERS];
 
 		struct linux_binfmt *binfmt;
 
@@ -1422,10 +1435,14 @@ struct mm_struct {
 	} __randomize_layout;
 
 	/*
-	 * The mm_cpumask needs to be at the end of mm_struct, because it
-	 * is dynamically sized based on nr_cpu_ids.
+	 * The mm_cpumask, mm_cid masks, and rss hierarchical counter
+	 * items need to be at the end of mm_struct, because they are
+	 * dynamically sized based on nr_cpu_ids.
+	 * The HPCC counter tree items are placed last and aligned
+	 * with PERCPU_COUNTER_TREE_ITEMS_ALIGN to satisfy their
+	 * cacheline alignment requirement.
 	 */
-	char flexible_array[] __aligned(__alignof__(unsigned long));
+	char flexible_array[] __mm_struct_flexible_array_aligned;
 };
 
 /* Copy value to the first system word of mm flags, non-atomically. */
@@ -1462,18 +1479,12 @@ static inline void __mm_flags_set_mask_bits_word(struct mm_struct *mm,
 			 MT_FLAGS_USE_RCU)
 extern struct mm_struct init_mm;
 
-#define MM_STRUCT_FLEXIBLE_ARRAY_INIT				\
-{								\
-	[0 ... sizeof(cpumask_t) + MM_CID_STATIC_SIZE - 1] = 0	\
-}
-
-/* Pointer magic because the dynamic array size confuses some compilers. */
-static inline void mm_init_cpumask(struct mm_struct *mm)
-{
-	unsigned long cpu_bitmap = (unsigned long)mm;
-
-	cpu_bitmap += offsetof(struct mm_struct, flexible_array);
-	cpumask_clear((struct cpumask *)cpu_bitmap);
+#define MM_STRUCT_FLEXIBLE_ARRAY_INIT						\
+{										\
+	[0 ... PERCPU_COUNTER_TREE_ITEMS_ALIGN(					\
+			sizeof(cpumask_t) + MM_CID_STATIC_SIZE)			\
+	       + (PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE * NR_MM_COUNTERS)	\
+	       - 1] = 0								\
 }
 
 /* Future-safe accessor for struct mm_struct's cpu_vm_mask. */
@@ -1482,6 +1493,11 @@ static inline cpumask_t *mm_cpumask(struct mm_struct *mm)
 	return (struct cpumask *)&mm->flexible_array;
 }
 
+static inline void mm_init_cpumask(struct mm_struct *mm)
+{
+	cpumask_clear((struct cpumask *)mm_cpumask(mm));
+}
+
 #ifdef CONFIG_LRU_GEN
 
 struct lru_gen_mm_list {
@@ -1653,6 +1669,21 @@ static inline void mm_destroy_sched(struct mm_struct *mm) { }
 
 #endif /* CONFIG_SCHED_CACHE */
 
+static inline size_t get_rss_stat_items_size(void)
+{
+	return percpu_counter_tree_items_size() * NR_MM_COUNTERS;
+}
+
+/*
+ * Return the offset of the RSS stat HPCC items within the mm_struct
+ * flexible array. The items are placed after the cpumask and mm_cid,
+ * aligned to the cacheline boundary required by the tree level items.
+ */
+static inline size_t get_rss_stat_items_offset(void)
+{
+	return PERCPU_COUNTER_TREE_ITEMS_ALIGN(cpumask_size() + mm_cid_size());
+}
+
 struct mmu_gather;
 extern void tlb_gather_mmu(struct mmu_gather *tlb, struct mm_struct *mm);
 extern void tlb_gather_mmu_fullmm(struct mmu_gather *tlb, struct mm_struct *mm);
diff --git a/include/linux/percpu_counter_tree.h b/include/linux/percpu_counter_tree.h
new file mode 100644
index 0000000000000..4095acdc879bf
--- /dev/null
+++ b/include/linux/percpu_counter_tree.h
@@ -0,0 +1,387 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+/* SPDX-FileCopyrightText: 2025 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> */
+
+#ifndef _PERCPU_COUNTER_TREE_H
+#define _PERCPU_COUNTER_TREE_H
+
+#include <linux/preempt.h>
+#include <linux/atomic.h>
+#include <linux/percpu.h>
+
+#ifdef CONFIG_SMP
+
+#if NR_CPUS == (1U << 0)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	0
+#elif NR_CPUS <= (1U << 1)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	1
+#elif NR_CPUS <= (1U << 2)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	3
+#elif NR_CPUS <= (1U << 3)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	7
+#elif NR_CPUS <= (1U << 4)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	7
+#elif NR_CPUS <= (1U << 5)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	11
+#elif NR_CPUS <= (1U << 6)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	21
+#elif NR_CPUS <= (1U << 7)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	21
+#elif NR_CPUS <= (1U << 8)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	37
+#elif NR_CPUS <= (1U << 9)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	73
+#elif NR_CPUS <= (1U << 10)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	149
+#elif NR_CPUS <= (1U << 11)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	293
+#elif NR_CPUS <= (1U << 12)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	585
+#elif NR_CPUS <= (1U << 13)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	1173
+#elif NR_CPUS <= (1U << 14)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	2341
+#elif NR_CPUS <= (1U << 15)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	4681
+#elif NR_CPUS <= (1U << 16)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	4681
+#elif NR_CPUS <= (1U << 17)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	8777
+#elif NR_CPUS <= (1U << 18)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	17481
+#elif NR_CPUS <= (1U << 19)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	34953
+#elif NR_CPUS <= (1U << 20)
+# define PERCPU_COUNTER_TREE_STATIC_NR_ITEMS	69905
+#else
+# error "Unsupported number of CPUs."
+#endif
+
+struct percpu_counter_tree_level_item {
+	atomic_long_t count;		/*
+					 * Count the number of carry for this tree item.
+					 * The carry counter is kept at the order of the
+					 * carry accounted for at this tree level.
+					 */
+} ____cacheline_aligned_in_smp;
+
+#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE	\
+	(PERCPU_COUNTER_TREE_STATIC_NR_ITEMS * sizeof(struct percpu_counter_tree_level_item))
+#define PERCPU_COUNTER_TREE_ITEMS_ALIGN(offset)	\
+	ALIGN((offset), __alignof__(struct percpu_counter_tree_level_item))
+
+struct percpu_counter_tree {
+	/* Fast-path fields. */
+	unsigned long __percpu *level0;	/* Pointer to per-CPU split counters (tree level 0). */
+	unsigned long level0_bit_mask;	/* Bit mask to apply to detect carry propagation from tree level 0. */
+	union {
+		unsigned long *i;	/* Approximate sum for single-CPU topology. */
+		atomic_long_t *a;	/* Approximate sum for SMP topology.  */
+	} approx_sum;
+	long bias;			/* Bias to apply to counter precise and approximate values. */
+
+	/* Slow-path fields. */
+	struct percpu_counter_tree_level_item *items;	/* Array of tree items for levels 1 to N. */
+	unsigned long batch_size;	/*
+					 * The batch size is the increment step at level 0 which
+					 * triggers a carry propagation. The batch size is required
+					 * to be greater than 1, and a power of 2.
+					 */
+	/*
+	 * The tree approximate sum is guaranteed to be within this accuracy range:
+	 * (precise_sum - approx_accuracy_range.under) <= approx_sum <= (precise_sum + approx_accuracy_range.over).
+	 * This accuracy is derived from the hardware topology and the tree batch_size.
+	 * The "under" accuracy is larger than the "over" accuracy because the negative range of a
+	 * two's complement signed integer is one unit larger than the positive range. This delta
+	 * is summed for each tree item, which leads to a significantly larger "under" accuracy range
+	 * compared to the "over" accuracy range.
+	 */
+	struct {
+		unsigned long under;
+		unsigned long over;
+	} approx_accuracy_range;
+};
+
+extern size_t __percpu_counter_tree_items_size __ro_after_init;
+
+/*
+ * percpu_counter_tree_items_size - Query the size required for counter tree items.
+ *
+ * Query the size of the memory area required to hold the counter tree
+ * items. This depends on the hardware topology and is invariant after
+ * boot.
+ *
+ * Return: Size required to hold tree items.
+ */
+static inline
+size_t percpu_counter_tree_items_size(void)
+{
+	WARN_ON_ONCE(__percpu_counter_tree_items_size == SIZE_MAX);
+	return __percpu_counter_tree_items_size;
+}
+
+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,
+				  unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags);
+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,
+			     unsigned long batch_size, gfp_t gfp_flags);
+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counter, unsigned int nr_counters);
+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter);
+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc);
+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter);
+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b);
+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v);
+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b);
+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v);
+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v);
+int percpu_counter_tree_subsystem_init(void);
+
+/**
+ * percpu_counter_tree_approximate_sum() - Return approximate counter sum.
+ * @counter: The counter to sum.
+ *
+ * Querying the approximate sum is fast, but it is only accurate within
+ * the bounds delimited by percpu_counter_tree_approximate_accuracy_range().
+ * This is meant to be used when speed is preferred over accuracy.
+ *
+ * Return: The current approximate counter sum.
+ */
+static inline
+long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)
+{
+	unsigned long v;
+
+	if (!counter->level0_bit_mask)
+		v = READ_ONCE(*counter->approx_sum.i);
+	else
+		v = atomic_long_read(counter->approx_sum.a);
+	return (long) (v + (unsigned long)READ_ONCE(counter->bias));
+}
+
+/**
+ * percpu_counter_tree_approximate_accuracy_range - Query the accuracy range for a counter tree.
+ * @counter: Counter to query.
+ * @under: Pointer to a variable to be incremented of the approximation
+ *         accuracy range below the precise sum.
+ * @over: Pointer to a variable to be incremented of the approximation
+ *        accuracy range above the precise sum.
+ *
+ * Query the accuracy range limits for the counter.
+ * Because of two's complement binary representation, the "under" range is typically
+ * slightly larger than the "over" range.
+ * Those values are derived from the hardware topology and the counter tree batch size.
+ * They are invariant for a given counter tree.
+ * Using this function should not be typically required, see the following functions instead:
+ * * percpu_counter_tree_approximate_compare(),
+ * * percpu_counter_tree_approximate_compare_value(),
+ * * percpu_counter_tree_precise_compare(),
+ * * percpu_counter_tree_precise_compare_value().
+ */
+static inline
+void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *counter,
+						    unsigned long *under, unsigned long *over)
+{
+	*under += counter->approx_accuracy_range.under;
+	*over += counter->approx_accuracy_range.over;
+}
+
+#else	/* !CONFIG_SMP */
+
+#define PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE	0
+#define PERCPU_COUNTER_TREE_ITEMS_ALIGN(offset)	(offset)
+
+struct percpu_counter_tree_level_item;
+
+struct percpu_counter_tree {
+	atomic_long_t count;
+};
+
+static inline
+size_t percpu_counter_tree_items_size(void)
+{
+	return 0;
+}
+
+static inline
+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,
+				  unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags)
+{
+	for (unsigned int i = 0; i < nr_counters; i++)
+		atomic_long_set(&counters[i].count, 0);
+	return 0;
+}
+
+static inline
+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,
+			     unsigned long batch_size, gfp_t gfp_flags)
+{
+	return percpu_counter_tree_init_many(counter, items, 1, batch_size, gfp_flags);
+}
+
+static inline
+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counter, unsigned int nr_counters)
+{
+}
+
+static inline
+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter)
+{
+}
+
+static inline
+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter)
+{
+	return atomic_long_read(&counter->count);
+}
+
+static inline
+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+	long count_a = percpu_counter_tree_precise_sum(a),
+	     count_b = percpu_counter_tree_precise_sum(b);
+
+	if (count_a == count_b)
+		return 0;
+	if (count_a < count_b)
+		return -1;
+	return 1;
+}
+
+static inline
+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v)
+{
+	long count = percpu_counter_tree_precise_sum(counter);
+
+	if (count == v)
+		return 0;
+	if (count < v)
+		return -1;
+	return 1;
+}
+
+static inline
+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+	return percpu_counter_tree_precise_compare(a, b);
+}
+
+static inline
+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v)
+{
+	return percpu_counter_tree_precise_compare_value(counter, v);
+}
+
+static inline
+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v)
+{
+	atomic_long_set(&counter->count, v);
+}
+
+static inline
+void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *counter,
+						    unsigned long *under, unsigned long *over)
+{
+}
+
+static inline
+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc)
+{
+	atomic_long_add(inc, &counter->count);
+}
+
+static inline
+long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)
+{
+	return percpu_counter_tree_precise_sum(counter);
+}
+
+static inline
+int percpu_counter_tree_subsystem_init(void)
+{
+	return 0;
+}
+
+#endif	/* CONFIG_SMP */
+
+/**
+ * percpu_counter_tree_approximate_sum_positive() - Return a positive approximate counter sum.
+ * @counter: The counter to sum.
+ *
+ * Return an approximate counter sum which is guaranteed to be greater
+ * or equal to 0.
+ *
+ * Return: The current positive approximate counter sum.
+ */
+static inline
+long percpu_counter_tree_approximate_sum_positive(struct percpu_counter_tree *counter)
+{
+	long v = percpu_counter_tree_approximate_sum(counter);
+	return v > 0 ? v : 0;
+}
+
+/**
+ * percpu_counter_tree_precise_sum_positive() - Return a positive precise counter sum.
+ * @counter: The counter to sum.
+ *
+ * Return a precise counter sum which is guaranteed to be greater
+ * or equal to 0.
+ *
+ * Return: The current positive precise counter sum.
+ */
+static inline
+long percpu_counter_tree_precise_sum_positive(struct percpu_counter_tree *counter)
+{
+	long v = percpu_counter_tree_precise_sum(counter);
+	return v > 0 ? v : 0;
+}
+
+/**
+ * percpu_counter_tree_approximate_min_max_range() - Return the approximation min and max precise values.
+ * @approx_sum: Approximated sum.
+ * @under: Tree accuracy range (under).
+ * @over: Tree accuracy range (over).
+ * @precise_min: Minimum possible value for precise sum (output).
+ * @precise_max: Maximum possible value for precise sum (output).
+ *
+ * Calculate the minimum and maximum precise values for a given
+ * approximation and (under, over) accuracy range.
+ *
+ * The range of the approximation as a function of the precise sum is expressed as:
+ *
+ *   approx_sum >= precise_sum - approx_accuracy_range.under
+ *   approx_sum <= precise_sum + approx_accuracy_range.over
+ *
+ * Therefore, the range of the precise sum as a function of the approximation is expressed as:
+ *
+ *   precise_sum <= approx_sum + approx_accuracy_range.under
+ *   precise_sum >= approx_sum - approx_accuracy_range.over
+ */
+static inline
+void percpu_counter_tree_approximate_min_max_range(long approx_sum, unsigned long under, unsigned long over,
+						   long *precise_min, long *precise_max)
+{
+	*precise_min = approx_sum - over;
+	*precise_max = approx_sum + under;
+}
+
+/**
+ * percpu_counter_tree_approximate_min_max() - Return the tree approximation, min and max possible precise values.
+ * @counter: The counter to sum.
+ * @approx_sum: Approximate sum (output).
+ * @precise_min: Minimum possible value for precise sum (output).
+ * @precise_max: Maximum possible value for precise sum (output).
+ *
+ * Return the approximate sum, minimum and maximum precise values for
+ * a counter.
+ */
+static inline
+void percpu_counter_tree_approximate_min_max(struct percpu_counter_tree *counter,
+					     long *approx_sum, long *precise_min, long *precise_max)
+{
+	unsigned long under = 0, over = 0;
+	long v = percpu_counter_tree_approximate_sum(counter);
+
+	percpu_counter_tree_approximate_accuracy_range(counter, &under, &over);
+	percpu_counter_tree_approximate_min_max_range(v, under, over, precise_min, precise_max);
+	*approx_sum = v;
+}
+
+#endif  /* _PERCPU_COUNTER_TREE_H */
diff --git a/include/trace/events/kmem.h b/include/trace/events/kmem.h
index cd7920c81f85b..290ccb9fd25dd 100644
--- a/include/trace/events/kmem.h
+++ b/include/trace/events/kmem.h
@@ -448,7 +448,7 @@ TRACE_EVENT(rss_stat,
 		 */
 		__entry->curr = current->mm == mm && !(current->flags & PF_KTHREAD);
 		__entry->member = member;
-		__entry->size = (percpu_counter_sum_positive(&mm->rss_stat[member])
+		__entry->size = (percpu_counter_tree_approximate_sum_positive(&mm->rss_stat[member])
 							    << PAGE_SHIFT);
 	),
 
diff --git a/init/main.c b/init/main.c
index 2613d3f9b3ce9..845cb57e90965 100644
--- a/init/main.c
+++ b/init/main.c
@@ -108,6 +108,7 @@
 #include <linux/time_namespace.h>
 #include <linux/unaligned.h>
 #include <linux/vdso_datastore.h>
+#include <linux/percpu_counter_tree.h>
 #include <net/net_namespace.h>
 
 #include <asm/io.h>
@@ -1010,6 +1011,7 @@ void start_kernel(void)
 	setup_boot_config();
 	setup_command_line(command_line);
 	setup_nr_cpu_ids();
+	percpu_counter_tree_subsystem_init();
 	setup_per_cpu_areas();
 	smp_prepare_boot_cpu();	/* arch-specific boot-cpu hooks */
 	early_numa_node_init();
diff --git a/kernel/fork.c b/kernel/fork.c
index 416758c8a3d43..db398b6c52886 100644
--- a/kernel/fork.c
+++ b/kernel/fork.c
@@ -137,6 +137,11 @@
  */
 #define MAX_THREADS FUTEX_TID_MASK
 
+/*
+ * Batch size of rss stat approximation
+ */
+#define RSS_STAT_BATCH_SIZE	32
+
 /*
  * Protected counters by write_lock_irq(&tasklist_lock)
  */
@@ -633,14 +638,12 @@ static void check_mm(struct mm_struct *mm)
 			 "Please make sure 'struct resident_page_types[]' is updated as well");
 
 	for (i = 0; i < NR_MM_COUNTERS; i++) {
-		long x = percpu_counter_sum(&mm->rss_stat[i]);
-
-		if (unlikely(x)) {
+		if (unlikely(percpu_counter_tree_precise_compare_value(&mm->rss_stat[i], 0) != 0))
 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld Comm:%s Pid:%d\n",
-				 mm, resident_page_types[i], x,
+				 mm, resident_page_types[i],
+				 percpu_counter_tree_precise_sum(&mm->rss_stat[i]),
 				 current->comm,
 				 task_pid_nr(current));
-		}
 	}
 
 	if (mm_pgtables_bytes(mm))
@@ -738,7 +741,7 @@ void __mmdrop(struct mm_struct *mm)
 	check_mm(mm);
 	mm_pasid_drop(mm);
 	mm_destroy_cid(mm);
-	percpu_counter_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
+	percpu_counter_tree_destroy_many(mm->rss_stat, NR_MM_COUNTERS);
 
 	free_mm(mm);
 }
@@ -1144,8 +1147,9 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
 	if (mm_alloc_sched(mm))
 		goto fail_sched;
 
-	if (percpu_counter_init_many(mm->rss_stat, 0, GFP_KERNEL_ACCOUNT,
-				     NR_MM_COUNTERS))
+	if (percpu_counter_tree_init_many(mm->rss_stat, get_rss_stat_items(mm),
+					  NR_MM_COUNTERS, RSS_STAT_BATCH_SIZE,
+					  GFP_KERNEL_ACCOUNT))
 		goto fail_pcpu;
 
 	lru_gen_init_mm(mm);
@@ -3122,7 +3126,9 @@ void __init mm_cache_init(void)
 	 * dynamically sized based on the maximum CPU number this system
 	 * can have, taking hotplug into account (nr_cpu_ids).
 	 */
-	mm_size = sizeof(struct mm_struct) + cpumask_size() + mm_cid_size();
+	mm_size = sizeof(struct mm_struct) +
+		PERCPU_COUNTER_TREE_ITEMS_ALIGN(cpumask_size() + mm_cid_size()) +
+		get_rss_stat_items_size();
 
 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
diff --git a/lib/Kconfig b/lib/Kconfig
index 4e6b34c3346d5..c0524258b2058 100644
--- a/lib/Kconfig
+++ b/lib/Kconfig
@@ -41,6 +41,18 @@ config PACKING_KUNIT_TEST
 
 	  When in doubt, say N.
 
+config PERCPU_COUNTER_TREE_KUNIT_TEST
+	tristate "KUnit tests for hierarchical per-cpu counters" if !KUNIT_ALL_TESTS
+	depends on KUNIT
+	default KUNIT_ALL_TESTS
+	help
+	  This builds Kunit tests for the hierarchical per-cpu counters.
+
+	  For more information on KUnit and unit tests in general,
+	  please refer to the KUnit documentation in Documentation/dev-tools/kunit/.
+
+	  When in doubt, say N.
+
 config BITREVERSE
 	tristate
 	select GENERIC_BITREVERSE if !HAVE_ARCH_BITREVERSE
diff --git a/lib/Makefile b/lib/Makefile
index dfab958327c5c..f1d0cb831630b 100644
--- a/lib/Makefile
+++ b/lib/Makefile
@@ -182,6 +182,7 @@ obj-$(CONFIG_TEXTSEARCH_KMP) += ts_kmp.o
 obj-$(CONFIG_TEXTSEARCH_BM) += ts_bm.o
 obj-$(CONFIG_TEXTSEARCH_FSM) += ts_fsm.o
 obj-$(CONFIG_SMP) += percpu_counter.o
+obj-$(CONFIG_SMP) += percpu_counter_tree.o
 obj-$(CONFIG_AUDIT_GENERIC) += audit.o
 obj-$(CONFIG_AUDIT_COMPAT_GENERIC) += compat_audit.o
 
diff --git a/lib/percpu_counter_tree.c b/lib/percpu_counter_tree.c
new file mode 100644
index 0000000000000..cfa5b04e05d7e
--- /dev/null
+++ b/lib/percpu_counter_tree.c
@@ -0,0 +1,694 @@
+// SPDX-License-Identifier: GPL-2.0+ OR MIT
+// SPDX-FileCopyrightText: 2025 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+
+/*
+ * Split Counters With Tree Approximation Propagation
+ *
+ * * Propagation diagram when reaching batch size thresholds (± batch size):
+ *
+ * Example diagram for 8 CPUs:
+ *
+ * log2(8) = 3 levels
+ *
+ * At each level, each pair propagates its values to the next level when
+ * reaching the batch size thresholds.
+ *
+ * Counters at levels 0, 1, 2 can be kept on a single byte ([-128 .. +127] range),
+ * although it may be relevant to keep them on "long" counters for
+ * simplicity. (complexity vs memory footprint tradeoff)
+ *
+ * Counter at level 3 can be kept on a "long" counter.
+ *
+ * Level 0:  0    1    2    3    4    5    6    7
+ *           |   /     |   /     |   /     |   /
+ *           |  /      |  /      |  /      |  /
+ *           | /       | /       | /       | /
+ * Level 1:  0         1         2         3
+ *           |       /           |       /
+ *           |    /              |    /
+ *           | /                 | /
+ * Level 2:  0                   1
+ *           |               /
+ *           |         /
+ *           |   /
+ * Level 3:  0
+ *
+ * * Approximation accuracy:
+ *
+ * BATCH(level N): Level N batch size.
+ *
+ * Example for BATCH(level 0) = 32.
+ *
+ * BATCH(level 0) =  32
+ * BATCH(level 1) =  64
+ * BATCH(level 2) = 128
+ * BATCH(level N) = BATCH(level 0) * 2^N
+ *
+ *            per-counter     global
+ *            accuracy        accuracy
+ * Level 0:   [ -32 ..  +31]  ±256  (8 * 32)
+ * Level 1:   [ -64 ..  +63]  ±256  (4 * 64)
+ * Level 2:   [-128 .. +127]  ±256  (2 * 128)
+ * Total:      ------         ±768  (log2(nr_cpu_ids) * BATCH(level 0) * nr_cpu_ids)
+ *
+ * Note that the global accuracy can be calculated more precisely
+ * by taking into account that the positive accuracy range is
+ * 31 rather than 32.
+ *
+ * -----
+ *
+ * Approximate Sum Carry Propagation
+ *
+ * Let's define a number of counter bits for each level, e.g.:
+ *
+ * log2(BATCH(level 0)) = log2(32) = 5
+ * Let's assume, for this example, a 32-bit architecture (sizeof(long) == 4).
+ *
+ *               nr_bit        value_mask                      range
+ * Level 0:      5 bits        v                             0 ..  +31
+ * Level 1:      1 bit        (v & ~((1UL << 5) - 1))        0 ..  +63
+ * Level 2:      1 bit        (v & ~((1UL << 6) - 1))        0 .. +127
+ * Level 3:     25 bits       (v & ~((1UL << 7) - 1))        0 .. 2^32-1
+ *
+ * Note: Use a "long" per-cpu counter at level 0 to allow precise sum.
+ *
+ * Note: Use cacheline aligned counters at levels above 0 to prevent false sharing.
+ *       If memory footprint is an issue, a specialized allocator could be used
+ *       to eliminate padding.
+ *
+ * Example with expanded values:
+ *
+ * counter_add(counter, inc):
+ *
+ *         if (!inc)
+ *                 return;
+ *
+ *         res = percpu_add_return(counter @ Level 0, inc);
+ *         orig = res - inc;
+ *         if (inc < 0) {
+ *                 inc = -(-inc & ~0b00011111);  // Clear used bits
+ *                 // xor bit 5: underflow
+ *                 if ((inc ^ orig ^ res) & 0b00100000)
+ *                         inc -= 0b00100000;
+ *         } else {
+ *                 inc &= ~0b00011111;           // Clear used bits
+ *                 // xor bit 5: overflow
+ *                 if ((inc ^ orig ^ res) & 0b00100000)
+ *                         inc += 0b00100000;
+ *         }
+ *         if (!inc)
+ *                 return;
+ *
+ *         res = atomic_long_add_return(counter @ Level 1, inc);
+ *         orig = res - inc;
+ *         if (inc < 0) {
+ *                 inc = -(-inc & ~0b00111111);  // Clear used bits
+ *                 // xor bit 6: underflow
+ *                 if ((inc ^ orig ^ res) & 0b01000000)
+ *                         inc -= 0b01000000;
+ *         } else {
+ *                 inc &= ~0b00111111;           // Clear used bits
+ *                 // xor bit 6: overflow
+ *                 if ((inc ^ orig ^ res) & 0b01000000)
+ *                         inc += 0b01000000;
+ *         }
+ *         if (!inc)
+ *                 return;
+ *
+ *         res = atomic_long_add_return(counter @ Level 2, inc);
+ *         orig = res - inc;
+ *         if (inc < 0) {
+ *                 inc = -(-inc & ~0b01111111);  // Clear used bits
+ *                 // xor bit 7: underflow
+ *                 if ((inc ^ orig ^ res) & 0b10000000)
+ *                         inc -= 0b10000000;
+ *         } else {
+ *                 inc &= ~0b01111111;           // Clear used bits
+ *                 // xor bit 7: overflow
+ *                 if ((inc ^ orig ^ res) & 0b10000000)
+ *                         inc += 0b10000000;
+ *         }
+ *         if (!inc)
+ *                 return;
+ *
+ *         atomic_long_add(counter @ Level 3, inc);
+ */
+
+#include <linux/percpu_counter_tree.h>
+#include <linux/cpumask.h>
+#include <linux/atomic.h>
+#include <linux/export.h>
+#include <linux/percpu.h>
+#include <linux/errno.h>
+#include <linux/slab.h>
+#include <linux/math.h>
+
+#define MAX_NR_LEVELS 5
+
+/*
+ * The counter configuration is selected at boot time based on the
+ * hardware topology.
+ */
+struct counter_config {
+	unsigned int nr_items;				/*
+							 * nr_items is the number of items in the tree for levels 1
+							 * up to and including the final level (approximate sum).
+							 * It excludes the level 0 per-CPU counters.
+							 */
+	unsigned char nr_levels;			/*
+							 * nr_levels is the number of hierarchical counter tree levels.
+							 * It excludes the final level (approximate sum).
+							 */
+	unsigned char n_arity_order[MAX_NR_LEVELS];	/*
+							 * n-arity of tree nodes for each level from
+							 * 0 to (nr_levels - 1).
+							 */
+};
+
+static const struct counter_config per_nr_cpu_order_config[] = {
+	[0] =	{ .nr_items = 0,	.nr_levels = 0,		.n_arity_order = { 0 } },
+	[1] =	{ .nr_items = 1,	.nr_levels = 1,		.n_arity_order = { 1 } },
+	[2] =	{ .nr_items = 3,	.nr_levels = 2,		.n_arity_order = { 1, 1 } },
+	[3] =	{ .nr_items = 7,	.nr_levels = 3,		.n_arity_order = { 1, 1, 1 } },
+	[4] =	{ .nr_items = 7,	.nr_levels = 3,		.n_arity_order = { 2, 1, 1 } },
+	[5] =	{ .nr_items = 11,	.nr_levels = 3,		.n_arity_order = { 2, 2, 1 } },
+	[6] =	{ .nr_items = 21,	.nr_levels = 3,		.n_arity_order = { 2, 2, 2 } },
+	[7] =	{ .nr_items = 21,	.nr_levels = 3,		.n_arity_order = { 3, 2, 2 } },
+	[8] =	{ .nr_items = 37,	.nr_levels = 3,		.n_arity_order = { 3, 3, 2 } },
+	[9] =	{ .nr_items = 73,	.nr_levels = 3,		.n_arity_order = { 3, 3, 3 } },
+	[10] =	{ .nr_items = 149,	.nr_levels = 4,		.n_arity_order = { 3, 3, 2, 2 } },
+	[11] =	{ .nr_items = 293,	.nr_levels = 4,		.n_arity_order = { 3, 3, 3, 2 } },
+	[12] =	{ .nr_items = 585,	.nr_levels = 4,		.n_arity_order = { 3, 3, 3, 3 } },
+	[13] =	{ .nr_items = 1173,	.nr_levels = 5,		.n_arity_order = { 3, 3, 3, 2, 2 } },
+	[14] =	{ .nr_items = 2341,	.nr_levels = 5,		.n_arity_order = { 3, 3, 3, 3, 2 } },
+	[15] =	{ .nr_items = 4681,	.nr_levels = 5,		.n_arity_order = { 3, 3, 3, 3, 3 } },
+	[16] =	{ .nr_items = 4681,	.nr_levels = 5,		.n_arity_order = { 4, 3, 3, 3, 3 } },
+	[17] =	{ .nr_items = 8777,	.nr_levels = 5,		.n_arity_order = { 4, 4, 3, 3, 3 } },
+	[18] =	{ .nr_items = 17481,	.nr_levels = 5,		.n_arity_order = { 4, 4, 4, 3, 3 } },
+	[19] =	{ .nr_items = 34953,	.nr_levels = 5,		.n_arity_order = { 4, 4, 4, 4, 3 } },
+	[20] =	{ .nr_items = 69905,	.nr_levels = 5,		.n_arity_order = { 4, 4, 4, 4, 4 } },
+};
+
+static const struct counter_config *counter_config;	/* Hierarchical counter configuration for the hardware topology. */
+static unsigned int nr_cpus_order;			/* Order of nr_cpu_ids. */
+static unsigned long accuracy_multiplier;		/* Calculate accuracy for a given batch size (multiplication factor). */
+
+static
+int __percpu_counter_tree_init(struct percpu_counter_tree *counter,
+			       unsigned long batch_size, gfp_t gfp_flags,
+			       unsigned long __percpu *level0,
+			       struct percpu_counter_tree_level_item *items)
+{
+	/* Batch size must be greater than 1, and a power of 2. */
+	if (WARN_ON(batch_size <= 1 || (batch_size & (batch_size - 1))))
+		return -EINVAL;
+	counter->batch_size = batch_size;
+	counter->bias = 0;
+	counter->level0 = level0;
+	counter->items = items;
+	if (!nr_cpus_order) {
+		counter->approx_sum.i = per_cpu_ptr(counter->level0, 0);
+		counter->level0_bit_mask = 0;
+	} else {
+		counter->approx_sum.a = &counter->items[counter_config->nr_items - 1].count;
+		counter->level0_bit_mask = 1UL << get_count_order(batch_size);
+	}
+	/*
+	 * Each tree item signed integer has a negative range which is
+	 * one unit greater than the positive range.
+	 */
+	counter->approx_accuracy_range.under = batch_size * accuracy_multiplier;
+	counter->approx_accuracy_range.over = (batch_size - 1) * accuracy_multiplier;
+	return 0;
+}
+
+/**
+ * percpu_counter_tree_init_many() - Initialize many per-CPU counter trees.
+ * @counters: An array of @nr_counters counters to initialize.
+ *	      Their memory is provided by the caller.
+ * @items: Pointer to memory area where to store tree items.
+ *	   This memory is provided by the caller.
+ *	   Its size needs to be at least @nr_counters * percpu_counter_tree_items_size().
+ * @nr_counters: The number of counter trees to initialize
+ * @batch_size: The batch size is the increment step at level 0 which triggers a
+ * 		carry propagation.
+ *		The batch size is required to be greater than 1, and a power of 2.
+ * @gfp_flags: gfp flags to pass to the per-CPU allocator.
+ *
+ * Initialize many per-CPU counter trees using a single per-CPU
+ * allocator invocation for @nr_counters counters.
+ *
+ * Return:
+ * * %0: Success
+ * * %-EINVAL:		- Invalid @batch_size argument
+ * * %-ENOMEM:		- Out of memory
+ */
+int percpu_counter_tree_init_many(struct percpu_counter_tree *counters, struct percpu_counter_tree_level_item *items,
+				  unsigned int nr_counters, unsigned long batch_size, gfp_t gfp_flags)
+{
+	void __percpu *level0, *level0_iter;
+	size_t counter_size = sizeof(*counters->level0),
+	       items_size = percpu_counter_tree_items_size();
+	void *items_iter;
+	unsigned int i;
+	int ret;
+
+	memset(items, 0, items_size * nr_counters);
+	level0 = __alloc_percpu_gfp(nr_counters * counter_size,
+				    __alignof__(*counters->level0), gfp_flags);
+	if (!level0)
+		return -ENOMEM;
+	level0_iter = level0;
+	items_iter = items;
+	for (i = 0; i < nr_counters; i++) {
+		ret = __percpu_counter_tree_init(&counters[i], batch_size, gfp_flags, level0_iter, items_iter);
+		if (ret)
+			goto free_level0;
+		level0_iter += counter_size;
+		items_iter += items_size;
+	}
+	return 0;
+
+free_level0:
+	free_percpu(level0);
+	return ret;
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_init_many);
+
+/**
+ * percpu_counter_tree_init() - Initialize one per-CPU counter tree.
+ * @counter: Counter to initialize.
+ *	     Its memory is provided by the caller.
+ * @items: Pointer to memory area where to store tree items.
+ *	   This memory is provided by the caller.
+ *	   Its size needs to be at least percpu_counter_tree_items_size().
+ * @batch_size: The batch size is the increment step at level 0 which triggers a
+ * 		carry propagation.
+ *		The batch size is required to be greater than 1, and a power of 2.
+ * @gfp_flags: gfp flags to pass to the per-CPU allocator.
+ *
+ * Initialize one per-CPU counter tree.
+ *
+ * Return:
+ * * %0: Success
+ * * %-EINVAL:		- Invalid @batch_size argument
+ * * %-ENOMEM:		- Out of memory
+ */
+int percpu_counter_tree_init(struct percpu_counter_tree *counter, struct percpu_counter_tree_level_item *items,
+			     unsigned long batch_size, gfp_t gfp_flags)
+{
+	return percpu_counter_tree_init_many(counter, items, 1, batch_size, gfp_flags);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_init);
+
+/**
+ * percpu_counter_tree_destroy_many() - Destroy many per-CPU counter trees.
+ * @counters: Array of counters trees to destroy.
+ * @nr_counters: The number of counter trees to destroy.
+ *
+ * Release internal resources allocated for @nr_counters per-CPU counter trees.
+ */
+
+void percpu_counter_tree_destroy_many(struct percpu_counter_tree *counters, unsigned int nr_counters)
+{
+	free_percpu(counters->level0);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_destroy_many);
+
+/**
+ * percpu_counter_tree_destroy() - Destroy one per-CPU counter tree.
+ * @counter: Counter to destroy.
+ *
+ * Release internal resources allocated for one per-CPU counter tree.
+ */
+void percpu_counter_tree_destroy(struct percpu_counter_tree *counter)
+{
+	return percpu_counter_tree_destroy_many(counter, 1);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_destroy);
+
+static
+long percpu_counter_tree_carry(long orig, long res, long inc, unsigned long bit_mask)
+{
+	if (inc < 0) {
+		inc = -(-inc & ~(bit_mask - 1));
+		/*
+		 * xor bit_mask: underflow.
+		 *
+		 * If inc has bit set, decrement an additional bit if
+		 * there is _no_ bit transition between orig and res.
+		 * Else, inc has bit cleared, decrement an additional
+		 * bit if there is a bit transition between orig and
+		 * res.
+		 */
+		if ((inc ^ orig ^ res) & bit_mask)
+			inc -= bit_mask;
+	} else {
+		inc &= ~(bit_mask - 1);
+		/*
+		 * xor bit_mask: overflow.
+		 *
+		 * If inc has bit set, increment an additional bit if
+		 * there is _no_ bit transition between orig and res.
+		 * Else, inc has bit cleared, increment an additional
+		 * bit if there is a bit transition between orig and
+		 * res.
+		 */
+		if ((inc ^ orig ^ res) & bit_mask)
+			inc += bit_mask;
+	}
+	return inc;
+}
+
+/*
+ * It does not matter through which path the carry propagates up the
+ * tree, therefore there is no need to disable preemption because the
+ * cpu number is only used to favor cache locality.
+ */
+static
+void percpu_counter_tree_add_slowpath(struct percpu_counter_tree *counter, long inc)
+{
+	unsigned int level_items, nr_levels = counter_config->nr_levels,
+		     level, n_arity_order;
+	unsigned long bit_mask;
+	struct percpu_counter_tree_level_item *item = counter->items;
+	unsigned int cpu = raw_smp_processor_id();
+
+	WARN_ON_ONCE(!nr_cpus_order);	/* Should never be called for 1 cpu. */
+
+	n_arity_order = counter_config->n_arity_order[0];
+	bit_mask = counter->level0_bit_mask << n_arity_order;
+	level_items = 1U << (nr_cpus_order - n_arity_order);
+
+	for (level = 1; level < nr_levels; level++) {
+		/*
+		 * For the purpose of carry propagation, the
+		 * intermediate level counters only need to keep track
+		 * of the bits relevant for carry propagation. We
+		 * therefore don't care about higher order bits.
+		 * Note that this optimization is unwanted if the
+		 * intended use is to track counters within intermediate
+		 * levels of the topology.
+		 */
+		if (abs(inc) & (bit_mask - 1)) {
+			atomic_long_t *count = &item[cpu & (level_items - 1)].count;
+			unsigned long orig, res;
+
+			res = atomic_long_add_return_relaxed(inc, count);
+			orig = res - inc;
+			inc = percpu_counter_tree_carry(orig, res, inc, bit_mask);
+			if (likely(!inc))
+				return;
+		}
+		item += level_items;
+		n_arity_order = counter_config->n_arity_order[level];
+		level_items >>= n_arity_order;
+		bit_mask <<= n_arity_order;
+	}
+	atomic_long_add(inc, counter->approx_sum.a);
+}
+
+/**
+ * percpu_counter_tree_add() - Add to a per-CPU counter tree.
+ * @counter: Counter added to.
+ * @inc: Increment value (either positive or negative).
+ *
+ * Add @inc to a per-CPU counter tree. This is a fast-path which will
+ * typically increment per-CPU counters as long as there is no carry
+ * greater or equal to the counter tree batch size.
+ */
+void percpu_counter_tree_add(struct percpu_counter_tree *counter, long inc)
+{
+	unsigned long bit_mask = counter->level0_bit_mask, orig, res;
+
+	res = this_cpu_add_return(*counter->level0, inc);
+	orig = res - inc;
+	inc = percpu_counter_tree_carry(orig, res, inc, bit_mask);
+	if (likely(!inc))
+		return;
+	percpu_counter_tree_add_slowpath(counter, inc);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_add);
+
+static
+long percpu_counter_tree_precise_sum_unbiased(struct percpu_counter_tree *counter)
+{
+	unsigned long sum = 0;
+	int cpu;
+
+	for_each_possible_cpu(cpu)
+		sum += *per_cpu_ptr(counter->level0, cpu);
+	return (long) sum;
+}
+
+/**
+ * percpu_counter_tree_precise_sum() - Return precise counter sum.
+ * @counter: The counter to sum.
+ *
+ * Querying the precise sum is relatively expensive because it needs to
+ * iterate over all CPUs.
+ * This is meant to be used when accuracy is preferred over speed.
+ *
+ * Return: The current precise counter sum.
+ */
+long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter)
+{
+	return percpu_counter_tree_precise_sum_unbiased(counter) + READ_ONCE(counter->bias);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_sum);
+
+static
+int compare_delta(long delta, unsigned long accuracy_neg, unsigned long accuracy_pos)
+{
+	if (delta >= 0) {
+		if (delta <= accuracy_pos)
+			return 0;
+		else
+			return 1;
+	} else {
+		if (-delta <= accuracy_neg)
+			return 0;
+		else
+			return -1;
+	}
+}
+
+/**
+ * percpu_counter_tree_approximate_compare - Approximated comparison of two counter trees.
+ * @a: First counter to compare.
+ * @b: Second counter to compare.
+ *
+ * Evaluate an approximate comparison of two counter trees.
+ * This approximation comparison is fast, and provides an accurate
+ * answer if the counters are found to be either less than or greater
+ * than the other. However, if the approximated comparison returns
+ * 0, the counters respective sums are found to be within the two
+ * counters accuracy range.
+ *
+ * Return:
+ * * %0		- Counters @a and @b do not differ by more than the sum of their respective
+ *                accuracy ranges.
+ * * %-1	- Counter @a less than counter @b.
+ * * %1		- Counter @a is greater than counter @b.
+ */
+int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+	return compare_delta(percpu_counter_tree_approximate_sum(a) - percpu_counter_tree_approximate_sum(b),
+			     a->approx_accuracy_range.over + b->approx_accuracy_range.under,
+			     a->approx_accuracy_range.under + b->approx_accuracy_range.over);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_approximate_compare);
+
+/**
+ * percpu_counter_tree_approximate_compare_value - Approximated comparison of a counter tree against a given value.
+ * @counter: Counter to compare.
+ * @v: Value to compare.
+ *
+ * Evaluate an approximate comparison of a counter tree against a given value.
+ * This approximation comparison is fast, and provides an accurate
+ * answer if the counter is found to be either less than or greater
+ * than the value. However, if the approximated comparison returns
+ * 0, the value is within the counter accuracy range.
+ *
+ * Return:
+ * * %0		- The value @v is within the accuracy range of the counter.
+ * * %-1	- The value @v is less than the counter.
+ * * %1		- The value @v is greater than the counter.
+ */
+int percpu_counter_tree_approximate_compare_value(struct percpu_counter_tree *counter, long v)
+{
+	return compare_delta(v - percpu_counter_tree_approximate_sum(counter),
+			     counter->approx_accuracy_range.under,
+			     counter->approx_accuracy_range.over);
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_approximate_compare_value);
+
+/**
+ * percpu_counter_tree_precise_compare - Precise comparison of two counter trees.
+ * @a: First counter to compare.
+ * @b: Second counter to compare.
+ *
+ * Evaluate a precise comparison of two counter trees.
+ * As an optimization, it uses the approximate counter comparison
+ * to quickly compare counters which are far apart. Only cases where
+ * counter sums are within the accuracy range require precise counter
+ * sums.
+ *
+ * Return:
+ * * %0		- Counters are equal.
+ * * %-1	- Counter @a less than counter @b.
+ * * %1		- Counter @a is greater than counter @b.
+ */
+int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
+{
+	long count_a = percpu_counter_tree_approximate_sum(a),
+	     count_b = percpu_counter_tree_approximate_sum(b);
+	unsigned long accuracy_a, accuracy_b;
+	long delta = count_a - count_b;
+	int res;
+
+	res = compare_delta(delta,
+			    a->approx_accuracy_range.over + b->approx_accuracy_range.under,
+			    a->approx_accuracy_range.under + b->approx_accuracy_range.over);
+	/* The values are distanced enough for an accurate approximated comparison. */
+	if (res)
+		return res;
+
+	/*
+	 * The approximated comparison is within the accuracy range, therefore at least one
+	 * precise sum is needed. Sum the counter which has the largest accuracy first.
+	 */
+	if (delta >= 0) {
+		accuracy_a = a->approx_accuracy_range.under;
+		accuracy_b = b->approx_accuracy_range.over;
+	} else {
+		accuracy_a = a->approx_accuracy_range.over;
+		accuracy_b = b->approx_accuracy_range.under;
+	}
+	if (accuracy_b < accuracy_a) {
+		count_a = percpu_counter_tree_precise_sum(a);
+		res = compare_delta(count_a - count_b,
+				    b->approx_accuracy_range.under,
+				    b->approx_accuracy_range.over);
+		if (res)
+			return res;
+		/* Precise sum of second counter is required. */
+		count_b = percpu_counter_tree_precise_sum(b);
+	} else {
+		count_b = percpu_counter_tree_precise_sum(b);
+		res = compare_delta(count_a - count_b,
+				    a->approx_accuracy_range.over,
+				    a->approx_accuracy_range.under);
+		if (res)
+			return res;
+		/* Precise sum of second counter is required. */
+		count_a = percpu_counter_tree_precise_sum(a);
+	}
+	if (count_a - count_b < 0)
+		return -1;
+	if (count_a - count_b > 0)
+		return 1;
+	return 0;
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_compare);
+
+/**
+ * percpu_counter_tree_precise_compare_value - Precise comparison of a counter tree against a given value.
+ * @counter: Counter to compare.
+ * @v: Value to compare.
+ *
+ * Evaluate a precise comparison of a counter tree against a given value.
+ * As an optimization, it uses the approximate counter comparison
+ * to quickly identify whether the counter and value are far apart.
+ * Only cases where the value is within the counter accuracy range
+ * require a precise counter sum.
+ *
+ * Return:
+ * * %0		- The value @v is equal to the counter.
+ * * %-1	- The value @v is less than the counter.
+ * * %1		- The value @v is greater than the counter.
+ */
+int percpu_counter_tree_precise_compare_value(struct percpu_counter_tree *counter, long v)
+{
+	long count = percpu_counter_tree_approximate_sum(counter);
+	int res;
+
+	res = compare_delta(v - count,
+			    counter->approx_accuracy_range.under,
+			    counter->approx_accuracy_range.over);
+	/* The values are distanced enough for an accurate approximated comparison. */
+	if (res)
+		return res;
+
+	/* Precise sum is required. */
+	count = percpu_counter_tree_precise_sum(counter);
+	if (v - count < 0)
+		return -1;
+	if (v - count > 0)
+		return 1;
+	return 0;
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_compare_value);
+
+static
+void percpu_counter_tree_set_bias(struct percpu_counter_tree *counter, long bias)
+{
+	WRITE_ONCE(counter->bias, bias);
+}
+
+/**
+ * percpu_counter_tree_set - Set the counter tree sum to a given value.
+ * @counter: Counter to set.
+ * @v: Value to set.
+ *
+ * Set the counter sum to a given value. It can be useful for instance
+ * to reset the counter sum to 0. Note that even after setting the
+ * counter sum to a given value, the counter sum approximation can
+ * return any value within the accuracy range around that value.
+ */
+void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v)
+{
+	percpu_counter_tree_set_bias(counter,
+				     v - percpu_counter_tree_precise_sum_unbiased(counter));
+}
+EXPORT_SYMBOL_GPL(percpu_counter_tree_set);
+
+/* Initialize to SIZE_MAX to catch early boot misuses. */
+size_t __percpu_counter_tree_items_size __ro_after_init = SIZE_MAX;
+EXPORT_SYMBOL_GPL(__percpu_counter_tree_items_size);
+
+static void __init calculate_accuracy_topology(void)
+{
+	unsigned int nr_levels = counter_config->nr_levels, level;
+	unsigned int level_items = 1U << nr_cpus_order;
+	unsigned long batch_size = 1;
+
+	for (level = 0; level < nr_levels; level++) {
+		unsigned int n_arity_order = counter_config->n_arity_order[level];
+
+		/*
+		 * The accuracy multiplier is derived from a batch size of 1
+		 * to speed up calculating the accuracy at tree initialization.
+		 */
+		accuracy_multiplier += batch_size * level_items;
+		batch_size <<= n_arity_order;
+		level_items >>= n_arity_order;
+	}
+}
+
+int __init percpu_counter_tree_subsystem_init(void)
+{
+	nr_cpus_order = get_count_order(nr_cpu_ids);
+	if (WARN_ON_ONCE(nr_cpus_order >= ARRAY_SIZE(per_nr_cpu_order_config))) {
+		printk(KERN_ERR "Unsupported number of CPUs (%u)\n", nr_cpu_ids);
+		return -1;
+	}
+	counter_config = &per_nr_cpu_order_config[nr_cpus_order];
+	if (!nr_cpus_order)
+		__percpu_counter_tree_items_size = 0;
+	else
+		__percpu_counter_tree_items_size = counter_config->nr_items *
+			sizeof(struct percpu_counter_tree_level_item);
+	calculate_accuracy_topology();
+	return 0;
+}
diff --git a/lib/tests/Makefile b/lib/tests/Makefile
index 3cac3b63a7522..051e73705977b 100644
--- a/lib/tests/Makefile
+++ b/lib/tests/Makefile
@@ -58,4 +58,6 @@ obj-$(CONFIG_UTIL_MACROS_KUNIT) += util_macros_kunit.o
 obj-$(CONFIG_RATELIMIT_KUNIT_TEST) += test_ratelimit.o
 obj-$(CONFIG_UUID_KUNIT_TEST) += uuid_kunit.o
 
+obj-$(CONFIG_PERCPU_COUNTER_TREE_KUNIT_TEST) += percpu_counter_tree_kunit.o
+
 obj-$(CONFIG_TEST_RUNTIME_MODULE)		+= module/
diff --git a/lib/tests/percpu_counter_tree_kunit.c b/lib/tests/percpu_counter_tree_kunit.c
new file mode 100644
index 0000000000000..a79176655c4b0
--- /dev/null
+++ b/lib/tests/percpu_counter_tree_kunit.c
@@ -0,0 +1,399 @@
+// SPDX-License-Identifier: GPL-2.0+ OR MIT
+// SPDX-FileCopyrightText: 2026 Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
+
+#include <kunit/test.h>
+#include <linux/percpu_counter_tree.h>
+#include <linux/kthread.h>
+#include <linux/wait.h>
+#include <linux/random.h>
+
+struct multi_thread_test_data {
+	long increment;
+	int nr_inc;
+	int counter_index;
+};
+
+#define NR_COUNTERS	2
+
+/* Hierarchical per-CPU counter instances. */
+static struct percpu_counter_tree counter[NR_COUNTERS];
+static struct percpu_counter_tree_level_item *items;
+
+/* Global atomic counters for validation. */
+static atomic_long_t global_counter[NR_COUNTERS];
+
+static DECLARE_WAIT_QUEUE_HEAD(kernel_threads_wq);
+static atomic_t kernel_threads_to_run;
+
+static void complete_work(void)
+{
+	if (atomic_dec_and_test(&kernel_threads_to_run))
+		wake_up(&kernel_threads_wq);
+}
+
+static void hpcc_print_info(struct kunit *test)
+{
+	kunit_info(test, "Running test with %d CPUs\n", num_online_cpus());
+}
+
+static void add_to_counter(int counter_index, unsigned int nr_inc, long increment)
+{
+	unsigned int i;
+
+	for (i = 0; i < nr_inc; i++) {
+		percpu_counter_tree_add(&counter[counter_index], increment);
+		atomic_long_add(increment, &global_counter[counter_index]);
+	}
+}
+
+static void check_counters(struct kunit *test)
+{
+	int counter_index;
+
+	/* Compare each counter with its global counter. */
+	for (counter_index = 0; counter_index < NR_COUNTERS; counter_index++) {
+		long v = atomic_long_read(&global_counter[counter_index]);
+		long approx_sum = percpu_counter_tree_approximate_sum(&counter[counter_index]);
+		unsigned long under_accuracy = 0, over_accuracy = 0;
+		long precise_min, precise_max;
+
+		/* Precise comparison. */
+		KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&counter[counter_index]), v);
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_precise_compare_value(&counter[counter_index], v));
+
+		/* Approximate comparison. */
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&counter[counter_index], v));
+
+		/* Accuracy limits checks. */
+		percpu_counter_tree_approximate_accuracy_range(&counter[counter_index], &under_accuracy, &over_accuracy);
+
+		KUNIT_EXPECT_GE(test, (long)(approx_sum - (v - under_accuracy)), 0);
+		KUNIT_EXPECT_LE(test, (long)(approx_sum - (v + over_accuracy)), 0);
+		KUNIT_EXPECT_GT(test, (long)(approx_sum - (v - under_accuracy - 1)), 0);
+		KUNIT_EXPECT_LT(test, (long)(approx_sum - (v + over_accuracy + 1)), 0);
+
+		/* Precise min/max range check. */
+		percpu_counter_tree_approximate_min_max_range(approx_sum, under_accuracy, over_accuracy, &precise_min, &precise_max);
+
+		KUNIT_EXPECT_GE(test, v - precise_min, 0);
+		KUNIT_EXPECT_LE(test, v - precise_max, 0);
+		KUNIT_EXPECT_GT(test, v - (precise_min - 1), 0);
+		KUNIT_EXPECT_LT(test, v - (precise_max + 1), 0);
+	}
+	/* Compare each counter with the second counter. */
+	KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&counter[0]), percpu_counter_tree_precise_sum(&counter[1]));
+	KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_precise_compare(&counter[0], &counter[1]));
+	KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare(&counter[0], &counter[1]));
+}
+
+static int multi_thread_worker_fn(void *data)
+{
+	struct multi_thread_test_data *td = data;
+
+	add_to_counter(td->counter_index, td->nr_inc, td->increment);
+	complete_work();
+	kfree(td);
+	return 0;
+}
+
+static void test_run_on_specific_cpu(struct kunit *test, int target_cpu, int counter_index, unsigned int nr_inc, long increment)
+{
+	struct task_struct *task;
+	struct multi_thread_test_data *td = kzalloc(sizeof(struct multi_thread_test_data), GFP_KERNEL);
+
+	KUNIT_EXPECT_PTR_NE(test, td, NULL);
+	td->increment = increment;
+	td->nr_inc = nr_inc;
+	td->counter_index = counter_index;
+	atomic_inc(&kernel_threads_to_run);
+	task = kthread_run_on_cpu(multi_thread_worker_fn, td, target_cpu, "kunit_multi_thread_worker");
+	KUNIT_ASSERT_NOT_ERR_OR_NULL(test, task);
+}
+
+static void init_kthreads(void)
+{
+	atomic_set(&kernel_threads_to_run, 1);
+}
+
+static void fini_kthreads(void)
+{
+	/* Release our own reference. */
+	complete_work();
+	/* Wait for all others threads to run. */
+	wait_event(kernel_threads_wq, (atomic_read(&kernel_threads_to_run) == 0));
+}
+
+static void test_sync_kthreads(void)
+{
+	fini_kthreads();
+	init_kthreads();
+}
+
+static void init_counters(struct kunit *test, unsigned long batch_size)
+{
+	int i, ret;
+
+	items = kzalloc(percpu_counter_tree_items_size() * NR_COUNTERS, GFP_KERNEL);
+	KUNIT_EXPECT_PTR_NE(test, items, NULL);
+	ret = percpu_counter_tree_init_many(counter, items, NR_COUNTERS, batch_size, GFP_KERNEL);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+
+	for (i = 0; i < NR_COUNTERS; i++)
+		atomic_long_set(&global_counter[i], 0);
+}
+
+static void fini_counters(void)
+{
+	percpu_counter_tree_destroy_many(counter, NR_COUNTERS);
+	kfree(items);
+}
+
+enum up_test_inc_type {
+	INC_ONE,
+	INC_MINUS_ONE,
+	INC_RANDOM,
+};
+
+/*
+ * Single-threaded tests. Those use many threads to run on various CPUs,
+ * but synchronize for completion of each thread before running the
+ * next, effectively making sure there are no concurrent updates.
+ */
+static void do_hpcc_test_single_thread(struct kunit *test, int _cpu0, int _cpu1, enum up_test_inc_type type)
+{
+	unsigned long batch_size_order = 5;
+	int cpu0 = _cpu0;
+	int cpu1 = _cpu1;
+	int i;
+
+	init_counters(test, 1UL << batch_size_order);
+	init_kthreads();
+	for (i = 0; i < 10000; i++) {
+		long increment;
+
+		switch (type) {
+		case INC_ONE:
+			increment = 1;
+			break;
+		case INC_MINUS_ONE:
+			increment = -1;
+			break;
+		case INC_RANDOM:
+			increment = (long) get_random_long() % 50000;
+			break;
+		}
+		if (_cpu0 < 0)
+			cpu0 = cpumask_any_distribute(cpu_online_mask);
+		if (_cpu1 < 0)
+			cpu1 = cpumask_any_distribute(cpu_online_mask);
+		test_run_on_specific_cpu(test, cpu0, 0, 1, increment);
+		test_sync_kthreads();
+		test_run_on_specific_cpu(test, cpu1, 1, 1, increment);
+		test_sync_kthreads();
+		check_counters(test);
+	}
+	fini_kthreads();
+	fini_counters();
+}
+
+static void hpcc_test_single_thread_first(struct kunit *test)
+{
+	int cpu = cpumask_first(cpu_online_mask);
+
+	do_hpcc_test_single_thread(test, cpu, cpu, INC_ONE);
+	do_hpcc_test_single_thread(test, cpu, cpu, INC_MINUS_ONE);
+	do_hpcc_test_single_thread(test, cpu, cpu, INC_RANDOM);
+}
+
+static void hpcc_test_single_thread_first_random(struct kunit *test)
+{
+	int cpu = cpumask_first(cpu_online_mask);
+
+	do_hpcc_test_single_thread(test, cpu, -1, INC_ONE);
+	do_hpcc_test_single_thread(test, cpu, -1, INC_MINUS_ONE);
+	do_hpcc_test_single_thread(test, cpu, -1, INC_RANDOM);
+}
+
+static void hpcc_test_single_thread_random(struct kunit *test)
+{
+	do_hpcc_test_single_thread(test, -1, -1, INC_ONE);
+	do_hpcc_test_single_thread(test, -1, -1, INC_MINUS_ONE);
+	do_hpcc_test_single_thread(test, -1, -1, INC_RANDOM);
+}
+
+/* Multi-threaded SMP tests. */
+
+static void do_hpcc_multi_thread_increment_each_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+	int cpu;
+
+	init_counters(test, batch_size);
+	init_kthreads();
+	for_each_online_cpu(cpu) {
+		test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+		test_run_on_specific_cpu(test, cpu, 1, nr_inc, increment);
+	}
+	fini_kthreads();
+	check_counters(test);
+	fini_counters();
+}
+
+static void do_hpcc_multi_thread_increment_even_cpus(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+	int cpu;
+
+	init_counters(test, batch_size);
+	init_kthreads();
+	for_each_online_cpu(cpu) {
+		test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+		test_run_on_specific_cpu(test, cpu & ~1, 1, nr_inc, increment); /* even cpus. */
+	}
+	fini_kthreads();
+	check_counters(test);
+	fini_counters();
+}
+
+static void do_hpcc_multi_thread_increment_single_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+	int cpu;
+
+	init_counters(test, batch_size);
+	init_kthreads();
+	for_each_online_cpu(cpu) {
+		test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+		test_run_on_specific_cpu(test, cpumask_first(cpu_online_mask), 1, nr_inc, increment);
+	}
+	fini_kthreads();
+	check_counters(test);
+	fini_counters();
+}
+
+static void do_hpcc_multi_thread_increment_random_cpu(struct kunit *test, unsigned long batch_size, unsigned int nr_inc, long increment)
+{
+	int cpu;
+
+	init_counters(test, batch_size);
+	init_kthreads();
+	for_each_online_cpu(cpu) {
+		test_run_on_specific_cpu(test, cpu, 0, nr_inc, increment);
+		test_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);
+	}
+	fini_kthreads();
+	check_counters(test);
+	fini_counters();
+}
+
+static void hpcc_test_multi_thread_batch_increment(struct kunit *test)
+{
+	unsigned long batch_size_order;
+
+	for (batch_size_order = 2; batch_size_order < 10; batch_size_order++) {
+		unsigned int nr_inc;
+
+		for (nr_inc = 1; nr_inc < 1024; nr_inc *= 2) {
+			long increment;
+
+			for (increment = 1; increment < 100000; increment *= 10) {
+				do_hpcc_multi_thread_increment_each_cpu(test, 1UL << batch_size_order, nr_inc, increment);
+				do_hpcc_multi_thread_increment_even_cpus(test, 1UL << batch_size_order, nr_inc, increment);
+				do_hpcc_multi_thread_increment_single_cpu(test, 1UL << batch_size_order, nr_inc, increment);
+				do_hpcc_multi_thread_increment_random_cpu(test, 1UL << batch_size_order, nr_inc, increment);
+			}
+		}
+	}
+}
+
+static void hpcc_test_multi_thread_random_walk(struct kunit *test)
+{
+	unsigned long batch_size_order = 5;
+	int loop;
+
+	for (loop = 0; loop < 100; loop++) {
+		int i;
+
+		init_counters(test, 1UL << batch_size_order);
+		init_kthreads();
+		for (i = 0; i < 1000; i++) {
+			long increment = (long) get_random_long() % 512;
+			unsigned int nr_inc = ((unsigned long) get_random_long()) % 1024;
+
+			test_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 0, nr_inc, increment);
+			test_run_on_specific_cpu(test, cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);
+		}
+		fini_kthreads();
+		check_counters(test);
+		fini_counters();
+	}
+}
+
+static void hpcc_test_init_one(struct kunit *test)
+{
+	struct percpu_counter_tree pct;
+	struct percpu_counter_tree_level_item *counter_items;
+	int ret;
+
+	counter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);
+	KUNIT_EXPECT_PTR_NE(test, counter_items, NULL);
+	ret = percpu_counter_tree_init(&pct, counter_items, 32, GFP_KERNEL);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+
+	percpu_counter_tree_destroy(&pct);
+	kfree(counter_items);
+}
+
+static void hpcc_test_set(struct kunit *test)
+{
+	static long values[] = {
+		5, 100, 127, 128, 255, 256, 4095, 4096, 500000, 0,
+		-5, -100, -127, -128, -255, -256, -4095, -4096, -500000,
+	};
+	struct percpu_counter_tree pct;
+	struct percpu_counter_tree_level_item *counter_items;
+	int i, ret;
+
+	counter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);
+	KUNIT_EXPECT_PTR_NE(test, counter_items, NULL);
+	ret = percpu_counter_tree_init(&pct, counter_items, 32, GFP_KERNEL);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+
+	for (i = 0; i < ARRAY_SIZE(values); i++) {
+		long v = values[i];
+
+		percpu_counter_tree_set(&pct, v);
+		KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&pct), v);
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&pct, v));
+
+		percpu_counter_tree_add(&pct, v);
+		KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&pct), 2 * v);
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&pct, 2 * v));
+
+		percpu_counter_tree_add(&pct, -2 * v);
+		KUNIT_EXPECT_EQ(test, percpu_counter_tree_precise_sum(&pct), 0);
+		KUNIT_EXPECT_EQ(test, 0, percpu_counter_tree_approximate_compare_value(&pct, 0));
+	}
+
+	percpu_counter_tree_destroy(&pct);
+	kfree(counter_items);
+}
+
+static struct kunit_case hpcc_test_cases[] = {
+	KUNIT_CASE(hpcc_print_info),
+	KUNIT_CASE(hpcc_test_single_thread_first),
+	KUNIT_CASE(hpcc_test_single_thread_first_random),
+	KUNIT_CASE(hpcc_test_single_thread_random),
+	KUNIT_CASE(hpcc_test_multi_thread_batch_increment),
+	KUNIT_CASE(hpcc_test_multi_thread_random_walk),
+	KUNIT_CASE(hpcc_test_init_one),
+	KUNIT_CASE(hpcc_test_set),
+	{}
+};
+
+static struct kunit_suite hpcc_test_suite = {
+	.name = "percpu_counter_tree",
+	.test_cases = hpcc_test_cases,
+};
+
+kunit_test_suite(hpcc_test_suite);
+
+MODULE_DESCRIPTION("Test cases for hierarchical per-CPU counters");
+MODULE_LICENSE("Dual MIT/GPL");

9/3 2026/09/02 08:37 llm kmsan-evaluator
0m Model:
gemini-3.7-flash

Args:
null

Results:
null

Tokens:
							input: 26134
							output: 18
							thoughts: 929
						

Thoughts:
**KMSAN Fuzzing Evaluation for Hierarchical Per-CPU Counters Patch**

Okay, let's break this down. My goal is to determine if this patch, which introduces the `percpu_counter_tree` structure, necessitates KMSAN fuzzing. I need to be thorough.

First, I see the core of the change: a new hierarchical per-CPU counter data structure and its integration into `mm_struct`. This replaces the existing `percpu_counter` array with a `percpu_counter_tree` array, specifically `rss_stat[NR_MM_COUNTERS]`. This means memory management and accounting are being fundamentally altered. The code introduces functions to initialize, allocate, destroy, and manage this new tree structure. There are updates in mm/fork.c to allocate, initialize, and destroy the rss_stat tree items in functions like mm_init, mm_cache_init, __mmdrop and check_mm. Importantly, KUnit tests have been included, which is a good sign but doesn't preclude the need for more testing.

My immediate concern is uninitialized memory and potential information leaks. That's where KMSAN becomes relevant. I need to assess how the new data structure is initialized and used.

Looking at `percpu_counter_tree_init_many`, I see `memset(items, 0, ...)` which zeros the `items` structure, good. `__alloc_percpu_gfp` also allocates per-CPU memory which is likely zero-initialized by default. The init function also sets the batch size, bias, level0 pointer and more. This seems like a reasonable initialization strategy.

I also notice that in the UP configuration, there's a simple initialization using `atomic_long_set`, which is also a zero-initialization of each counter. Good.

Now, the `mm_struct` part. I see a `flexible_array` which is initialized. The `MM_STRUCT_FLEXIBLE_ARRAY_INIT` call is likely zeroing out the static array, ensuring clean initial state for init_mm. The `kmem_cache_create_usercopy` function is creating a slab cache for `mm_struct`, and the size calculation includes the space for the new per-CPU counter tree. A key question is whether allocations from this cache, via `allocate_mm` (or ultimately, `kmem_cache_alloc`) are zero-initialized. *I'll need to double check how the `mm_struct` is allocated in `fork.c` or elsewhere.* I'll search the code base for uses of `allocate_mm` and `kmem_cache_alloc` with the `mm_cachep` object to confirm the allocation path. This will show how the `mm_struct` is allocated and initialized, if it is zalloc or not.

In conclusion, while the patch *appears* to have robust initialization practices, I still have an outstanding question about the allocation of `mm_struct` itself. If the allocation path leads to `kmem_cache_alloc` without zeroing, there *could* be a risk, and KMSAN fuzzing would be warranted. However, if allocation uses `kmem_cache_zalloc`, or some other mechanism guaranteeing zeroed memory, the risk is significantly reduced. My next step is to trace the allocation path of `mm_struct`.



10/3 2026/09/02 08:37 tool grepper
0m Args:
{
  "Expression": "mm_cachep"
}

Results:
{
  "Output": "kernel/fork.c=485=struct kmem_cache *fs_cachep;\n--\nkernel/fork.c-487-/* SLAB cache for mm_struct structures (tsk-\u003emm) */\nkernel/fork.c:488:static struct kmem_cache *mm_cachep;\nkernel/fork.c-489-\n--\nkernel/fork.c=633=static void check_mm(struct mm_struct *mm)\n--\nkernel/fork.c-657-\nkernel/fork.c:658:#define allocate_mm()\t(kmem_cache_alloc(mm_cachep, GFP_KERNEL))\nkernel/fork.c:659:#define free_mm(mm)\t(kmem_cache_free(mm_cachep, (mm)))\nkernel/fork.c-660-\n--\nkernel/fork.c=3120=void __init mm_cache_init(void)\n--\nkernel/fork.c-3132-\nkernel/fork.c:3133:\tmm_cachep = kmem_cache_create_usercopy(\"mm_struct\",\nkernel/fork.c-3134-\t\t\tmm_size, ARCH_MIN_MMSTRUCT_ALIGN,\n"
}

11/3 2026/09/02 08:37 llm kmsan-evaluator
0m Model:
gemini-3.7-flash

Args:
null

Results:
null

Tokens:
							input: 28108
							output: 32
							thoughts: 23
						

Thoughts:
Here's my take on those thoughts, tailored for an expert audience:

**Kernel Memory Management - Diving In**

Okay, so I'm thinking, where's the best place to start debugging this memory-related issue? My gut instinct is leaning towards how memory is handled during the `fork` system call, particularly the duplication and initialization of the memory management structures for the new process. So, I'm going to jump into `kernel/fork.c`. Specifically, I want to zero in on how `dup_mm` or `mm_init` functions are implemented. A potential bug in memory duplication during fork is a classic source of problems, and these functions are where that magic happens. I need to understand what's happening at the lowest level, how the page tables are set up, and whether the reference counts are getting handled correctly. Let's see if that's where the gremlins are hiding.



12/3 2026/09/02 08:37 tool grepper
0m Args:
{
  "Expression": "dup_mm|mm_init",
  "PathPrefix": "kernel/fork.c"
}

Results:
{
  "Output": "kernel/fork.c-119-\nkernel/fork.c:120:/* For dup_mmap(). */\nkernel/fork.c-121-#include \"../mm/internal.h\"\n--\nkernel/fork.c=569=EXPORT_SYMBOL(free_task);\nkernel/fork.c-570-\nkernel/fork.c:571:void dup_mm_exe_file(struct mm_struct *mm, struct mm_struct *oldmm)\nkernel/fork.c-572-{\n--\nkernel/fork.c=1050=__setup(\"coredump_filter=\", coredump_filter_setup);\n--\nkernel/fork.c-1053-\nkernel/fork.c:1054:static void mm_init_aio(struct mm_struct *mm)\nkernel/fork.c-1055-{\n--\nkernel/fork.c=1062=static __always_inline void mm_clear_owner(struct mm_struct *mm,\n--\nkernel/fork.c-1070-\nkernel/fork.c:1071:static void mm_init_owner(struct mm_struct *mm, struct task_struct *p)\nkernel/fork.c-1072-{\n--\nkernel/fork.c-1077-\nkernel/fork.c:1078:static void mm_init_uprobes_state(struct mm_struct *mm)\nkernel/fork.c-1079-{\n--\nkernel/fork.c=1085=static void mmap_init_lock(struct mm_struct *mm)\n--\nkernel/fork.c-1093-\nkernel/fork.c:1094:static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)\nkernel/fork.c-1095-{\n--\nkernel/fork.c-1109-\tspin_lock_init(\u0026mm-\u003earg_lock);\nkernel/fork.c:1110:\tmm_init_cpumask(mm);\nkernel/fork.c:1111:\tmm_init_aio(mm);\nkernel/fork.c:1112:\tmm_init_owner(mm, p);\nkernel/fork.c-1113-\tmm_pasid_init(mm);\n--\nkernel/fork.c-1119-#endif\nkernel/fork.c:1120:\tmm_init_uprobes_state(mm);\nkernel/fork.c-1121-\thugetlb_count_init(mm);\nkernel/fork.c:1122:\tfutex_mm_init(mm);\nkernel/fork.c-1123-\n--\nkernel/fork.c-1135-\tif (mm_alloc_pgd(mm))\nkernel/fork.c:1136:\t\tgoto fail_mm_init;\nkernel/fork.c-1137-\n--\nkernel/fork.c-1167-\tmm_free_pgd(mm);\nkernel/fork.c:1168:fail_mm_init:\nkernel/fork.c-1169-\tfree_mm(mm);\n--\nkernel/fork.c=1176=struct mm_struct *mm_alloc(void)\n--\nkernel/fork.c-1184-\tmemset(mm, 0, sizeof(*mm));\nkernel/fork.c:1185:\treturn mm_init(mm, current);\nkernel/fork.c-1186-}\n--\nkernel/fork.c=1515=void mm_exit_exec_release(struct task_struct *tsk, struct mm_struct *mm)\n--\nkernel/fork.c-1521-/**\nkernel/fork.c:1522: * dup_mm() - duplicates an existing mm structure\nkernel/fork.c-1523- * @tsk: the task_struct with which the new mm will be associated.\n--\nkernel/fork.c-1530- */\nkernel/fork.c:1531:static struct mm_struct *dup_mm(struct task_struct *tsk,\nkernel/fork.c-1532-\t\t\t\tstruct mm_struct *oldmm)\n--\nkernel/fork.c-1542-\nkernel/fork.c:1543:\tif (!mm_init(mm, tsk))\nkernel/fork.c-1544-\t\tgoto fail_nomem;\nkernel/fork.c-1545-\nkernel/fork.c:1546:\tuprobe_start_dup_mmap();\nkernel/fork.c:1547:\terr = dup_mmap(mm, oldmm);\nkernel/fork.c-1548-\tif (err)\nkernel/fork.c-1549-\t\tgoto free_pt;\nkernel/fork.c:1550:\tuprobe_end_dup_mmap();\nkernel/fork.c-1551-\n--\nkernel/fork.c-1562-\tmm-\u003ebinfmt = NULL;\nkernel/fork.c:1563:\tmm_init_owner(mm, NULL);\nkernel/fork.c-1564-\tmmput(mm);\nkernel/fork.c-1565-\tif (err)\nkernel/fork.c:1566:\t\tuprobe_end_dup_mmap();\nkernel/fork.c-1567-\n--\nkernel/fork.c=1572=static int copy_mm(u64 clone_flags, struct task_struct *tsk)\n--\nkernel/fork.c-1598-\t} else {\nkernel/fork.c:1599:\t\tmm = dup_mm(tsk, current-\u003emm);\nkernel/fork.c-1600-\t\tif (!mm)\n"
}

13/3 2026/09/02 08:37 llm kmsan-evaluator
0m Model:
gemini-3.7-flash

Args:
null

Results:
null

Tokens:
							input: 29802
							output: 34
							thoughts: 23
						

Thoughts:
Here's a summary of my thought process, as requested:

**Diving into `fork.c` - Lines 1140-1160**

Okay, I need to get a handle on what's happening within the `fork()` system call, specifically around lines 1140-1160 in `kernel/fork.c`. Given the granularity of this code region, my instinct is that this is a critical section or point of interest within the broader fork operation. I immediately start hypothesizing what it *could* be.

Is this the memory copy stage for the new process's page table? Could this be related to resource allocation, perhaps managing the new process's PID or file descriptors? Or is it more fundamental, dealing with the initialization of the process structure itself? The level of detail here could point to anything; it's likely a relatively self-contained, but important, operation within the larger context of a `fork`. I'm expecting to see calls to memory management functions or perhaps interactions with the process control block. This might be a prime spot for debugging memory leaks if I see something in here about memory usage. Let's see... I'm expecting to find the key to the mystery here, at least some of it, in this code.



14/3 2026/09/02 08:37 tool read-file
0m Args:
{
  "File": "kernel/fork.c",
  "FirstLine": 1135,
  "LineCount": 40
}

Results:
{
  "Contents": "1135:\t\tif (mm_alloc_pgd(mm))\n1136:\t\t\tgoto fail_mm_init;\n1137:\t\n1138:\t\tif (mm_alloc_id(mm))\n1139:\t\t\tgoto fail_noid;\n1140:\t\n1141:\t\tif (init_new_context(p, mm))\n1142:\t\t\tgoto fail_nocontext;\n1143:\t\n1144:\t\tif (mm_alloc_cid(mm, p))\n1145:\t\t\tgoto fail_cid;\n1146:\t\n1147:\t\tif (mm_alloc_sched(mm))\n1148:\t\t\tgoto fail_sched;\n1149:\t\n1150:\t\tif (percpu_counter_tree_init_many(mm-\u003erss_stat, get_rss_stat_items(mm),\n1151:\t\t\t\t\t\t  NR_MM_COUNTERS, RSS_STAT_BATCH_SIZE,\n1152:\t\t\t\t\t\t  GFP_KERNEL_ACCOUNT))\n1153:\t\t\tgoto fail_pcpu;\n1154:\t\n1155:\t\tlru_gen_init_mm(mm);\n1156:\t\treturn mm;\n1157:\t\n1158:\tfail_pcpu:\n1159:\t\tmm_destroy_sched(mm);\n1160:\tfail_sched:\n1161:\t\tmm_destroy_cid(mm);\n1162:\tfail_cid:\n1163:\t\tdestroy_context(mm);\n1164:\tfail_nocontext:\n1165:\t\tmm_free_id(mm);\n1166:\tfail_noid:\n1167:\t\tmm_free_pgd(mm);\n1168:\tfail_mm_init:\n1169:\t\tfree_mm(mm);\n1170:\t\treturn NULL;\n1171:\t}\n1172:\t\n1173:\t/*\n1174:\t * Allocate and initialize an mm_struct.\n"
}

15/3 2026/09/02 08:37 llm kmsan-evaluator
0m Model:
gemini-3.7-flash

Args:
null

Results:
null

Tokens:
							input: 30670
							output: 380
							thoughts: 886
						

Thoughts:
**KMSAN Assessment: Memory Management Structures**

Okay, let's break this down from a KMSAN perspective. We're looking at memory management data structures and if this patch introduces any risks of uninitialized memory being leaked to user space or used in critical conditional logic.

First, we see `percpu_counter_tree_init_many` being called to initialize `rss_stat`. This is where the core of the concern lies. However, it looks like `memset` is used on `items` and in UP mode, `counters[i].count` is zeroed. This means that at initialization, the percpu counters are guaranteed to be initialized. This is good.

Now, let's consider the four criteria KMSAN uses.
1. Kernel structures sent to userspace - No. `rss_stat` and `percpu_counter_tree` aren't *directly* copied to user space. We're only seeing numeric values (like RSS counts) exposed through things like `/proc/` which are formatted, not the raw structs.
2. Conditional logic on uninitialized fields - No. The code explicitly initializes all fields of `struct percpu_counter_tree` and the memory holding the counters is zeroed.
3. Allocation of complex data structures with uninitialized fields - No. Zero-initialization via `memset` or explicit assignment is happening for all fields within those data structures.
4. Bounds checks and lengths that expose uninitialized memory - No. KASAN would catch any out-of-bounds reads or writes.

I need to confirm all `percpu_counter_tree` fields are initialized during init. That's `batch_size`, `bias`, `level0`, `items`, `approx_sum.i`, `approx_sum.a`, `level0_bit_mask`, `approx_accuracy_range.under` and `approx_accuracy_range.over`.

There's the initialization of the `mm_struct`, via `memset` and `mm_init` and no direct copy to userspace.

Any potential memory errors? Well, there are no uninitialized memory bugs or kernel-to-user info-leaks here. KASAN should handle any out-of-bounds accesses or slab issues, and race conditions are KCSAN/LOCKDEP/KASAN territory.

So, based on this thorough review, this patch *doesn't* introduce any uninitialized memory risks that would warrant KMSAN. Standard debugging tools seem adequate.

Let's double-check all this.
Let's call `set-results`.



16/3 2026/09/02 08:38 tool set-results
0m Args:
{
  "KMSANReasoning": "The patch introduces Hierarchical Per-CPU Counters (HPCC / percpu_counter_tree) and transitions `mm_struct`'s RSS accounting (`rss_stat`) to use this new counter tree mechanism with storage placed in the flexible array of `mm_struct`.\n\nAnalyzing the changes for uninitialized memory risks and applicability of KMSAN vs KASAN:\n1. Initialization: All `percpu_counter_tree` structures and their associated tree items are explicitly initialized via `percpu_counter_tree_init_many()` (using `memset` to zero out the items buffer, zero-initialized per-cpu memory via `__alloc_percpu_gfp`, and explicit field initialization in `__percpu_counter_tree_init()`). On UP builds, `count` is initialized with `atomic_long_set(\u0026counters[i].count, 0)`.\n2. Userspace info-leaks: RSS statistics are numeric values accessed via `get_mm_counter()` and exposed as formatted integers (e.g. in `/proc/$pid/status` via `seq_printf`), rather than direct structure copies or uninitialized padding copies to user space.\n3. Memory safety risks: The primary potential risks in this patch involve memory sizing of the flexible array at the end of `mm_struct`, array index calculations during carry propagation, or concurrency issues. These classes of bugs (such as out-of-bounds reads/writes or use-after-free) are monitored and detected by KASAN and standard sanitizers.\n\nBecause no uninitialized memory branches or kernel-to-userspace leaks are introduced or exposed, a dedicated KMSAN fuzzing session is not warranted.",
  "NeedsKMSAN": false
}

Results:
{
  "KMSANReasoning": "The patch introduces Hierarchical Per-CPU Counters (HPCC / percpu_counter_tree) and transitions `mm_struct`'s RSS accounting (`rss_stat`) to use this new counter tree mechanism with storage placed in the flexible array of `mm_struct`.\n\nAnalyzing the changes for uninitialized memory risks and applicability of KMSAN vs KASAN:\n1. Initialization: All `percpu_counter_tree` structures and their associated tree items are explicitly initialized via `percpu_counter_tree_init_many()` (using `memset` to zero out the items buffer, zero-initialized per-cpu memory via `__alloc_percpu_gfp`, and explicit field initialization in `__percpu_counter_tree_init()`). On UP builds, `count` is initialized with `atomic_long_set(\u0026counters[i].count, 0)`.\n2. Userspace info-leaks: RSS statistics are numeric values accessed via `get_mm_counter()` and exposed as formatted integers (e.g. in `/proc/$pid/status` via `seq_printf`), rather than direct structure copies or uninitialized padding copies to user space.\n3. Memory safety risks: The primary potential risks in this patch involve memory sizing of the flexible array at the end of `mm_struct`, array index calculations during carry propagation, or concurrency issues. These classes of bugs (such as out-of-bounds reads/writes or use-after-free) are monitored and detected by KASAN and standard sanitizers.\n\nBecause no uninitialized memory branches or kernel-to-userspace leaks are introduced or exposed, a dedicated KMSAN fuzzing session is not warranted.",
  "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)