Skip to contentSkip to conversation

Hierarchical Percpu Counters for RSS

PATCH Superseded Mathieu Desnoyers 1 participant 11 messages Sep 4

Subsystems (8)

v22 of 25 Superseded Latest is v25 →

lore
Share & tools
lore

Mathieu Desnoyers

author reviewer
#0 lore raw

v22 cover Hierarchical Percpu Counters for RSS

Hi Andrew,

Here is the hierarchical percpu counters for RSS accounting series rebased on top of v7.3-rc1. It includes a series of documentation and test code fixes done to answer a review from Sashiko at:
https://sashiko.dev/#/patchset/[email protected]

This aims at replacing the prior version of the series you had in mm.

As a reminder, the goal here is to provide more precise RSS counters through /proc. A future step would be to also use these counters to speed up the OOM killer task selection when OOM is triggered by memcg. In whole-machine OOM situations, latency introduced by the OOM killer task selection may not be too much of an issue, but for memcg, where cgroups may routinely depend on the OOM killer, the acceptable latency tradeoff is quite different.

Thanks,

Mathieu

Mathieu Desnoyers (10):
lib: introduce hierarchical per-cpu counters
lib: test hierarchical per-cpu counters
mm: improve RSS counter approximation accuracy for proc interfaces
mm: reorder mm_struct flexible array to place mm_cpumask first
init: move percpu_counter_tree_subsystem_init() earlier in boot
lib: inline percpu_counter_tree_items_size with boot-safety sentinel lib/hpcc: Document that accuracy is a property of settled counters lib/hpcc: Clarify accuracy range documentation
lib/hpcc: Introduce wrapped delta helper
lib/tests/hpcc: Fix hotplug, module unload, and error handling

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
 .../core-api/percpu-counter-tree.rst          |  82 ++
 include/linux/mm.h                            |  20 +-
 include/linux/mm_types.h                      |  65 +-
 include/linux/percpu_counter_tree.h           | 391 +++++++++
 include/trace/events/kmem.h                   |   2 +-
 init/main.c                                   |   2 +
 kernel/fork.c                                 |  24 +-
 lib/Kconfig                                   |  12 +
 lib/Makefile                                  |   1 +
 lib/percpu_counter_tree.c                     | 747 ++++++++++++++++++
 lib/tests/Makefile                            |   2 +
 lib/tests/percpu_counter_tree_kunit.c         | 583 ++++++++++++++
 12 files changed, 1899 insertions(+), 32 deletions(-)
 create mode 100644 Documentation/core-api/percpu-counter-tree.rst
 create mode 100644 include/linux/percpu_counter_tree.h
 create mode 100644 lib/percpu_counter_tree.c
 create mode 100644 lib/tests/percpu_counter_tree_kunit.c
Signature · 1 line
2.43.0
author reviewer
#1 lore raw

PATCH v22 1/10 lib: introduce hierarchical per-cpu counters

This series introduces the hierarchical tree counter (hpcc) to increase accuracy of approximated RSS counters exposed through proc interfaces.

With a test program hopping across CPUs doing frequent mmap/munmap operations, the upstream implementation approximation reaches a 1GB delta from the precise value after a few minutes, compared to a 80MB delta with the hierarchical counter. The hierarchical counter provides a guaranteed maximum approximation inaccuracy of 192MB on that hardware topology.

* Motivation

The purpose of this hierarchical split-counter scheme is to:

- Minimize contention when incrementing and decrementing counters,
- Provide fast access to a sum approximation,
- Provide a sum approximation with an acceptable accuracy level when scaling to many-core systems.
- Provide approximate and precise comparison of two counters, and between a counter and a value.
- Provide possible precise sum ranges for a given sum approximation.

Its goals are twofold:

- Improve the accuracy of the approximated RSS counter values returned by proc interfaces [1],
- Reduce the latency of the OOM killer on large many-core systems.

* Design

The hierarchical per-CPU counters propagate a sum approximation through a N-way tree. When reaching the batch size, the carry is propagated through a binary tree which consists of logN(nr_cpu_ids) levels. The batch size for each level is twice the batch size of the prior level.

Example propagation diagram with 8 cpus through a binary tree:

Level 0:  0    1    2    3    4    5    6    7
          |   /     |   /     |   /     |   /
          |  /      |  /      |  /      |  /
          | /       | /       | /       | /
Level 1:  0         1         2         3
          |       /           |       /
          |    /              |    /
          | /                 | /
Level 2:  0                   1
          |               /
          |         /
          |   /
Level 3:  0

For a binary tree, the maximum inaccuracy is bound by:
batch_size * log2(nr_cpu_ids) * nr_cpu_ids
which evolves with O(n*log(n)) as the number of CPUs increases.

For a N-way tree, the maximum inaccuracy can be pre-calculated based on the the N-arity of each level and the batch size.

* Memory Use

The most important parts in terms of memory use are the per-cpu counters and the tree items which propagate the carry.

In the proposed implementation, the per-cpu counters are allocated within per-cpu data structures, so they end up using:

nr_possible_cpus * sizeof(unsigned long)

This is in addition to the tree items. The size of those items is defined by the per_nr_cpu_order_config table "nr_items" field. Each item is aligned on cacheline size (typically 64 bytes) to minimize false sharing.

Here is the footprint for a few nr_cpu_ids on a 64-bit arch:

nr_cpu_ids percpu counters (bytes) nr_items items size (bytes) total (bytes)

    2               16                     1                 64                    80
    4               32                     3                192                   224
    8               64                     7                448                   512
   64               512                   21               1344                  1856
  128              1024                   21               1344                  2368
  256              2048                   37               2368                  4416
  512              4096                   73               4672                  8768

There are of course various trade offs we can make here. We can:

* Increase the n-arity of the intermediate items to shrink the nr_items required for a given nr_cpus. This will increase contention of carry propagation across more cores.

* Remove cacheline alignment of intermediate tree items. This will shrink the memory needed for tree items, but will increase false sharing.

* Represent intermediate tree items on a byte rather than long. This further reduces the memory required for intermediate tree items, but further increases false sharing.

* Represent per-cpu counters on bytes rather than long. This makes the "sum" operation trickier, because it needs to iterate on the intermediate carry propagation nodes as well and synchronize with ongoing "tree add" operations. It further reduces memory use.

* Implement a custom strided allocator for intermediate items carry propagation bytes. This shares cachelines across different tree instances, keeping good locality. This ensures that all accesses from a given location in the machine topology touch the same cacheline for the various tree instances. This adds complexity, but provides compactness as well as minimal false-sharing.

Compared to this, the upstream percpu counters use a 32-bit integer per-cpu (4 bytes), and accumulate within a 64-bit global value.

So there is an extra memory footprint added by the current hpcc implementation, but if it's an issue we have various options to consider to reduce its footprint.

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
---
 .../core-api/percpu-counter-tree.rst          |  75 ++
 include/linux/mm_types.h                      |   4 +-
 include/linux/percpu_counter_tree.h           | 367 +++++++++
 init/main.c                                   |   2 +
 lib/Makefile                                  |   1 +
 lib/percpu_counter_tree.c                     | 702 ++++++++++++++++++
 6 files changed, 1149 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/core-api/percpu-counter-tree.rst
 create mode 100644 include/linux/percpu_counter_tree.h
 create mode 100644 lib/percpu_counter_tree.c
Documentation/core-api/percpu-counter-tree.rst new file +75 -0
new file mode 100644
index 000000000000..196da056e7b4
@@ -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
include/linux/mm_types.h +2 -2
index 6d815f6440c9..dff5fd1c1b06 100644
@@ -1462,8 +1462,8 @@ 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				\
-{								\
+#define MM_STRUCT_FLEXIBLE_ARRAY_INIT									\
+{													\
 	[0 ... sizeof(cpumask_t) + MM_CID_STATIC_SIZE - 1] = 0	\
 }
 
include/linux/percpu_counter_tree.h new file +367 -0

367 lines not on this page · raw message

init/main.c +2 -0
index 2613d3f9b3ce..eda2170bb21f 100644
@@ -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>
@@ -1041,6 +1042,7 @@ void start_kernel(void)
 	vfs_caches_init_early();
 	sort_main_extable();
 	trap_init();
+	percpu_counter_tree_subsystem_init();
 	mm_core_init();
 	maple_tree_init();
 	poking_init();
lib/Makefile +1 -0
index dfab958327c5..f1d0cb831630 100644
@@ -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
 
lib/percpu_counter_tree.c new file +702 -0

702 lines not on this page · raw message

Signature · 1 line
2.43.0
author reviewer
#2 lore raw

PATCH v22 2/10 lib: test hierarchical per-cpu counters

In reply to Mathieu Desnoyers

Introduce Kunit tests for hierarchical per-cpu counters.

Keep track of two sets of hierarchical counters, each meant to have the same precise sum at any time, but distributed differently across the topology.

Keep track of an atomic counter along with each hierarchical counter, for sum validation.

Those tests cover:

- Single-threaded (no concurrency) updates.
- Concurrent updates of counters from various CPUs.

Perform the following validations:

- Compare the precise sum of counters with the sum tracked by an atomic counter.
- Compare the precise sum of two sets of hierarchical counters.
- Approximated comparison of hierarchical counter with atomic counter.
- Approximated comparison of two sets of hierarchical counters.
- Validate the bounds of approximation ranges.

Run with the following .kunit/.kunitconfig:

CONFIG_KUNIT=y
CONFIG_SMP=y
CONFIG_PREEMPT=y
CONFIG_NR_CPUS=32
CONFIG_HOTPLUG_CPU=y
CONFIG_PERCPU_COUNTER_TREE_KUNIT_TEST=y

With the following execution (to use SMP):

./tools/testing/kunit/kunit.py run --arch=x86_64 --qemu_args="-smp 12"

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>

---
Changes since v19:
- Rename config option to PERCPU_COUNTER_TREE_KUNIT_TEST.

---
 lib/Kconfig                           |  12 +
 lib/tests/Makefile                    |   2 +
 lib/tests/percpu_counter_tree_kunit.c | 399 ++++++++++++++++++++++++++
 3 files changed, 413 insertions(+)
 create mode 100644 lib/tests/percpu_counter_tree_kunit.c
lib/Kconfig +12 -0
index 4e6b34c3346d..c0524258b205 100644
@@ -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
lib/tests/Makefile +2 -0
index 3cac3b63a752..051e73705977 100644
@@ -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/
lib/tests/percpu_counter_tree_kunit.c new file +399 -0

399 lines not on this page · raw message

Signature · 1 line
2.43.0
author reviewer
#3 lore raw

PATCH v22 3/10 mm: improve RSS counter approximation accuracy for proc interfaces

In reply to Mathieu Desnoyers

Use hierarchical per-cpu counters for RSS tracking to improve the accuracy of per-mm RSS sum approximation on large many-core systems [1]. This improves the accuracy of the RSS values returned by proc interfaces.

Here is a (possibly incomplete) list of the prior approaches that were used or proposed, along with their downside:

1) Per-thread rss tracking: large error on many-thread processes.

2) Per-CPU counters: up to 12% slower for short-lived processes and 9% increased system time in make test workloads [1]. Moreover, the inaccuracy increases with O(n^2) with the number of CPUs.

3) Per-NUMA-node counters: requires atomics on fast-path (overhead), error is high with systems that have lots of NUMA nodes (32 times the number of NUMA nodes).

4) Use a percise per-cpu counter sum for each counter value query:
Requires iteration on each possible CPUs for each sum, which adds overhead on large many-core systems running many processes.

The approach proposed here is to replace the per-cpu counters by the hierarchical per-cpu counters, which bounds the inaccuracy based on the system topology with O(N*logN).

* Testing results:

Test hardware: 2 sockets AMD EPYC 9654 96-Core Processor (384 logical CPUs total)

Methodology:

Comparing the current upstream implementation with the hierarchical counters is done by keeping both implementations wired up in parallel, and running a single-process, single-threaded program which hops randomly across CPUs in the system, calling mmap(2) and munmap(2) on random CPUs, keeping track of an array of allocated mappings, randomly choosing entries to either map or unmap.

get_mm_counter() is instrumented to compare the upstream counter approximation to the precise value, and print the delta when going over a given threshold. The delta of the hierarchical counter approximation to the precise value is also printed for comparison.

After a few minutes running this test, the upstream implementation counter approximation reaches a 1GB delta from the precise value, compared to 80MB delta with the hierarchical counter. The hierarchical counter provides a guaranteed maximum approximation inaccuracy of 192MB on that hardware topology.

* Fast path implementation comparison

The new inline percpu_counter_tree_add() uses a this_cpu_add_return() for the fast path (under a certain allocation size threshold). Above that, it calls a slow path which "trickles up" the carry to upper level counters with atomic_add_return.

In comparison, the upstream counters implementation calls percpu_counter_add_batch which uses this_cpu_try_cmpxchg() on the fast path, and does a raw_spin_lock_irqsave above a certain threshold.

The hierarchical implementation is therefore expected to have less contention on mid-sized allocations than the upstream counters because the atomic counters tracking those bits are only shared across nearby CPUs. In comparison, the upstream counters immediately use a global spinlock when reaching the threshold.

* Benchmarks

Using will-it-scale page_fault1 benchmarks to compare the upstream counters to the hierarchical counters. This is done with hyperthreading disabled. The speedup is within the standard deviation of the upstream runs, so the overhead is not significant.

upstream hierarchical speedup

page_fault1_processes -s 100 -t 1           614783         615558      +0.1%
page_fault1_threads -s 100 -t 1             612788         612447      -0.1%
page_fault1_processes -s 100 -t 96        37994977       37932035      -0.2%
page_fault1_threads -s 100 -t 96           2484130        2504860      +0.8%
page_fault1_processes -s 100 -t 192       71262917       71118830      -0.2%
page_fault1_threads -s 100 -t 192          2446437        2469296      +0.1%

* Memory Use

The most important parts in terms of memory use are the per-cpu counters and the tree items which propagate the carry.

In the proposed implementation, the per-cpu counters are allocated within per-cpu data structures, so they end up using:

nr_possible_cpus * sizeof(unsigned long)

This is in addition to the tree items. The size of those items is defined by the per_nr_cpu_order_config table "nr_items" field. Each item is aligned on cacheline size (typically 64 bytes) to minimize false sharing.

Here is the footprint for a few nr_cpu_ids on a 64-bit arch:

nr_cpu_ids percpu counters (bytes) nr_items items size (bytes) total (bytes)

    2               16                     1                 64                    80
    4               32                     3                192                   224
    8               64                     7                448                   512
   64               512                   21               1344                  1856
  128              1024                   21               1344                  2368
  256              2048                   37               2368                  4416
  512              4096                   73               4672                  8768

Compared to this, the upstream percpu counters use a 32-bit integer per-cpu (4 bytes), and accumulate within a 64-bit global value.

So there is an extra memory footprint added by the current hpcc implementation, but if it's an issue we have various options to consider to reduce its footprint.

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
---
 include/linux/mm.h          | 19 ++++++++++----
 include/linux/mm_types.h    | 50 +++++++++++++++++++++++++++----------
 include/trace/events/kmem.h |  2 +-
 kernel/fork.c               | 22 +++++++++-------
 4 files changed, 65 insertions(+), 28 deletions(-)
include/linux/mm.h +14 -5
index dd09c438fa23..7dd6fdda9bc8 100644
@@ -3447,38 +3447,47 @@ 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);
+	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);
 }
include/linux/mm_types.h +37 -13

95 lines not on this page · raw message

include/trace/events/kmem.h +1 -1
index cd7920c81f85..290ccb9fd25d 100644
@@ -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);
 	),
 
kernel/fork.c +13 -9
index 416758c8a3d4..5bad7a24d186 100644
@@ -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,7 @@ 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) + cpumask_size() + mm_cid_size() + get_rss_stat_items_size();
 
 	mm_cachep = kmem_cache_create_usercopy("mm_struct",
 			mm_size, ARCH_MIN_MMSTRUCT_ALIGN,
Signature · 1 line
2.43.0
author reviewer
#4 lore raw

PATCH v22 4/10 mm: reorder mm_struct flexible array to place mm_cpumask first

In reply to Mathieu Desnoyers

Reorder the mm_struct flexible array layout from:

[HPCC tree items][mm_cpumask][mm_cid]

to:

[mm_cpumask][mm_cid][alignment padding][HPCC tree items]

The previous layout placed the HPCC tree items first, which required mm_cpumask() to skip past them using percpu_counter_tree_items_size(). This created a boot-time initialization ordering dependency: any use of mm_cpumask() before percpu_counter_tree_subsystem_init() would compute the wrong pointer offset, reading from or writing to the HPCC items region instead of the actual cpumask.

On powerpc, switch_mm_irqs_off() accesses mm_cpumask() early in boot via VM_WARN_ON_ONCE(!cpumask_test_cpu(cpu, mm_cpumask(prev))), which could fire spuriously or cause silent memory corruption if the HPCC subsystem was not yet initialized.

By placing mm_cpumask first, mm_cpumask() remains a simple &mm->flexible_array with no runtime dependency on HPCC initialization. The HPCC tree items are accessed via get_rss_stat_items_offset(), which skips past the cpumask and mm_cid with appropriate cacheline alignment padding. This accessor is only used during mm_struct initialization (percpu_counter_tree_init_many), not on context switch or other hot paths.

Introduce the PERCPU_COUNTER_TREE_ITEMS_ALIGN() macro to handle the SMP cacheline alignment vs !SMP no-op in a single place, used by both the static init_mm flexible array initializer and the runtime offset computation.

The cost is at most one cacheline (typically 64 bytes) of padding per mm_struct between the mm_cid data and the HPCC tree items.

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
---
 include/linux/mm.h                  |  1 +
 include/linux/mm_types.h            | 47 +++++++++++++++++------------
 include/linux/percpu_counter_tree.h |  3 ++
 kernel/fork.c                       |  4 ++-
 4 files changed, 34 insertions(+), 21 deletions(-)
include/linux/mm.h +1 -0
index 7dd6fdda9bc8..ffbcd18c4ecb 100644
@@ -3453,6 +3453,7 @@ static inline struct percpu_counter_tree_level_item *get_rss_stat_items(struct m
 	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;
 }
 
include/linux/mm_types.h +27 -20

77 lines not on this page · raw message

include/linux/percpu_counter_tree.h +3 -0
index 828c763edd4a..3e8a820e2d1d 100644
@@ -66,6 +66,8 @@ struct percpu_counter_tree_level_item {
 
 #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. */
@@ -167,6 +169,7 @@ void percpu_counter_tree_approximate_accuracy_range(struct percpu_counter_tree *
 #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;
 
kernel/fork.c +3 -1
index 5bad7a24d186..db398b6c5288 100644
@@ -3126,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() + get_rss_stat_items_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,
Signature · 1 line
2.43.0
author reviewer
#5 lore raw

PATCH v22 5/10 init: move percpu_counter_tree_subsystem_init() earlier in boot

In reply to Mathieu Desnoyers

Move percpu_counter_tree_subsystem_init() from after trap_init() to immediately after setup_nr_cpu_ids() in start_kernel().

The function's only dependency is nr_cpu_ids: it calls get_count_order(nr_cpu_ids), indexes into a const configuration table, and performs arithmetic to derive accuracy parameters. It requires no memory allocator, percpu areas, or other infrastructure.

Initialize the subsystem as soon as its dependency is available rather than deferring until later in the boot sequence. This ensures percpu_counter_tree_items_size() returns the correct value well before its first use in mm_cache_init().

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
---
 init/main.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
init/main.c +1 -1
index eda2170bb21f..845cb57e9096 100644
@@ -1011,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();
@@ -1042,7 +1043,6 @@ void start_kernel(void)
 	vfs_caches_init_early();
 	sort_main_extable();
 	trap_init();
-	percpu_counter_tree_subsystem_init();
 	mm_core_init();
 	maple_tree_init();
 	poking_init();
Signature · 1 line
2.43.0
author reviewer
#6 lore raw

PATCH v22 6/10 lib: inline percpu_counter_tree_items_size with boot-safety sentinel

In reply to Mathieu Desnoyers

Replace the out-of-line percpu_counter_tree_items_size() function with a static inline that loads the __ro_after_init variable __percpu_counter_tree_items_size directly. This eliminates a function call on paths that compute mm_struct flexible array layout offsets.

Initialize the variable to SIZE_MAX as a sentinel value, and add a WARN_ON_ONCE check in the inline accessor to catch any accidental use before percpu_counter_tree_subsystem_init() sets the real value based on nr_cpu_ids. An early misuse would produce an absurd offset that triggers the warning with a stack trace pointing at the offending caller, rather than silently computing wrong memory offsets.

percpu_counter_tree_subsystem_init() sets the variable to the runtime value immediately after deriving counter_config from nr_cpu_ids, before calculate_accuracy_topology(). After boot, __ro_after_init moves the variable into read-only memory.

On !CONFIG_SMP, the existing inline returning 0 is unchanged and requires no sentinel.

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
---
 include/linux/percpu_counter_tree.h | 19 ++++++++++++++++++-
 lib/percpu_counter_tree.c           | 24 ++++++++----------------
 2 files changed, 26 insertions(+), 17 deletions(-)
include/linux/percpu_counter_tree.h +18 -1
index 3e8a820e2d1d..4095acdc879b 100644
@@ -101,7 +101,24 @@ struct percpu_counter_tree {
 	} approx_accuracy_range;
 };
 
-size_t percpu_counter_tree_items_size(void);
+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,
lib/percpu_counter_tree.c +8 -16
index 5c8fc2dcdc16..cfa5b04e05d7 100644
@@ -653,22 +653,9 @@ void percpu_counter_tree_set(struct percpu_counter_tree *counter, long v)
 }
 EXPORT_SYMBOL_GPL(percpu_counter_tree_set);
 
-/*
- * 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.
- */
-size_t percpu_counter_tree_items_size(void)
-{
-	if (!nr_cpus_order)
-		return 0;
-	return counter_config->nr_items * sizeof(struct percpu_counter_tree_level_item);
-}
-EXPORT_SYMBOL_GPL(percpu_counter_tree_items_size);
+/* 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)
 {
@@ -697,6 +684,11 @@ int __init percpu_counter_tree_subsystem_init(void)
 		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;
 }
Signature · 1 line
2.43.0
author reviewer
#7 lore raw

PATCH v22 7/10 lib/hpcc: Document that accuracy is a property of settled counters

In reply to Mathieu Desnoyers

Answer a report from Sashiko at:
https://sashiko.dev/#/patchset/[email protected]

This change is documentation only. The bound describes a settled tree; the two-counter comparisons read their operands independently. No code change.

I considered and rejected the preempt_disable() proposed by Sashiko and an alternative dual pre/post counters design.

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
---
 Documentation/core-api/percpu-counter-tree.rst |  4 ++++
 include/linux/percpu_counter_tree.h            | 10 +++++++---
 lib/percpu_counter_tree.c                      |  6 ++++--
 3 files changed, 15 insertions(+), 5 deletions(-)
Documentation/core-api/percpu-counter-tree.rst +4 -0
index 196da056e7b4..bb13e28bef11 100644
@@ -43,6 +43,10 @@ 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.
 
+The bounded accuracy is a property of the settled tree. While updates are
+in flight the transient error can exceed it, bounded by the number of
+updaters and their increment size.
+
 Use Cases
 =========
 
include/linux/percpu_counter_tree.h +7 -3
index 4095acdc879b..d593806b4ab2 100644
@@ -93,7 +93,8 @@ struct percpu_counter_tree {
 	 * 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.
+	 * compared to the "over" accuracy range. The accuracy range is a bound on a settled counter:
+	 * one with no update in progress.
 	 */
 	struct {
 		unsigned long under;
@@ -169,6 +170,8 @@ long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)
  * 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.
+ * The bounds describe a settled counter: one with no update in progress.
+ * An update in flight between its per-CPU increment and its carry propagation is not covered.
  * Using this function should not be typically required, see the following functions instead:
  * * percpu_counter_tree_approximate_compare(),
  * * percpu_counter_tree_approximate_compare_value(),
@@ -341,8 +344,9 @@ long percpu_counter_tree_precise_sum_positive(struct percpu_counter_tree *counte
  * @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.
+ * Calculate the minimum and maximum precise values for a given approximation
+ * and (under, over) accuracy range. The accuracy range is a bound on a settled
+ * tree: one with no update in progress.
  *
  * The range of the approximation as a function of the precise sum is expressed as:
  *
lib/percpu_counter_tree.c +4 -2
index cfa5b04e05d7..cd71581f56bb 100644
@@ -483,7 +483,8 @@ int compare_delta(long delta, unsigned long accuracy_neg, unsigned long accuracy
  * 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.
+ * counters accuracy range. The two counters are read independently;
+ * the result is not an atomic snapshot of both.
  *
  * Return:
  * * %0		- Counters @a and @b do not differ by more than the sum of their respective
@@ -532,7 +533,8 @@ EXPORT_SYMBOL_GPL(percpu_counter_tree_approximate_compare_value);
  * 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.
+ * sums. The two counters are read independently; the result is not an
+ * atomic snapshot of both.
  *
  * Return:
  * * %0		- Counters are equal.
Signature · 1 line
2.43.0
author reviewer
#8 lore raw

PATCH v22 8/10 lib/hpcc: Clarify accuracy range documentation

In reply to Mathieu Desnoyers

Answer a report from Sashiko at:
https://sashiko.dev/#/patchset/[email protected]

Note that both Sashiko and Claude got it wrong with respect to what was going on there. I took out pen and paper to draw the range situation, and presented the result to Claude through ascii art, which solved the matter. Having two LLMs misguided by the code, I decided to add a visual representation of the approximation ranges to compare_delta() so anyone reviewing this code won't fall into the same traps.

This change is documentation only.

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
---
 lib/percpu_counter_tree.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)
lib/percpu_counter_tree.c +28 -0
index cd71581f56bb..a8351c53d062 100644
@@ -457,6 +457,32 @@ long percpu_counter_tree_precise_sum(struct percpu_counter_tree *counter)
 }
 EXPORT_SYMBOL_GPL(percpu_counter_tree_precise_sum);
 
+/*
+ * Each counter's approximation lies within [precise - under, precise + over]:
+ *
+ *                  approx_a range
+ *            <-----------+----------->
+ *          under_a       |       over_a
+ *                    precise_a
+ *                        |                          approx_b range
+ *                        |                    <-----------+----------->
+ *                        |                  under_b       |       over_b
+ *                        |                            precise_b
+ *                        |                                |
+ *                        |<------------ gap ------------->|
+ *  ----------------------+--------------------------------+-------------> values
+ *
+ * The two ranges are disjoint, and the comparison can return a definitive
+ * answer, only once the gap exceeds the two facing half-widths:
+ *
+ *   a below b:  gap > over_a + under_b   (a's upper edge, b's lower edge)
+ *   a above b:  gap > under_a + over_b   (a's lower edge, b's upper edge)
+ *
+ * When comparing against a plain value, the value has zero width, so the
+ * margins reduce to that single counter's under and over.
+ *
+ * accuracy_neg is used when delta < 0, and accuracy_pos is used when delta >= 0.
+ */
 static
 int compare_delta(long delta, unsigned long accuracy_neg, unsigned long accuracy_pos)
 {
@@ -494,6 +520,7 @@ int compare_delta(long delta, unsigned long accuracy_neg, unsigned long accuracy
  */
 int percpu_counter_tree_approximate_compare(struct percpu_counter_tree *a, struct percpu_counter_tree *b)
 {
+	/* See the range geometry above compare_delta(). */
 	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);
@@ -549,6 +576,7 @@ int percpu_counter_tree_precise_compare(struct percpu_counter_tree *a, struct pe
 	long delta = count_a - count_b;
 	int res;
 
+	/* See the range geometry above compare_delta(). */
 	res = compare_delta(delta,
 			    a->approx_accuracy_range.over + b->approx_accuracy_range.under,
 			    a->approx_accuracy_range.under + b->approx_accuracy_range.over);
Signature · 1 line
2.43.0
author reviewer
#9 lore raw

PATCH v22 9/10 lib/hpcc: Introduce wrapped delta helper

In reply to Mathieu Desnoyers

Answer a report from Sashiko at:
https://sashiko.dev/#/patchset/[email protected]

Document that the comparison between counters is on the wrapped difference. It is valid only when the two counters differ by less than LONG_MAX, and results are undefined beyond that.

Introduce a wrapped_delta() static inline helper to perform this subtraction on unsigned types, which define the subtraction across overflow, and use it in the comparison API.

I've reflowed some kdocs comments that were around the addition of new sentences about wrapped difference.

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
---
 .../core-api/percpu-counter-tree.rst          |  3 +
 lib/percpu_counter_tree.c                     | 81 ++++++++++++-------
 2 files changed, 55 insertions(+), 29 deletions(-)
Documentation/core-api/percpu-counter-tree.rst +3 -0
index bb13e28bef11..878cbd85304c 100644
@@ -72,6 +72,9 @@ 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.
 
+Because the comparison is on the wrapped difference, it is not transitive:
+ordering is undefined over a set of counters spanning more than LONG_MAX.
+
 Functions and structures
 ========================
 
lib/percpu_counter_tree.c +52 -29

163 lines not on this page · raw message

Signature · 1 line
2.43.0
author reviewer
#10 lore raw

PATCH v22 10/10 lib/tests/hpcc: Fix hotplug, module unload, and error handling

In reply to Mathieu Desnoyers

Answer a report from Sashiko at:
https://sashiko.dev/#/patchset/[email protected]

Those were good catches. Following them up surfaced more than the report
contained: ERR_PTR handling, a td leak, hotplug locking, allocation sizing, the cpu & ~1 skip, and a lost-worker bug where kthread_stop() could preempt the threadfn before it ran, plus a task_struct reaping race that only shows up at 1000 workers.

Plainly following Sashiko's advice to move to kthread_stop() did not
work: the thread running the worker needed a task struct reference, a completion to ensure the work was actually done, in addition to the kthread_stop. The kthread_stop only ensure that the thread is really done before module unload, without guaranteeing that the kthread has actually done its work.

Cc "Paul E. McKenney" <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Dennis Zhou <[email protected]>
Cc Tejun Heo <[email protected]>
Cc Christoph Lameter <[email protected]>
Cc Martin Liu <[email protected]>
Cc David Rientjes <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc SeongJae Park <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Johannes Weiner <[email protected]>
Cc Sweet Tea Dorminy <[email protected]>
Cc Lorenzo Stoakes <[email protected]>
Cc Liam R. Howlett <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Wei Yang <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Al Viro <[email protected]>
Cc Yu Zhao <[email protected]>
Cc Roman Gushchin <[email protected]>
Cc Mateusz Guzik <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Baolin Wang <[email protected]>
Cc Aboorva Devarajan <[email protected]>
Cc David Carlier <[email protected]>
Cc Josh Law <[email protected]>
Cc Andrew Morton <[email protected]>
---
 lib/tests/percpu_counter_tree_kunit.c | 280 +++++++++++++++++++++-----
 1 file changed, 232 insertions(+), 48 deletions(-)
lib/tests/percpu_counter_tree_kunit.c +232 -48
index a79176655c4b..8af8d2659b57 100644
@@ -6,10 +6,13 @@
 #include <linux/kthread.h>
 #include <linux/wait.h>
 #include <linux/random.h>
+#include <linux/cpuhplock.h>
+#include <linux/slab.h>
+#include <linux/sched/task.h>
 
 struct multi_thread_test_data {
 	long increment;
-	int nr_inc;
+	unsigned int nr_inc;
 	int counter_index;
 };
 
@@ -31,6 +34,9 @@ static void complete_work(void)
 		wake_up(&kernel_threads_wq);
 }
 
+/* Random tasks test. */
+#define NR_RAND_TASKS	1000
+
 static void hpcc_print_info(struct kunit *test)
 {
 	kunit_info(test, "Running test with %d CPUs\n", num_online_cpus());
@@ -67,18 +73,19 @@ static void check_counters(struct kunit *test)
 		/* Accuracy limits checks. */
 		percpu_counter_tree_approximate_accuracy_range(&counter[counter_index], &under_accuracy, &over_accuracy);
 
+		/*
+		 * under_accuracy and over_accuracy are unsigned long, so the
+		 * inner expression promotes to unsigned. Compute the difference
+		 * in unsigned and cast to signed for the comparison against 0.
+		 */
 		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]));
@@ -96,18 +103,26 @@ static int multi_thread_worker_fn(void *data)
 	return 0;
 }
 
-static void test_run_on_specific_cpu(struct kunit *test, int target_cpu, int counter_index, unsigned int nr_inc, long increment)
+static struct task_struct *test_run_on_specific_cpu(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);
+	struct task_struct *task;
 
-	KUNIT_EXPECT_PTR_NE(test, td, NULL);
+	if (!td)
+		return 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);
+	task = kthread_create_on_cpu(multi_thread_worker_fn, td, target_cpu, "kunit_multi_thread_worker");
+	if (IS_ERR_OR_NULL(task)) {
+		complete_work();
+		kfree(td);
+		return task;
+	}
+	get_task_struct(task);
+	wake_up_process(task);
+	return task;
 }
 
 static void init_kthreads(void)
@@ -115,6 +130,9 @@ static void init_kthreads(void)
 	atomic_set(&kernel_threads_to_run, 1);
 }
 
+/*
+ * The caller needs to wait for work completion _before_ stopping kthreads.
+ */
 static void fini_kthreads(void)
 {
 	/* Release our own reference. */
@@ -129,23 +147,27 @@ static void test_sync_kthreads(void)
 	init_kthreads();
 }
 
-static void init_counters(struct kunit *test, unsigned long batch_size)
+static int init_counters(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);
+	items = kvcalloc(NR_COUNTERS, percpu_counter_tree_items_size(), GFP_KERNEL);
+	if (!items)
+		return -ENOMEM;
 	ret = percpu_counter_tree_init_many(counter, items, NR_COUNTERS, batch_size, GFP_KERNEL);
-	KUNIT_EXPECT_EQ(test, ret, 0);
-
+	if (ret) {
+		kvfree(items);
+		return ret;
+	}
 	for (i = 0; i < NR_COUNTERS; i++)
 		atomic_long_set(&global_counter[i], 0);
+	return 0;
 }
 
 static void fini_counters(void)
 {
 	percpu_counter_tree_destroy_many(counter, NR_COUNTERS);
-	kfree(items);
+	kvfree(items);
 }
 
 enum up_test_inc_type {
@@ -164,11 +186,16 @@ static void do_hpcc_test_single_thread(struct kunit *test, int _cpu0, int _cpu1,
 	unsigned long batch_size_order = 5;
 	int cpu0 = _cpu0;
 	int cpu1 = _cpu1;
-	int i;
+	int ret, i;
 
-	init_counters(test, 1UL << batch_size_order);
+	ret = init_counters(1UL << batch_size_order);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		return;
 	init_kthreads();
+	cpus_read_lock();
 	for (i = 0; i < 10000; i++) {
+		struct task_struct *task;
 		long increment;
 
 		switch (type) {
@@ -181,18 +208,34 @@ static void do_hpcc_test_single_thread(struct kunit *test, int _cpu0, int _cpu1,
 		case INC_RANDOM:
 			increment = (long) get_random_long() % 50000;
 			break;
+		default:
+			WARN_ON_ONCE(1);
+			increment = 0;
 		}
 		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);
+		task = test_run_on_specific_cpu(cpu0, 0, 1, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task);
+		if (IS_ERR_OR_NULL(task)) {
+			fini_kthreads();
+			goto end;
+		}
 		test_sync_kthreads();
-		test_run_on_specific_cpu(test, cpu1, 1, 1, increment);
+		kthread_stop_put(task);
+		task = test_run_on_specific_cpu(cpu1, 1, 1, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task);
+		if (IS_ERR_OR_NULL(task)) {
+			fini_kthreads();
+			goto end;
+		}
 		test_sync_kthreads();
+		kthread_stop_put(task);
 		check_counters(test);
 	}
-	fini_kthreads();
+end:
+	cpus_read_unlock();
 	fini_counters();
 }
 
@@ -225,62 +268,168 @@ static void hpcc_test_single_thread_random(struct kunit *test)
 
 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);
+	struct task_struct *(*task)[NR_COUNTERS];
+	int ret, cpu;
+
+	task = kvcalloc(nr_cpu_ids, sizeof(*task), GFP_KERNEL);
+	KUNIT_EXPECT_NOT_NULL(test, task);
+	if (!task)
+		return;
+	ret = init_counters(batch_size);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		goto end;
 	init_kthreads();
+	cpus_read_lock();
 	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);
+		task[cpu][0] = test_run_on_specific_cpu(cpu, 0, nr_inc, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[cpu][0]);
+		if (IS_ERR_OR_NULL(task[cpu][0]))
+			break;
+		task[cpu][1] = test_run_on_specific_cpu(cpu, 1, nr_inc, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[cpu][1]);
+		if (IS_ERR_OR_NULL(task[cpu][1]))
+			break;
 	}
 	fini_kthreads();
+	for_each_online_cpu(cpu) {
+		if (!IS_ERR_OR_NULL(task[cpu][0]))
+			kthread_stop_put(task[cpu][0]);
+		if (!IS_ERR_OR_NULL(task[cpu][1]))
+			kthread_stop_put(task[cpu][1]);
+	}
+	cpus_read_unlock();
 	check_counters(test);
 	fini_counters();
+end:
+	kvfree(task);
 }
 
 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);
+	struct task_struct *(*task)[NR_COUNTERS];
+	int ret, cpu;
+
+	task = kvcalloc(nr_cpu_ids, sizeof(*task), GFP_KERNEL);
+	KUNIT_EXPECT_NOT_NULL(test, task);
+	if (!task)
+		return;
+	ret = init_counters(batch_size);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		goto end;
 	init_kthreads();
+	cpus_read_lock();
 	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. */
+		/*
+		 * Funnel pairs of CPU indexes to their associated even index.
+		 *
+		 *   Map 0 and 1 -> index 0
+		 *   Map 2 and 3 -> index 2 and so on.
+		 */
+		int even_cpu = cpu & ~1;
+
+		if (!cpumask_test_cpu(even_cpu, cpu_online_mask))
+			continue;
+		task[cpu][0] = test_run_on_specific_cpu(cpu, 0, nr_inc, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[cpu][0]);
+		if (IS_ERR_OR_NULL(task[cpu][0]))
+			break;
+		task[cpu][1] = test_run_on_specific_cpu(even_cpu, 1, nr_inc, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[cpu][1]);
+		if (IS_ERR_OR_NULL(task[cpu][1]))
+			break;
 	}
 	fini_kthreads();
+	for_each_online_cpu(cpu) {
+		if (!IS_ERR_OR_NULL(task[cpu][0]))
+			kthread_stop_put(task[cpu][0]);
+		if (!IS_ERR_OR_NULL(task[cpu][1]))
+			kthread_stop_put(task[cpu][1]);
+	}
+	cpus_read_unlock();
 	check_counters(test);
 	fini_counters();
+end:
+	kvfree(task);
 }
 
 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);
+	struct task_struct *(*task)[NR_COUNTERS];
+	int ret, cpu;
+
+	task = kvcalloc(nr_cpu_ids, sizeof(*task), GFP_KERNEL);
+	KUNIT_EXPECT_NOT_NULL(test, task);
+	if (!task)
+		return;
+	ret = init_counters(batch_size);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		goto end;
 	init_kthreads();
+	cpus_read_lock();
 	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);
+		task[cpu][0] = test_run_on_specific_cpu(cpu, 0, nr_inc, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[cpu][0]);
+		if (IS_ERR_OR_NULL(task[cpu][0]))
+			break;
+		task[cpu][1] = test_run_on_specific_cpu(cpumask_first(cpu_online_mask), 1, nr_inc, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[cpu][1]);
+		if (IS_ERR_OR_NULL(task[cpu][1]))
+			break;
 	}
 	fini_kthreads();
+	for_each_online_cpu(cpu) {
+		if (!IS_ERR_OR_NULL(task[cpu][0]))
+			kthread_stop_put(task[cpu][0]);
+		if (!IS_ERR_OR_NULL(task[cpu][1]))
+			kthread_stop_put(task[cpu][1]);
+	}
+	cpus_read_unlock();
 	check_counters(test);
 	fini_counters();
+end:
+	kvfree(task);
 }
 
 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);
+	struct task_struct *(*task)[NR_COUNTERS];
+	int ret, cpu;
+
+	task = kvcalloc(nr_cpu_ids, sizeof(*task), GFP_KERNEL);
+	KUNIT_EXPECT_NOT_NULL(test, task);
+	if (!task)
+		return;
+	ret = init_counters(batch_size);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		goto end;
 	init_kthreads();
+	cpus_read_lock();
 	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);
+		task[cpu][0] = test_run_on_specific_cpu(cpu, 0, nr_inc, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[cpu][0]);
+		if (IS_ERR_OR_NULL(task[cpu][0]))
+			break;
+		task[cpu][1] = test_run_on_specific_cpu(cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);
+		KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[cpu][1]);
+		if (IS_ERR_OR_NULL(task[cpu][1]))
+			break;
 	}
 	fini_kthreads();
+	for_each_online_cpu(cpu) {
+		if (!IS_ERR_OR_NULL(task[cpu][0]))
+			kthread_stop_put(task[cpu][0]);
+		if (!IS_ERR_OR_NULL(task[cpu][1]))
+			kthread_stop_put(task[cpu][1]);
+	}
+	cpus_read_unlock();
 	check_counters(test);
 	fini_counters();
+end:
+	kvfree(task);
 }
 
 static void hpcc_test_multi_thread_batch_increment(struct kunit *test)
@@ -305,25 +454,50 @@ static void hpcc_test_multi_thread_batch_increment(struct kunit *test)
 
 static void hpcc_test_multi_thread_random_walk(struct kunit *test)
 {
+	struct task_struct *(*task)[NR_COUNTERS];
 	unsigned long batch_size_order = 5;
 	int loop;
 
+	task = kvcalloc(NR_RAND_TASKS, sizeof(*task), GFP_KERNEL);
+	KUNIT_EXPECT_NOT_NULL(test, task);
+	if (!task)
+		return;
 	for (loop = 0; loop < 100; loop++) {
-		int i;
+		int ret, i;
 
-		init_counters(test, 1UL << batch_size_order);
+		memset(task, 0, NR_RAND_TASKS * sizeof(*task));
+		ret = init_counters(1UL << batch_size_order);
+		KUNIT_EXPECT_EQ(test, ret, 0);
+		if (ret)
+			goto end;
 		init_kthreads();
-		for (i = 0; i < 1000; i++) {
+		cpus_read_lock();
+		for (i = 0; i < NR_RAND_TASKS; 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);
+			task[i][0] = test_run_on_specific_cpu(cpumask_any_distribute(cpu_online_mask), 0, nr_inc, increment);
+			KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[i][0]);
+			if (IS_ERR_OR_NULL(task[i][0]))
+				break;
+			task[i][1] = test_run_on_specific_cpu(cpumask_any_distribute(cpu_online_mask), 1, nr_inc, increment);
+			KUNIT_EXPECT_NOT_ERR_OR_NULL(test, task[i][1]);
+			if (IS_ERR_OR_NULL(task[i][1]))
+				break;
 		}
 		fini_kthreads();
+		for (i = 0; i < NR_RAND_TASKS; i++) {
+			if (!IS_ERR_OR_NULL(task[i][0]))
+				kthread_stop_put(task[i][0]);
+			if (!IS_ERR_OR_NULL(task[i][1]))
+				kthread_stop_put(task[i][1]);
+		}
+		cpus_read_unlock();
 		check_counters(test);
 		fini_counters();
 	}
+end:
+	kvfree(task);
 }
 
 static void hpcc_test_init_one(struct kunit *test)
@@ -333,11 +507,16 @@ static void hpcc_test_init_one(struct kunit *test)
 	int ret;
 
 	counter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);
-	KUNIT_EXPECT_PTR_NE(test, counter_items, NULL);
+	KUNIT_EXPECT_NOT_NULL(test, counter_items);
+	if (!counter_items)
+		return;
 	ret = percpu_counter_tree_init(&pct, counter_items, 32, GFP_KERNEL);
 	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		goto end;
 
 	percpu_counter_tree_destroy(&pct);
+end:
 	kfree(counter_items);
 }
 
@@ -352,9 +531,13 @@ static void hpcc_test_set(struct kunit *test)
 	int i, ret;
 
 	counter_items = kzalloc(percpu_counter_tree_items_size(), GFP_KERNEL);
-	KUNIT_EXPECT_PTR_NE(test, counter_items, NULL);
+	KUNIT_EXPECT_NOT_NULL(test, counter_items);
+	if (!counter_items)
+		return;
 	ret = percpu_counter_tree_init(&pct, counter_items, 32, GFP_KERNEL);
 	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		goto end;
 
 	for (i = 0; i < ARRAY_SIZE(values); i++) {
 		long v = values[i];
@@ -373,6 +556,7 @@ static void hpcc_test_set(struct kunit *test)
 	}
 
 	percpu_counter_tree_destroy(&pct);
+end:
 	kfree(counter_items);
 }
 
Signature · 1 line
2.43.0