Skip to contentSkip to conversation

Hierarchical Percpu Counters for RSS and tmpfs

RFC PATCH In review Mathieu Desnoyers 2 participants 21 messages Nov 11 – Nov 13

Subsystems (10)
lore
Share & tools
lore

Mathieu Desnoyers

author reviewer
#0 lore raw

v25 cover Hierarchical Percpu Counters for RSS and tmpfs

Hi David,

Here is the hierarchical per-cpu counters series, based on v7.4-rc2. After your review of v24 [3], v25 adds a second user in patches 8 to
11. This user is the tmpfs size limit. It is still an RFC because of the questions at the end.

The problem
-----------

The RSS counters are struct percpu_counter since
commit f1a7941243c1 ("mm: convert mm's rss stats into percpu_counter"). Their batch size is max(32, 2 * nr_cpus). So their error grows with nr_cpus^2. At 384 logical CPUs, it reaches 1.1GB per counter.

/proc/PID/status, /proc/PID/statm and the OOM killer now use precise sums (commits 82241a83cd15 and 5898aa8f9a0b). Other readers still use the approximation:

- the RSS high watermark (VmHWM, ru_maxrss, taskstats);
- /proc/PID/stat (ps, top, monitoring agents);
- the taskstats RSS-time integral (coremem);
- NUMA balancing and the mark_victim tracepoint.

On the test machine below, /proc/PID/stat was off by 17MB for a single-threaded process. It was off by up to 134MB with 64 threads.

Precise sums cannot fix the high watermark or the integral. They are sampled on every unmap and at each tick. A precise sum reads every possible CPU: about 4us per counter at 384 logical CPUs. A smaller batch takes the counter spinlock on every carry. At batch 32, an update of a shared mm costs 4.4 to 69us with one thread per CPU. With this series, it costs 26ns to 1.2us.

The tmpfs size limit has the same problem in another form. percpu_counter_limited_add() takes no lock only while the mount is more than batch * nr_cpus pages below its size. This is 1.1GB at 384 logical CPUs. A smaller mount, such as a 64MB /dev/shm, takes the counter spinlock and sums all CPUs for each page.

The series
----------

Patches 1 to 5 use hierarchical per-cpu counters for the RSS counters. Per-cpu bytes carry into a tree of atomic counters. The tree is shaped at boot from nr_cpu_ids. The batch is 32 and the error bound is in O(n*log(n)). There is no global lock. A follow-up will use the comparison functions for the OOM killer task selection.

Patches 6 and 7 keep the RSS counters of single-threaded processes exact, without per-cpu memory. Until a second thread shares the mm, the counters are a plain bias and an atomic bias. Creating the second thread allocates the per-cpu counters and activates the tree. Most processes never need that per-cpu memory, so process creation gets cheaper. In a 384-vCPU guest, posix_spawn() of a static program gains 22 to 42% over patches 1 to 5.

Patch 8 adds limit counters on the tree. A limit counter splits the value into two counters which only grow: the additions and the subtractions. Their carries are ordered so that each sum errs in one direction only. An addition then checks the limit without a lock. It sums the CPUs only within the accuracy of the limit. The limit stays strict. Patch 9 tests the limit counters, and patch 10 checks their memory ordering with litmus tests. Patch 11 uses a limit counter for the tmpfs size limit.

Patches 12 to 14 are tools to check the tree shape on other hardware:
two boot parameters and a KUnit benchmark. I measured the defaults on one machine only, so results from other hardware are welcome.

Results
-------

The machine is a 2-socket AMD EPYC 9654 with 384 logical CPUs. The tree is 8,8,8 with batch 32. Patches 3, 7 and 11 have the details. The bare-metal results were measured on v7.3.

Accuracy per counter, bound and largest error seen, while a process hops across all CPUs (384-vCPU guest pinned to the host):

hpcc upstream
bound 158.5MB 1.1GB
measured, single-threaded 0 (exact) 841MB
measured, with a second thread 96MB 845MB

Update cost, ns per update, one thread per CPU, bare metal (mm: the 4 counters of one mm; private: one counter per thread):

upstream upstream
hpcc batch 768 batch 32
mm, +1 26 288 4370
mm, random +-32 135 385 69171
mm, random +-512 1174 20229 69186
private, random +-32 31 20 -

Memory per mm, in bytes (guest, v7.4-rc1):

                  single-threaded   threaded   upstream
    16 CPUs                  1820       1948       2076
    384 CPUs                 1928       8145       8072
    1024 CPUs                2185      17204      18569

tmpfs, fallocate() of one page at a time, in thousands of calls per second (384-vCPU guest, v7.4-rc2):

    size=  processes   upstream    hpcc
    64MB           1        208     483
    64MB         384        126   54275
    1GB          384        125   93879
    2GB          384      93851   93476

Behavior changes
----------------

- The per-cpu counters are allocated by the second thread, not by fork(). So clone() with CLONE_VM can now fail with -ENOMEM.
- mm_struct gains rss_owner and rss_stat_mutex. rss_owner is the task running on the mm. It is never dereferenced.
- The precise sums take no lock. Under concurrent updates, they can miss a carry on its way up the tree. They are exact for a process at rest.
- The rss_stat tracepoint reports the approximation (patch 5).
- tmpfs (patch 11): an allocation near a full mount can fail although it fits. This happens while a concurrent allocation which does not fit is undone. A remount keeps the batch size of the first size.

Caveats
-------

- From 33 to 39 CPUs, the RSS counters are up to 1.37 times less accurate than upstream.
- Just above a power of 2 CPUs, a threaded process uses up to 1.50 times the memory of upstream for its RSS counters.
- A multi-threaded process which ran on few CPUs can hold more error than upstream.
- With 384 threads created at once, the per-cpu allocator serializes the allocations, as it does upstream at every fork.
- tmpfs: in the last 1/4 of the size, each allocation sums all CPUs. With one process, this is 37% slower than upstream.

Changes since v24 [2]
---------------------

- Rebased onto v7.4-rc2.
- New patches 8 to 11: the tmpfs size limit. In my reply to your review [3], I wrote that mounts of 2GB and above lose 1 to 2%. Measured again on v7.4-rc2, they are within 1%.
- New litmus tests in patch 10, in tools/testing/hpcc/litmus. They check the memory ordering of the limit counters, of the carries and of the publication of the tree. Variants without an ordering show that it is needed.
- Patch 6 (Sashiko): the activation race test releases its workers with release/acquire.
- Patches 12 to 14 were patches 8 to 10, unchanged.

The v24 cover letter [2] lists the earlier changes, since v22 [1].

These tests pass on v7.4-rc2:

- Every commit builds without warnings on x86_64 (SMP and UP), arm64, ppc64le, 32-bit powerpc and sparc64. Sparse adds no warnings.
- KUnit passes in guests with 1, 16 and 384 vCPUs. It also passes with lockdep with 16 and 64 vCPUs.
- The userspace test passes on simulated topologies up to 65536 CPUs, as a 64-bit and a 32-bit build.
- The RSS counters match a page table walk from 1 to 64 threads.
- herd7 checks the memory ordering of the limit counters with litmus tests.

I wrote v22. Starting from it, an LLM coding assistant drove the implementation of this revision from my design decisions. It wrote the code, the tests, the benchmark and the measurement scripts. It ran the measurements in guests and prepared the bare-metal ones. It drafted the comments, the changelogs and this letter. I made the design decisions, reviewed every change and directed the rework through my review comments.

Questions
---------

David answered the questions of v24 [3]. These remain open:

1. Fork and exit reviewers: is mm->rss_owner acceptable (patch 7)? The alternative is current->mm == mm and an "activated" flag.
2. Martin: the rss_stat tracepoint now reports the approximation (patch 5). Is that fine for its users, such as Perfetto?
3. Who could run the benchmark of patch 14 on non-AMD, arm64 or POWER machines? The defaults were only measured on one machine.
4. tmpfs maintainers: are the behavior changes of patch 11 acceptable?

Thanks,

Mathieu

[1] https://lore.kernel.org/lkml/[email protected]/
[2] https://lore.kernel.org/lkml/[email protected]/
[3] https://lore.kernel.org/lkml/[email protected]/

Mathieu Desnoyers (14):
lib: introduce hierarchical per-cpu counters
lib: test hierarchical per-cpu counters
mm: use hierarchical per-cpu counters for the RSS counters tools/testing/hpcc: add userspace test of hierarchical per-CPU
counters
mm: report the approximate RSS in the rss_stat tracepoint
lib: percpu_counter_tree: add lazy tree activation
mm: keep the RSS counters of single-threaded processes exact
lib: percpu_counter_tree: add limit counters
lib: percpu_counter_tree: test the limit counters tools/testing/hpcc: add litmus tests of the memory ordering
mm: shmem: use a limit counter for the tmpfs size limit
lib: percpu_counter_tree: add the arity boot parameter
mm: add the rss_stat_batch boot parameter
lib: add a benchmark of hierarchical per-cpu counters

 .../admin-guide/kernel-parameters.txt         |   24 +
 Documentation/core-api/index.rst              |    1 +
 .../core-api/percpu-counter-tree.rst          |  145 ++
 MAINTAINERS                                   |   12 +
 fs/exec.c                                     |    5 +
 include/linux/mm.h                            |   28 +-
 include/linux/mm_types.h                      |   19 +-
 include/linux/percpu_counter_tree.h           |  445 +++++
 include/linux/shmem_fs.h                      |    3 +-
 include/trace/events/kmem.h                   |    3 +-
 init/main.c                                   |    3 +
 kernel/exit.c                                 |    3 +
 kernel/fork.c                                 |   61 +-
 lib/Kconfig                                   |   27 +
 lib/Makefile                                  |    1 +
 lib/percpu_counter_tree.c                     | 1776 +++++++++++++++++
 lib/tests/Makefile                            |    3 +
 lib/tests/percpu_counter_tree_bench.c         |  610 ++++++
 lib/tests/percpu_counter_tree_kunit.c         | 1240 ++++++++++++
 mm/shmem.c                                    |   33 +-
 tools/testing/hpcc/.gitignore                 |    2 +
 tools/testing/hpcc/Makefile                   |   18 +
 tools/testing/hpcc/include/hpcc_shim.h        |  253 +++
 tools/testing/hpcc/include/kunit/visibility.h |    2 +
 tools/testing/hpcc/include/linux/args.h       |    4 +
 tools/testing/hpcc/include/linux/atomic.h     |    2 +
 tools/testing/hpcc/include/linux/bug.h        |    2 +
 tools/testing/hpcc/include/linux/cache.h      |    2 +
 tools/testing/hpcc/include/linux/cpumask.h    |    2 +
 tools/testing/hpcc/include/linux/errno.h      |    3 +
 tools/testing/hpcc/include/linux/limits.h     |    2 +
 tools/testing/hpcc/include/linux/math.h       |    2 +
 .../testing/hpcc/include/linux/moduleparam.h  |   12 +
 tools/testing/hpcc/include/linux/percpu.h     |    2 +
 .../hpcc/include/linux/percpu_counter_tree.h  |    2 +
 tools/testing/hpcc/include/linux/preempt.h    |    2 +
 tools/testing/hpcc/include/linux/slab.h       |    2 +
 tools/testing/hpcc/litmus/README              |   61 +
 .../leave-first-precise-sum-relaxed.litmus    |   37 +
 .../litmus/leave-first-precise-sum.litmus     |   41 +
 .../litmus/limit-arrive-first-acquire.litmus  |   38 +
 .../limit-arrive-first-unordered.litmus       |   37 +
 .../hpcc/litmus/limit-arrive-first.litmus     |   41 +
 .../hpcc/litmus/limit-free-level0-nomb.litmus |   40 +
 .../hpcc/litmus/limit-free-level0.litmus      |   43 +
 .../hpcc/litmus/limit-free-root.litmus        |   42 +
 .../litmus/limit-last-checker-nomb.litmus     |   28 +
 .../hpcc/litmus/limit-last-checker.litmus     |   33 +
 .../hpcc/litmus/limit-undo-level0.litmus      |   35 +
 .../hpcc/litmus/limit-undo-root-rmb.litmus    |   30 +
 .../litmus/limit-undo-root-unordered.litmus   |   29 +
 .../hpcc/litmus/limit-undo-root.litmus        |   32 +
 .../litmus/publish-approximate-sum.litmus     |   40 +
 .../hpcc/litmus/publish-carry-normb.litmus    |   36 +
 .../testing/hpcc/litmus/publish-carry.litmus  |   43 +
 .../publish-precise-sum-noacquire.litmus      |   38 +
 .../hpcc/litmus/publish-precise-sum.litmus    |   44 +
 .../litmus/publish-update-norelease.litmus    |   34 +
 .../testing/hpcc/litmus/publish-update.litmus |   40 +
 tools/testing/hpcc/main.c                     |  892 +++++++++
 60 files changed, 6467 insertions(+), 23 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_bench.c
 create mode 100644 lib/tests/percpu_counter_tree_kunit.c
 create mode 100644 tools/testing/hpcc/.gitignore
 create mode 100644 tools/testing/hpcc/Makefile
 create mode 100644 tools/testing/hpcc/include/hpcc_shim.h
 create mode 100644 tools/testing/hpcc/include/kunit/visibility.h
 create mode 100644 tools/testing/hpcc/include/linux/args.h
 create mode 100644 tools/testing/hpcc/include/linux/atomic.h
 create mode 100644 tools/testing/hpcc/include/linux/bug.h
 create mode 100644 tools/testing/hpcc/include/linux/cache.h
 create mode 100644 tools/testing/hpcc/include/linux/cpumask.h
 create mode 100644 tools/testing/hpcc/include/linux/errno.h
 create mode 100644 tools/testing/hpcc/include/linux/limits.h
 create mode 100644 tools/testing/hpcc/include/linux/math.h
 create mode 100644 tools/testing/hpcc/include/linux/moduleparam.h
 create mode 100644 tools/testing/hpcc/include/linux/percpu.h
 create mode 100644 tools/testing/hpcc/include/linux/percpu_counter_tree.h
 create mode 100644 tools/testing/hpcc/include/linux/preempt.h
 create mode 100644 tools/testing/hpcc/include/linux/slab.h
 create mode 100644 tools/testing/hpcc/litmus/README
 create mode 100644 tools/testing/hpcc/litmus/leave-first-precise-sum-relaxed.litmus
 create mode 100644 tools/testing/hpcc/litmus/leave-first-precise-sum.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-arrive-first-acquire.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-arrive-first-unordered.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-arrive-first.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-free-level0-nomb.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-free-level0.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-free-root.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-last-checker-nomb.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-last-checker.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-undo-level0.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-undo-root-rmb.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-undo-root-unordered.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-undo-root.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-approximate-sum.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-carry-normb.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-carry.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-precise-sum-noacquire.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-precise-sum.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-update-norelease.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-update.litmus
 create mode 100644 tools/testing/hpcc/main.c

base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb

Signature · 1 line
2.47.3
author reviewer
#1 lore raw

RFC PATCH v25 1/14 lib: introduce hierarchical per-cpu counters

Introduce hierarchical per-cpu counters, struct percpu_counter_tree: a split counter whose approximate sum stays within a fixed bound of its precise sum, without taking a global lock on updates. They are meant for counters updated from many CPUs whose approximation is read often, such as the RSS counters of an mm. A following patch uses them for the RSS counters, to bound their inaccuracy on large many-core systems [1].

* 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.

* Design

The hierarchical per-CPU counters propagate a sum approximation through an N-way tree. When reaching the batch size, the carry is propagated up the tree, whose fan-out at each level is selected at boot from nr_cpu_ids. The batch size of each level is the batch size of the prior level multiplied by the prior level's fan-out.

The following diagram illustrates the propagation with 8 CPUs through a binary tree. This is not an actual configuration: at 8 CPUs, the default tree is flat (see the default shapes below). CPU c propagates into item (c & (L - 1)) of a level holding L items, so the CPUs are listed in bit-reversed order:

Level 3:  0  (root)
          |   \
          |         \
          |               \
Level 2:  0                   1
          | \                 | \
          |    \              |    \
          |       \           |       \
Level 1:  0         2         1         3
          | \       | \       | \       | \
          |  \      |  \      |  \      |  \
          |   \     |   \     |   \     |   \
Level 0:  0    4    2    6    1    5    3    7

Each counter below the root keeps a residual: once it reaches its batch size in either direction, it propagates its multiples of the batch size and subtracts them, which leaves a residual within (-batch, +batch). This hysteresis absorbs updates going back and forth around a batch size boundary, instead of propagating them up to the root on each update. The residual moves in steps of the counter's input: 1 for the per-cpu counters, which receive the updates, and BATCH(N - 1), the batch size of the level below, for the counters of level N, which only receive its carries. The largest residual is therefore batch - 1 at level 0, and BATCH(N) - BATCH(N - 1) at level N. The approximate sum is the precise sum minus the residuals, so it is within the same distance of the precise sum in both directions:

accuracy = nr_cpu_ids * (batch - 1) +

             sum(N >= 1) (BATCH(N) - BATCH(N - 1)) * nr_items(N)

The level 0 per-cpu counters are signed bytes, updated with a this_cpu_try_cmpxchg() loop, which limits the batch size to 128.

Up to 32 CPUs, the tree is flat: the per-cpu counters propagate directly to the root, like struct percpu_counter. From 33 to 64 CPUs, the per-cpu counters propagate to 4 intermediate counters, each shared by up to 16 CPUs, so the carries of all CPUs do not contend on the root. Beyond, each level has a fan-out of 8: a remaining order of 1 gives the root a fan-out of 16, and a remaining order of 2 adds a level with a fan-out of 4 below the root. With a fixed batch size, the maximum inaccuracy grows with O(n*log(n)) as the number of CPUs increases, compared to O(n^2) for struct percpu_counter, whose batch size grows with the number of CPUs. For example, at 384 logical CPUs with a batch size of 32, the bound is 40576, compared to 294528 for a struct percpu_counter with its default batch size of 768.

* CPU hotplug

Like the per-cpu data of struct percpu_counter, the tree is sized at boot, and is not reshaped on CPU hotplug. The level 0 residual of an offline CPU stays in place: the precise sum still reads it, and the bound, computed from nr_cpu_ids, still holds. Unlike the default batch size of struct percpu_counter, which follows the number of online CPUs, the bound does not shrink when fewer CPUs are online. When the possible CPUs are sparse, the tree is still shaped for nr_cpu_ids, the highest possible CPU number plus one, and the bound also counts the level 0 residuals of the missing CPUs: it holds, but cannot be reached.

* Memory Use

Each counter uses a 32-byte struct percpu_counter_tree, one byte of per-cpu data per possible CPU, and its tree items. percpu_counter_tree_init_many() allocates the per-cpu data and the tree items, whose sizes depend on the number of possible CPUs and on nr_cpu_ids, so struct percpu_counter_tree has a fixed size. The items at the same tree position of all the counters initialized together are packed in a cache line aligned block, so a set of counters updated together, such as the 4 RSS counters of an mm, shares cache lines without false sharing between CPUs updating different branches of the tree. When the items of a tree position fit in a cache line, the tree items come from a slab cache created by percpu_counter_tree_subsystem_init(), which runs once the slab allocator is up.

The memory use of nr_counters initialized together, up to 8, on a 64-bit arch with 64-byte cache lines is:

nr_counters * 32 + ALIGN(nr_counters, 4) * nr_possible_cpus
+ nr_items * 64

as the per-cpu allocator rounds sizes up to 4 bytes. The tree is shaped for nr_cpu_ids rounded up to a power of 2: nr_items is 1 (the root) up to 32 CPUs, 5 up to 64, 17 up to 128, 41 up to 256, 73 up to 512, 145 up to 1024 and 585 up to 4096. In comparison, a struct percpu_counter uses 40 bytes and 4 bytes of per-cpu data per possible CPU.

For a set of 4 counters, the hierarchical counters use less memory than as many struct percpu_counter from 3 to 64 CPUs, and beyond when the number of CPUs is a power of 2 (at most 0.89 times as much). Between powers of 2, fewer CPUs share the cost of the tree items: 0.94 to 1.09 times at 3 * 2^n CPUs (96, 192, 384, ...), and up to 1.47 times just above a power of 2 (129 CPUs). A lone counter uses one item of each cache line: 3.0 to 3.5 times the memory of a struct percpu_counter when the number of CPUs is a power of 2 beyond 64, and up to 5.7 times just above.

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 Andrew Morton <[email protected]>

---
Changes since v23:
- Read a zeroed counter as 0 in percpu_counter_tree_approximate_sum(), like a zeroed struct percpu_counter, and document it: sparc64 init_new_context() reads the RSS counters after mm_init() zeroes them, before their initialization. (Noted in Sashiko's review data, not in its report.)

Changes since v22:
- Refactor configuration table, remove duplicated definitions, document heuristic, add table content validation, run by the KUnit and userspace tests.
- Allocate the per-cpu counters and the tree items in percpu_counter_tree_init_many(), instead of taking tree items from the caller: remove percpu_counter_tree_items_size(), PERCPU_COUNTER_TREE_ITEMS_STATIC_SIZE and the items argument of the init functions. struct percpu_counter_tree has a fixed size of 32 bytes, down from 64.
- Call percpu_counter_tree_subsystem_init() after mm_core_init(), once its boot parameters are parsed and slab is up, before the first counter is used, and warn about counters initialized before it.
- Use signed bytes for the level 0 per-cpu counters, with the same hysteresis as the intermediate levels, updated with a this_cpu_try_cmpxchg() loop. Limit the batch size to 128.
- Pack the tree items of the counters initialized together by percpu_counter_tree_init_many() in cache lines, allocated from a slab cache when the items of a tree position fit in one cache line.
- Use a flat tree up to 32 CPUs, a fan-out of 16 then 4 from 33 to 64 CPUs to keep the carries of all CPUs from contending on the root, and a fan-out of 8 beyond, with a root fan-out of 16 for a remaining order of 1, to match the memory footprint and accuracy of struct percpu_counter at low CPU counts and bound the inaccuracy with O(n*log(n)) at high CPU counts.
- Print the tree shape at boot.
- Document that the accuracy range is a property of settled counters. (Reported by Sashiko.)
- Add a diagram of the approximation ranges above compare_delta(). (Reported by Sashiko.)
- Introduce wrapped_delta(), and document that comparisons are valid only for counters differing by less than LONG_MAX. (Reported by Sashiko.)
- Fix the direction of the approximation margins in the comparison functions. They were swapped, which returned wrong definitive answers when 2^arity of a level exceeds the batch size (batch size 2 from 9 CPUs, batch size 4 from 65 CPUs).
- Add hysteresis to the intermediate tree levels: they keep a residual within (-batch, +batch) of their level, and only propagate once it reaches their batch size, so updates going back and forth around a batch size boundary no longer propagate up to the root on each update.
- Replace percpu_counter_tree_approximate_accuracy_range() and its "under" and "over" ranges by a single accuracy, the exact bound of the residuals, which is the same in both directions:
percpu_counter_tree_approximate_accuracy().
- Add percpu_counter_tree_check_residuals() for the tests: it checks the residuals of the intermediate counters, and that no carry was lost or duplicated.
- Extract the carries of the intermediate counters with a cmpxchg on the value returned by the addition, so concurrent updaters never subtract a carry computed from a stale residual, and explain why relaxed ordering is sufficient.
- Read the level 0 counters with READ_ONCE() in the precise sum.
- Document that percpu_counter_tree_set() must not run concurrently with updates.
- Add the documentation to the core-api toctree.
- Fix the propagation diagram to match the CPU to item mapping.
- Mark boot-time topology state __ro_after_init, use pr_err().
- Validate the batch size on UP as on SMP.
- Fix the sign of the !CONFIG_SMP value comparisons, and compare on the wrapped difference as on SMP.
- Add a MAINTAINERS entry.
- Fix checkpatch warnings.
- Fix documentation typos.

---
 Documentation/core-api/index.rst              |    1 +
 .../core-api/percpu-counter-tree.rst          |  109 ++
 MAINTAINERS                                   |    9 +
 include/linux/percpu_counter_tree.h           |  301 +++++
 init/main.c                                   |    3 +
 lib/Makefile                                  |    1 +
 lib/percpu_counter_tree.c                     | 1119 +++++++++++++++++
 7 files changed, 1543 insertions(+)
 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/index.rst +1 -0
index 92f91c6a0d79..fe03cefc1734 100644
@@ -48,6 +48,7 @@ Library functionality that is used throughout the kernel.
    generic-radix-tree
    packing
    this_cpu_ops
+   percpu-counter-tree
    timekeeping
    errseq
    wrappers/atomic_t
Documentation/core-api/percpu-counter-tree.rst new file +109 -0

109 lines not on this page · raw message

MAINTAINERS +9 -0
index 222b7fc2c3aa..d0829c379222 100644
@@ -11950,6 +11950,15 @@ L:	[email protected]
 S:	Maintained
 F:	drivers/hid/hid-logitech-hidpp.c
 
+HIERARCHICAL PER-CPU COUNTERS (HPCC)
+M:	Mathieu Desnoyers <[email protected]>
+L:	[email protected]
+L:	[email protected]
+S:	Supported
+F:	Documentation/core-api/percpu-counter-tree.rst
+F:	include/linux/percpu_counter_tree.h
+F:	lib/percpu_counter_tree.c
+
 HIGH-RESOLUTION TIMERS, TIMER WHEEL, CLOCKEVENTS
 M:	Anna-Maria Behnsen <[email protected]>
 M:	Frederic Weisbecker <[email protected]>
include/linux/percpu_counter_tree.h new file +301 -0

301 lines not on this page · raw message

init/main.c +3 -0
index 7b0c8c34e6a9..d9614cc5bd63 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>
@@ -1104,6 +1105,8 @@ void start_kernel(void)
 	sort_main_extable();
 	trap_init();
 	mm_core_init();
+	/* After parsing its boot parameters and setting up slab, before the first counter. */
+	percpu_counter_tree_subsystem_init();
 	maple_tree_init();
 	poking_init();
 	ftrace_init();
lib/Makefile +1 -0
index a2afe954805c..07410b1d20a3 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 +1119 -0

1,119 lines not on this page · raw message

Signature · 1 line
2.47.3
author reviewer
#2 lore raw

RFC PATCH v25 2/14 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.
- Contended carries: rounds of concurrent carries from many CPUs into the tree items they share.

The multi-threaded tests run their workers on at most 64 CPUs, spread evenly across the online CPUs, so their run time does not grow with the size of the machine.

The single-threaded and saturation tests run each update on its target CPU with work_on_cpu(), and the multi-threaded tests queue their updates on a CPU intensive workqueue, whose workers are reused across rounds and can preempt each other on a CPU. The single and multi-threaded tests stop early after a time bound, so they complete on large virtual machines where cross-CPU wakeups are slow.

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.
- Check the residuals of the tree items, and that no carry was lost or duplicated, whenever the counters are settled, including between the rounds of contended carries.
- Saturate a counter upward and downward to its worst-case approximation errors, check that it reaches the edges of its accuracy range exactly when all possible CPUs are online, and validate the comparisons at the edges of its precise range.

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 Andrew Morton <[email protected]>

---
Changes since v23:
- Select the first online CPU of the single-threaded tests with the CPU hotplug lock held. (Reported by Sashiko.)
- Publish the start flag of the contended carries test with smp_store_release(), paired with smp_load_acquire() in the workers. (Reported by Sashiko.)
- Check whether every possible CPU is online with the CPU hotplug lock held in the saturated counter comparison test. (Reported by Sashiko.)
- Check that a zeroed counter reads as 0.

Changes since v22:
- Fix CPU hotplug locking, module unload, and error handling: ERR_PTR handling, a test data leak, allocation sizing, the cpu & ~1 skip, a lost worker when kthread_stop() runs before the thread function, and a task_struct reaping race. (Reported by Sashiko.)
- Merge the four multi-thread increment tests into one function taking a CPU selector.
- Add a saturated counter comparison test, upward and downward.
- Add a contended carries test.
- Bound the number of CPUs running workers in the multi-threaded tests.
- Check the residuals and carries of settled counters.
- Add a configuration table validation test.
- Run the updates with work_on_cpu() and a workqueue rather than creating a kthread for each update, and bound the run time of the single and multi-threaded tests, which timed out with 192 CPUs in a virtual machine.
- Fix checkpatch warnings.

Changes since v19:
- Rename config option to PERCPU_COUNTER_TREE_KUNIT_TEST.

---
 MAINTAINERS                           |   1 +
 lib/Kconfig                           |  12 +
 lib/tests/Makefile                    |   2 +
 lib/tests/percpu_counter_tree_kunit.c | 845 ++++++++++++++++++++++++++
 4 files changed, 860 insertions(+)
 create mode 100644 lib/tests/percpu_counter_tree_kunit.c
MAINTAINERS +1 -0
index d0829c379222..a4e4badc0648 100644
@@ -11958,6 +11958,7 @@ S:	Supported
 F:	Documentation/core-api/percpu-counter-tree.rst
 F:	include/linux/percpu_counter_tree.h
 F:	lib/percpu_counter_tree.c
+F:	lib/tests/percpu_counter_tree_kunit.c
 
 HIGH-RESOLUTION TIMERS, TIMER WHEEL, CLOCKEVENTS
 M:	Anna-Maria Behnsen <[email protected]>
lib/Kconfig +12 -0
index 1e42f5167c68..3921177a0d24 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 df0537e1b91f..e98687da8706 100644
@@ -59,4 +59,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 +845 -0

845 lines not on this page · raw message

Signature · 1 line
2.47.3
author reviewer
#3 lore raw

RFC PATCH v25 3/14 mm: use hierarchical per-cpu counters for the RSS counters

In reply to Mathieu Desnoyers

Use hierarchical per-cpu counters for RSS tracking to bound the inaccuracy of the per-mm RSS approximation on large many-core systems [1].

The approximation is read by /proc/PID/stat (rss), by the RSS high watermark (VmHWM in /proc/PID/status, getrusage() ru_maxrss, taskstats hiwater_rss), by the taskstats integral RSS, by NUMA balancing to scale its scan period, and by the mark_victim OOM tracepoint. /proc/PID/status, /proc/PID/statm, the OOM killer and the rss_stat tracepoint use precise sums, which iterate over all CPUs for each read:
the tracepoint since commit f1a7941243c1 ("mm: convert mm's rss stats into percpu_counter"), and the others since commit 82241a83cd15 ("mm:
fix the inaccurate memory statistics issue for users") and commit 5898aa8f9a0b ("mm: fix OOM killer inaccuracy on large many-core systems").

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 precise per-cpu counter sum for each counter value query:
Requires iteration on each possible CPU 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)

Methodology:

Comparing the current upstream implementation with the hierarchical counters is done with a debug patch, which keeps both implementations wired up in parallel, and a test program, neither part of this series. The single-process, single-threaded program hops randomly across CPUs in the system, calling mmap(2) and munmap(2) on random CPUs, keeping track of an array of 100000 mapping slots, randomly choosing slots to either map 1 to 16 pages or unmap them.

get_mm_counter() is instrumented to compare both counter approximations to the precise value, and to record the largest delta of each. The test runs in a KVM guest with 384 vCPUs, each pinned to its own CPU of the test hardware, with the NUMA topology of the host.

With the counters of this patch, before the single-threaded mode added later in the series, the upstream implementation counter approximation reaches an 830MB delta from the precise value within the first seconds, while the mappings accumulate, compared to a 106MB delta with the hierarchical counter. The hierarchical counter approximation is guaranteed to be within 158.5MB of the precise value in both directions on that hardware topology, compared to 1.1GB for the upstream implementation (384 CPUs * 767 pages).

* Fast path implementation comparison

The new percpu_counter_tree_add() updates a per-cpu byte with a this_cpu_try_cmpxchg() loop on the fast path, like the upstream percpu_counter_add_batch(). When the per-cpu residual reaches the batch size, it calls a slow path which "trickles up" the carry to upper level counters with atomic_add_return(), each of them keeping its own residual.

In comparison, the upstream percpu_counter_add_batch() takes a global raw_spin_lock_irqsave() when reaching the batch size, and flushes the whole per-cpu count into the global count.

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 each shared by a fraction of the CPUs.

* Benchmarks

Using will-it-scale page_fault1 benchmarks to compare the upstream counters to the hierarchical counters of this patch. This is done with hyperthreading disabled at runtime, so the counter tree keeps its shape for 384 logical CPUs, while the upstream batch size follows the 192 online ones (384 instead of 768). The differences are within the boot-to-boot spread of up to 3%, and the multi-threaded runs, bound by the mmap_lock, have a standard deviation of 5% to 11%: no regression is measured, and no gain is claimed. The numbers with the whole series are in patch 7 and the cover letter.

                                          upstream   hierarchical     delta
page_fault1_processes -s 100 -t 1           544932         557092     +2.2%
page_fault1_threads -s 100 -t 1             547501         557742     +1.9%
page_fault1_processes -s 100 -t 96        37374404       37580199     +0.6%
page_fault1_threads -s 100 -t 96           2311884        2299998     -0.5%
page_fault1_processes -s 100 -t 192       69491758       70590309     +1.6%
page_fault1_threads -s 100 -t 192          2284108        2271423     -0.6%

* Memory Use

Each mm_struct holds NR_MM_COUNTERS (4) counters, initialized together by percpu_counter_tree_init_many() with a batch size of 32, so their tree items share cache lines. Per mm, on a 64-bit arch with 64-byte cache lines, compared to the upstream percpu counters, along with the maximum inaccuracy of each counter in pages:

Bytes per mm Accuracy (pages)
nr_cpus fan-out hpcc upstream hpcc upstream

        2 2           200       192      +-62        +-62
       16 16          256       416     +-496       +-496
       64 16,4        704      1184    +-3904      +-8128
      128 8,16       1728      2208    +-7552     +-32640
      256 8,4,8      3776      4256   +-21248    +-130816
      384 8,8,8      6336      6304   +-40576    +-294528
      512 8,8,8      6848      8352   +-44544    +-523776
     1024 8,8,16    13504     16544   +-89088   +-2096128
     4096 8,8,8,8   53952     65696  +-471040  +-33550336

This counts the 4 counter structures, their per-cpu data, and the tree items, without the rounding of the slab cache holding them. The fan-out is listed from the per-cpu counters to the root. Up to 32 CPUs, the tree is flat. Up to 16 CPUs, its accuracy matches the upstream counters, whose batch size of max(32, 2 * nr_cpus) grows beyond, making them less accurate than the hierarchical counters, except from 33 to 39 CPUs, where the intermediate counters of the 16,4 tree make the hierarchical counters up to 1.37 times less accurate.

The hierarchical counters use less memory than the upstream counters from 3 to 64 CPUs. The tree is shaped for nr_cpus rounded up to a power of 2: when nr_cpus is a power of 2, they also use less memory beyond 64 CPUs (at most 0.89 times as much). Between powers of 2, fewer CPUs share the cost of the tree items: 1.01 times at 384 logical CPUs, 1.09 at 192 and 0.94 at 96, and up to 1.47 times just above a power of 2 (at 129 CPUs, 1.23 at 65 and 1.36 at 257).

* mm_struct layout

percpu_counter_tree_init_many() allocates the per-cpu data and the tree items of the RSS counters, so their size in mm_struct does not depend on the number of CPUs: struct mm_struct shrinks by 32 bytes, as a struct percpu_counter_tree is 32 bytes, compared to 40 for a struct percpu_counter.

* rss_stat tracepoint

The rss_stat tracepoint keeps reporting the precise sum, now computed from the hierarchical per-cpu counter.

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 Andrew Morton <[email protected]>

---
Changes since v22:
- The library allocates the per-cpu counters and the tree items of the RSS counters: mm_struct holds no tree items, and the static init_mm and efi_mm need no change.
- check_mm(): sum each RSS counter once.
- Keep reporting the precise sum in the rss_stat tracepoint. Switching it to the approximation is done by a separate patch.
- Initialize the 4 RSS counters together so their tree items share cache lines.
- Fix checkpatch warnings.

---
 include/linux/mm.h          | 10 +++++-----
 include/linux/mm_types.h    |  3 ++-
 include/trace/events/kmem.h |  3 +--
 kernel/fork.c               | 13 +++++++++----
 4 files changed, 17 insertions(+), 12 deletions(-)
include/linux/mm.h +5 -5
index 6af3b7008f1a..2b40f382da35 100644
@@ -3611,33 +3611,33 @@ static inline bool get_user_page_fast_only(unsigned long addr,
  */
 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 +2 -1
index 1ed35d258d2e..20b4517b7329 100644
@@ -19,6 +19,7 @@
 #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>
@@ -1350,7 +1351,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;
 
include/trace/events/kmem.h +1 -2
index cd7920c81f85..ac4c96db7638 100644
@@ -448,8 +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])
-							    << PAGE_SHIFT);
+		__entry->size = get_mm_counter_sum(mm, member) << PAGE_SHIFT;
 	),
 
 	TP_printk("mm_id=%u curr=%d type=%s size=%ldB",
kernel/fork.c +9 -4
index 5efceb8d58a7..d9bdaf2bd998 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,7 +638,7 @@ 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]);
+		long x = percpu_counter_tree_precise_sum(&mm->rss_stat[i]);
 
 		if (unlikely(x)) {
 			pr_alert("BUG: Bad rss-counter state mm:%p type:%s val:%ld Comm:%s Pid:%d\n",
@@ -738,7 +743,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);
 }
@@ -1143,8 +1148,8 @@ 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, NR_MM_COUNTERS, RSS_STAT_BATCH_SIZE,
+					  GFP_KERNEL_ACCOUNT))
 		goto fail_pcpu;
 
 	lru_gen_init_mm(mm);
Signature · 1 line
2.47.3
author reviewer
#4 lore raw

RFC PATCH v25 4/14 tools/testing/hpcc: add userspace test of hierarchical per-CPU counters

In reply to Mathieu Desnoyers

The KUnit test only covers the topology of the machine it runs on. Add a userspace test which builds lib/percpu_counter_tree.c with a simulated topology, which allows testing every supported tree configuration on a single machine, following the approach of tools/testing/vma and tools/testing/radix-tree.

A small shim header provides the kernel environment needed by the library, on top of tools/include: per-CPU data is an array indexed by the simulated current CPU, and atomic operations are plain operations, because the test is single-threaded. It therefore only covers settled counters.

Validate the configuration table, then, for each simulated number of CPUs (1 to 65536, up to 1048576 with -a) and batch size (2 to 128):

- Saturate the counter upward and downward: leave every tree item with its largest positive (or negative) residual which has not been propagated yet, check that the distance between the precise and approximate sums matches the residual capacity of the tree, computed from the configuration table, which is exactly the accuracy range, the same in both directions, and check the accuracy range contract and the comparison functions in these worst-case states. A lost carry fails the saturation rather than hanging it.

- Random walk: apply random increments from random CPUs to two counters, and check the accuracy range contract and the comparison functions against shadow sums after each increment.

Along with the accuracy range contract, check the residuals of the tree items, and that no carry was lost or duplicated.

The comparison checks include the edges of the possible precise range. The approximate comparison against a value must be definitive exactly outside of [approx - accuracy, approx + accuracy].

Usage:

make -C tools/testing/hpcc
tools/testing/hpcc/hpcc [-a]

---
Changes since v23:
- Destroy the counters already initialized when an initialization fails in test_saturated() and test_random_walk(). (Reported by Sashiko.)

---
 MAINTAINERS                                   |   1 +
 tools/testing/hpcc/.gitignore                 |   2 +
 tools/testing/hpcc/Makefile                   |  18 +
 tools/testing/hpcc/include/hpcc_shim.h        | 177 ++++++++
 tools/testing/hpcc/include/kunit/visibility.h |   2 +
 tools/testing/hpcc/include/linux/args.h       |   4 +
 tools/testing/hpcc/include/linux/atomic.h     |   2 +
 tools/testing/hpcc/include/linux/bug.h        |   2 +
 tools/testing/hpcc/include/linux/cache.h      |   2 +
 tools/testing/hpcc/include/linux/cpumask.h    |   2 +
 tools/testing/hpcc/include/linux/errno.h      |   3 +
 tools/testing/hpcc/include/linux/limits.h     |   2 +
 tools/testing/hpcc/include/linux/math.h       |   2 +
 tools/testing/hpcc/include/linux/percpu.h     |   2 +
 .../hpcc/include/linux/percpu_counter_tree.h  |   2 +
 tools/testing/hpcc/include/linux/preempt.h    |   2 +
 tools/testing/hpcc/include/linux/slab.h       |   2 +
 tools/testing/hpcc/main.c                     | 427 ++++++++++++++++++
 18 files changed, 654 insertions(+)
 create mode 100644 tools/testing/hpcc/.gitignore
 create mode 100644 tools/testing/hpcc/Makefile
 create mode 100644 tools/testing/hpcc/include/hpcc_shim.h
 create mode 100644 tools/testing/hpcc/include/kunit/visibility.h
 create mode 100644 tools/testing/hpcc/include/linux/args.h
 create mode 100644 tools/testing/hpcc/include/linux/atomic.h
 create mode 100644 tools/testing/hpcc/include/linux/bug.h
 create mode 100644 tools/testing/hpcc/include/linux/cache.h
 create mode 100644 tools/testing/hpcc/include/linux/cpumask.h
 create mode 100644 tools/testing/hpcc/include/linux/errno.h
 create mode 100644 tools/testing/hpcc/include/linux/limits.h
 create mode 100644 tools/testing/hpcc/include/linux/math.h
 create mode 100644 tools/testing/hpcc/include/linux/percpu.h
 create mode 100644 tools/testing/hpcc/include/linux/percpu_counter_tree.h
 create mode 100644 tools/testing/hpcc/include/linux/preempt.h
 create mode 100644 tools/testing/hpcc/include/linux/slab.h
 create mode 100644 tools/testing/hpcc/main.c
MAINTAINERS +1 -0
index a4e4badc0648..c9b266a5df54 100644
@@ -11959,6 +11959,7 @@ F:	Documentation/core-api/percpu-counter-tree.rst
 F:	include/linux/percpu_counter_tree.h
 F:	lib/percpu_counter_tree.c
 F:	lib/tests/percpu_counter_tree_kunit.c
+F:	tools/testing/hpcc/
 
 HIGH-RESOLUTION TIMERS, TIMER WHEEL, CLOCKEVENTS
 M:	Anna-Maria Behnsen <[email protected]>
tools/testing/hpcc/.gitignore new file +2 -0
new file mode 100644
index 000000000000..f362a8a46868
@@ -0,0 +1,2 @@
+# SPDX-License-Identifier: GPL-2.0+ OR MIT
+hpcc
tools/testing/hpcc/Makefile new file +18 -0
new file mode 100644
index 000000000000..e4758643a3f0
@@ -0,0 +1,18 @@
+# SPDX-License-Identifier: GPL-2.0+ OR MIT
+
+.PHONY: default clean
+
+default: hpcc
+
+CFLAGS += -O2 -g -Wall -I./include -I../../include -fno-strict-overflow -fno-strict-aliasing
+CFLAGS += -DCONFIG_SMP -DCONFIG_KUNIT=1 -D'NR_CPUS=(1U << 20)'
+
+DEPS = ../../../lib/percpu_counter_tree.c \
+	../../../include/linux/percpu_counter_tree.h \
+	include/hpcc_shim.h
+
+hpcc: main.c $(DEPS)
+	$(CC) $(CFLAGS) -o $@ main.c $(LDLIBS)
+
+clean:
+	$(RM) hpcc
tools/testing/hpcc/include/hpcc_shim.h new file +177 -0

177 lines not on this page · raw message

tools/testing/hpcc/include/kunit/visibility.h new file +2 -0
new file mode 100644
index 000000000000..dfcbfd01a415
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#define EXPORT_SYMBOL_IF_KUNIT(symbol)
tools/testing/hpcc/include/linux/args.h new file +4 -0
new file mode 100644
index 000000000000..0c00a85fdd21
@@ -0,0 +1,4 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+/* Also defined by the C library <sys/cdefs.h>. */
+#undef __CONCAT
+#include "../../../../../include/linux/args.h"
tools/testing/hpcc/include/linux/atomic.h new file +2 -0
new file mode 100644
index 000000000000..b2aa26415cca
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
tools/testing/hpcc/include/linux/bug.h new file +2 -0
new file mode 100644
index 000000000000..b2aa26415cca
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
tools/testing/hpcc/include/linux/cache.h new file +2 -0
new file mode 100644
index 000000000000..b2aa26415cca
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
tools/testing/hpcc/include/linux/cpumask.h new file +2 -0
new file mode 100644
index 000000000000..b2aa26415cca
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
tools/testing/hpcc/include/linux/errno.h new file +3 -0
new file mode 100644
index 000000000000..45fdd60261e7
@@ -0,0 +1,3 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+/* Also included by the C library <errno.h>: only provide the error numbers. */
+#include <asm/errno.h>
tools/testing/hpcc/include/linux/limits.h new file +2 -0
new file mode 100644
index 000000000000..b2aa26415cca
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
tools/testing/hpcc/include/linux/math.h new file +2 -0
new file mode 100644
index 000000000000..b2aa26415cca
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
tools/testing/hpcc/include/linux/percpu.h new file +2 -0
new file mode 100644
index 000000000000..b2aa26415cca
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
tools/testing/hpcc/include/linux/percpu_counter_tree.h new file +2 -0
new file mode 100644
index 000000000000..065a2aca4d5b
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../../../../../include/linux/percpu_counter_tree.h"
tools/testing/hpcc/include/linux/preempt.h new file +2 -0
new file mode 100644
index 000000000000..b2aa26415cca
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
tools/testing/hpcc/include/linux/slab.h new file +2 -0
new file mode 100644
index 000000000000..b2aa26415cca
@@ -0,0 +1,2 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
tools/testing/hpcc/main.c new file +427 -0

427 lines not on this page · raw message

Signature · 1 line
2.47.3
author reviewer
#5 lore raw

RFC PATCH v25 5/14 mm: report the approximate RSS in the rss_stat tracepoint

In reply to Mathieu Desnoyers

The rss_stat tracepoint is emitted on every RSS update, including each page fault. When it is enabled, it reports the precise sum of the RSS counter, which iterates over all possible CPUs for each event: 384 per page fault on a machine with 384 logical CPUs.

Report the approximate sum of the hierarchical per-cpu counter instead, through get_mm_counter(), which reads the root of the counter tree. The size field of the event, the RSS counter after the update, is therefore within the accuracy bound of the counter from the precise value: within 158.5MB on a machine with 384 logical CPUs and 4kB pages.

The tracepoint reports the precise sum since commit f1a7941243c1 ("mm:
convert mm's rss stats into percpu_counter"). Before that, it reported an atomic counter which only received the per-task cached updates in batches.

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 Andrew Morton <[email protected]>

---
Changes since v22:
- Split from "mm: improve RSS counter approximation accuracy for proc interfaces", which now keeps reporting the precise sum.

---
 include/trace/events/kmem.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
include/trace/events/kmem.h +1 -1
index ac4c96db7638..8ee6d5df5961 100644
@@ -448,7 +448,7 @@ TRACE_EVENT(rss_stat,
 		 */
 		__entry->curr = current->mm == mm && !(current->flags & PF_KTHREAD);
 		__entry->member = member;
-		__entry->size = get_mm_counter_sum(mm, member) << PAGE_SHIFT;
+		__entry->size = get_mm_counter(mm, member) << PAGE_SHIFT;
 	),
 
 	TP_printk("mm_id=%u curr=%d type=%s size=%ldB",
Signature · 1 line
2.47.3
author reviewer
#6 lore raw

RFC PATCH v25 6/14 lib: percpu_counter_tree: add lazy tree activation

In reply to Mathieu Desnoyers

Add counters which start without their tree, for counters which may never need its scalability, such as the RSS counters of a single-threaded process.

percpu_counter_tree_init_many_lazy() initializes counters without allocating their per-cpu counters and tree items. Until percpu_counter_tree_activate_many() allocates and publishes them, the counters are exact:

- percpu_counter_tree_add_owner() adds to the bias of the counter, without atomic instruction. Its calls for a given counter must not run concurrently with each other: they come from a single context, the owner chosen by the user of the counters, such as a task.
- percpu_counter_tree_add() adds atomically to a new atomic bias of the counter, for any other updater.

The precise and approximate sums read both biases, in O(1). The activation does not move these values: the sums keep reading them along with the tree, so updates racing with the activation are not lost, whichever side of it they land on. The bias only has the owner as writer, and the atomic bias only receives atomic additions, before and after the activation. After the activation, both update functions add to the tree, and percpu_counter_tree_active() reports it, so a user can skip selecting between them. The accuracy range of a lazily initialized counter is the range of its tree, even before activation, which keeps the comparison functions correct across an activation.

The activations of the same counters must be serialized by the caller, for instance with a mutex: a concurrent activation would publish a second tree. The activation publishes the root, then the per-cpu counters, of each counter in order, with release ordering. Once the last counter is active, the activation is complete, so a caller which sees it active can skip the activation and its serialization; it may not observe the other counters active yet, which only delays their updates going to the tree. The update functions only reach the per-cpu counters through their published pointer, which orders their initialization before their use by address dependency, as for rcu_dereference(), without an acquire on the fast path. The approximate sum reaches the root the same way. The carry path reads the root pointer after the per-cpu counters pointer with a read barrier between them, and the precise sum reads the per-cpu counters pointer with an acquire.

struct percpu_counter_tree grows from 32 to 40 bytes with the atomic bias, the size of struct percpu_counter.

Test the lazy counters:

- KUnit: exact sums before activation with owner and atomic updates, set(), idempotent activation, destruction without activation, and an activation racing with an owner and remote updaters on other CPUs, which also activate the tree when released, serialized by a mutex, checking that the counter is exact while they pause, that the tree is active once an activation returns, and that no update is lost across the activations.
- Userspace test: random owner and atomic updates from random CPUs, exact before the tree is activated halfway, with the accuracy and comparison checks after each update. The test checks that the activation allocates one tree, that activating again allocates nothing, and that destroying the counter frees the tree. The shim provides the ordering primitives as plain accesses.

---
Changes since v24:
- Release the workers of the activation race test with smp_store_release(), paired with smp_load_acquire() in the workers, so that the test reads the counter before they resume. (Reported by Sashiko.)

Changes since v23:
- The NULL check of approx_sum in percpu_counter_tree_approximate_sum() moved to patch 1.

---
 .../core-api/percpu-counter-tree.rst          |  28 ++
 include/linux/percpu_counter_tree.h           |  85 ++++-
 lib/percpu_counter_tree.c                     | 315 ++++++++++++++++--
 lib/tests/percpu_counter_tree_kunit.c         | 223 +++++++++++++
 tools/testing/hpcc/include/hpcc_shim.h        |  28 +-
 tools/testing/hpcc/main.c                     |  47 +++
 6 files changed, 680 insertions(+), 46 deletions(-)
Documentation/core-api/percpu-counter-tree.rst +28 -0
index 6b381deacd83..138e9b74b0c8 100644
@@ -74,6 +74,34 @@ takes no lock: an update which carries from the per-cpu counter to the
 upper levels can be counted in part, the residual it left below read and
 its carry missed on the way up.
 
+Lazy Tree Activation
+====================
+
+Counters initialized with percpu_counter_tree_init_many_lazy() start
+without their per-cpu counters and tree items, for counters which may
+never need the scalability of the tree. Until
+percpu_counter_tree_activate_many() allocates and publishes the tree,
+the counters are exact:
+
+ * percpu_counter_tree_add_owner() adds to the bias of the counter,
+   written only by its owner, a single context chosen by the user of the
+   counters, such as a task, without atomic instruction.
+
+ * percpu_counter_tree_add() adds to the atomic bias of the counter, for
+   any other updater.
+
+The precise and approximate sums read both, in O(1), and count each
+update whole. The activation does not move these values: the sums keep
+reading them along with the tree, so updates racing with the activation
+are not lost, whichever side of it they land on. The bias only has the
+owner as writer, and the atomic bias only receives atomic additions,
+before and after the activation. After activation, both update functions
+add to the tree, and the approximation has the accuracy of the tree.
+
+The activations of the same counters must be serialized by the caller:
+a concurrent activation would publish a second tree and lose the
+updates made to the first.
+
 Use Cases
 =========
 
include/linux/percpu_counter_tree.h +78 -7

129 lines not on this page · raw message

lib/percpu_counter_tree.c +279 -36

443 lines not on this page · raw message

lib/tests/percpu_counter_tree_kunit.c +223 -0

241 lines not on this page · raw message

tools/testing/hpcc/include/hpcc_shim.h +25 -3
index 7e268de984c6..d321c8363b0b 100644
@@ -68,6 +68,9 @@ static inline int get_count_order(unsigned int count)
 #define atomic_long_add_return_relaxed(i, v)	((v)->counter += (i))
 #define atomic_long_add_return_release(i, v)	((v)->counter += (i))
 #define smp_rmb()				barrier()
+/* The harness runs on one thread: ordering primitives are plain accesses. */
+#define smp_load_acquire(p)			READ_ONCE(*(p))
+#define smp_store_release(p, v)			WRITE_ONCE(*(p), (v))
 
 static inline bool atomic_long_try_cmpxchg_relaxed(atomic_long_t *v, long *old, long new)
 {
@@ -92,15 +95,32 @@ extern unsigned int hpcc_current_cpu;
  */
 #define HPCC_PCPU_UNIT	64
 
+/* Outstanding allocations, to check for leaks. */
+extern long hpcc_nr_allocs;
+
+static inline void *hpcc_alloc_account(void *p)
+{
+	if (p)
+		hpcc_nr_allocs++;
+	return p;
+}
+
+static inline void hpcc_free_account(void *p)
+{
+	if (p)
+		hpcc_nr_allocs--;
+}
+
 static inline void *__alloc_percpu_gfp(size_t size, size_t align, gfp_t gfp)
 {
 	if (size > HPCC_PCPU_UNIT || align > HPCC_PCPU_UNIT)
 		return NULL;
-	return calloc(nr_cpu_ids, HPCC_PCPU_UNIT);
+	return hpcc_alloc_account(calloc(nr_cpu_ids, HPCC_PCPU_UNIT));
 }
 
 static inline void free_percpu(void *ptr)
 {
+	hpcc_free_account(ptr);
 	free(ptr);
 }
 
@@ -136,21 +156,23 @@ static inline void *kmem_cache_zalloc(struct kmem_cache *s, gfp_t gfp)
 
 	if (p)
 		memset(p, 0, s->size);
-	return p;
+	return hpcc_alloc_account(p);
 }
 
 static inline void kmem_cache_free(struct kmem_cache *s, void *p)
 {
+	hpcc_free_account(p);
 	free(p);
 }
 
 static inline void *kzalloc(size_t size, gfp_t gfp)
 {
-	return calloc(1, size);
+	return hpcc_alloc_account(calloc(1, size));
 }
 
 static inline void kfree(void *p)
 {
+	hpcc_free_account(p);
 	free(p);
 }
 
tools/testing/hpcc/main.c +47 -0

71 lines not on this page · raw message

Signature · 1 line
2.47.3
#7 lore raw

Re: [RFC PATCH v25 06/14] lib: percpu_counter_tree: add lazy tree activation

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] lib: percpu_counter_tree_kunit: lazy_race_fn() serializes remote updates --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] lib: percpu_counter_tree_kunit: lazy_race_fn() serializes remote updates
--

commit 5130476e081ef221464be8ba2bb48a1905d08dcd
Author: Mathieu Desnoyers <[email protected]>

lib: percpu_counter_tree: add lazy tree activation

This commit adds lazy tree initialization and activation for hierarchical per-CPU counters, along with KUnit and userspace tests.

Quoted 5 lines
lib/tests/percpu_counter_tree_kunit.c +0 -0
index 5774278ea1403..12bd5a4bbb459 100644
@@ -796,6 +798,225 @@ static void hpcc_test_saturated_compare(struct kunit *test)

[ ... ]

Quoted 19 lines
lib/tests/percpu_counter_tree_kunit.c +19 -0
+static void lazy_race_fn(struct work_struct *work)
+{
+	struct lazy_race_work *w = container_of(work, struct lazy_race_work, work);
+	struct lazy_race_shared *sh = w->sh;
+	long sum = 0;
+	int i;
+
+	for (i = 0; i < LAZY_RACE_NR_INC; i++) {
+		long inc = (long)(get_random_u32() % 65) - 32;
+
+		if (i == LAZY_RACE_NR_FIRST) {
+			/* Fully ordered: the first updates are visible before the pause. */
+			atomic_long_add_return(sum, &sh->first_sum);
+			atomic_inc_return(&sh->paused);
+			/* Pairs with the test's release of go. */
+			while (!smp_load_acquire(&sh->go))
+				cond_resched();
+			if (!w->owner) {
+				mutex_lock(&sh->activate_lock);

lib/tests/percpu_counter_tree_kunit.c static void hpcc_test_saturated_compare(struct kunit *test) · line 952

Quoted 10 lines
lib/tests/percpu_counter_tree_kunit.c +10 -0
+				if (percpu_counter_tree_activate_many(sh->c, 1, GFP_KERNEL) ||
+				    !percpu_counter_tree_active(sh->c))
+					atomic_inc(&sh->activate_errors);
+				mutex_unlock(&sh->activate_lock);
+			}
+		}
+		if (w->owner)
+			percpu_counter_tree_add_owner(sh->c, inc);
+		else
+			percpu_counter_tree_add(sh->c, inc);

[Severity: Medium]
Does acquiring sh->activate_lock in every non-owner worker right after sh->go becomes true prevent percpu_counter_tree_add() from ever racing with percpu_counter_tree_activate_many()?

Because both the main test thread and all non-owner workers serialize on sh->activate_lock immediately upon release, the first caller to take the mutex finishes activating and publishing the tree while the remaining non-owner workers wait on the mutex. None of the non-owner workers can reach percpu_counter_tree_add() until activation is already complete, so only the owner worker's percpu_counter_tree_add_owner() calls actually race with tree publication.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
author reviewer
#8 lore raw

Re: [RFC PATCH v25 06/14] lib: percpu_counter_tree: add lazy tree activation

Quoted 4 lines

[Severity: Medium]
Does acquiring sh->activate_lock in every non-owner worker right after sh->go becomes true prevent percpu_counter_tree_add() from ever racing with percpu_counter_tree_activate_many()?

[...]

Quoted 4 lines

None of the non-owner workers can
reach percpu_counter_tree_add() until activation is already complete, so only the owner worker's percpu_counter_tree_add_owner() calls actually race with tree publication.

Yes, this is a gap in the test. Each remote worker takes the mutex before its next addition. The tree is published by the time it gets the mutex. So the test only covers the owner's additions racing with the publication, not the remote ones.

Planned fix for the next round: only every other remote worker activates the tree. The others add right after the release, so their additions race with the activation.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
author reviewer
#9 lore raw

RFC PATCH v25 7/14 mm: keep the RSS counters of single-threaded processes exact

In reply to Mathieu Desnoyers

Until a second thread shares the mm, initialize the RSS counters lazily, without their counter tree: the task owning the mm adds to a plain counter, and other tasks, such as reclaim, khugepaged, the OOM reaper or remote GUP, add atomically. The RSS counters of single-threaded processes are therefore exact, their precise sums for /proc/PID/status, /proc/PID/statm and the OOM killer take O(1), and they use no per-cpu memory. The readers of the approximation, such as /proc/PID/stat, the RSS high watermark and the rss_stat tracepoint, get the exact value for these processes.

The owner, mm->rss_owner, is the task running on the mm: the child in dup_mm(), or the task in exec_mmap(), which also clears it from the mm it leaves, as exit_mm() does. It stays NULL, which matches no task, in the mm of exec() until exec_mmap() and in those of the other users of mm_alloc(): all their updates are atomic. It is only compared with current, never dereferenced, so a single task writes the plain counter, including while a vfork() child shares the mm. mm->owner (CONFIG_MEMCG) is not used, because mm_update_next_owner() hands it over to another task while a vfork() child may still update the counters.

copy_mm() activates the counter tree when a thread is created with CLONE_VM, except for vfork(), whose parent waits while the child shares the mm. mm->rss_stat_mutex serializes the activations, as mm->mm_cid.mutex serializes the mode changes of mm_cid at fork and exit, without relying on which tasks can create threads. Once the tree is active, thread creation no longer takes the mutex. This moves the allocation of the per-cpu counters and tree items of the RSS counters from fork() to the creation of the second thread of a process, which returns -ENOMEM if it fails, as fork() could before. The tasks the kernel creates with CLONE_VM for a process, such as the io_uring workers and the vhost tasks, also share its mm: a single-threaded process using them gets the counter tree. The updates made before the activation stay in the single counters, which the sums keep reading, so updates racing with the activation are not lost. Once the tree is active, __add_mm_counter() no longer reads rss_owner, so the updates of the threads of a process do not pull in its cache line, which other mm_struct fields share.

The tree stays active when the process returns to a single thread:
going back to the single counters would need a grace period for the remote updaters, and a process alternating between one and two threads would pay for each switch.

Before the activation, the updates of tasks other than the owner are atomic additions to one word per counter: concurrent remote updates of the same single-threaded process from many CPUs, such as direct reclaim unmapping its pages, contend on it.

* Testing results:

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

With the test program and the instrumentation described in the patch switching the RSS counters to hierarchical counters, in a KVM guest with 384 vCPUs, each pinned to its own CPU of the host, with the NUMA topology of the host, the approximation of the RSS counters of the single-threaded program is exact, compared to an 841MB delta for the upstream counters. With an idle second thread, which activates the counter tree, the hierarchical counters reach a 96MB delta, compared to 845MB for the upstream counters.

On bare metal, with 1000 to 16000 single-threaded processes alive, a read of /proc/PID/statm, which computes 3 precise sums, takes 5.3 to 6.5us, compared to 16.5 to 19.0us with the upstream counters, and a read of /proc/PID/status, which computes 4 precise sums, takes 11.4 to 13.1us, compared to 26.6 to 28.6us. A fork + exit of a child touching no pages takes 116us, compared to 139us (219us compared to 247us when it touches 64 pages): its counters are destroyed without 4 precise sums over 384 logical CPUs in check_mm(), and neither per-cpu memory nor tree items are allocated or freed.

On bare metal with SMT disabled at runtime, where the upstream batch size is 384, will-it-scale page_fault2 with one process is 5.1% faster than with the upstream counters, and page_fault3 1.3% faster (one boot each, the upstream one on the previous day; the boot-to-boot spread reaches 3%, so neither is claimed as a gain).

* Memory Use

Per mm, on a 64-bit arch with 64-byte cache lines, including the rss_owner pointer and the 24-byte activation mutex, for a single-threaded and a multi-threaded process, compared to the upstream percpu counters:

Bytes per mm
nr_cpus fan-out 1 thread threads upstream

        2 2             192      264       192
       16 16            192      320       416
       64 16,4          192      768      1184
      384 8,8,8         192     6400      6304
     1024 8,8,16        192    13568     16544

A single-threaded process uses 192 bytes for its RSS counters whatever the number of CPUs: the 4 counter structures, rss_owner and the mutex in mm_struct, compared to the 4 upstream counter structures (160 bytes) and their per-cpu memory. On x86_64 with 16, 384 and 1024 possible CPUs, the mm_struct slab object keeps its upstream size (1752, 1872 and 2112 bytes in /proc/slabinfo). A multi-threaded process adds nr_cpus bytes of per-cpu memory per counter (1536 per mm at 384 logical CPUs), compared to 4 * nr_cpus bytes per counter (6144 per mm) for the upstream counters, and the tree items, without the rounding of their slab cache. fork() no longer allocates memory for the RSS counters.

---
 .../core-api/percpu-counter-tree.rst          |  7 ++++
 fs/exec.c                                     |  5 +++
 include/linux/mm.h                            | 24 +++++++++++--
 include/linux/mm_types.h                      | 16 +++++++++
 kernel/exit.c                                 |  3 ++
 kernel/fork.c                                 | 35 +++++++++++++++++--
 6 files changed, 85 insertions(+), 5 deletions(-)
Documentation/core-api/percpu-counter-tree.rst +7 -0
index 138e9b74b0c8..87babe2276c4 100644
@@ -102,6 +102,13 @@ The activations of the same counters must be serialized by the caller:
 a concurrent activation would publish a second tree and lose the
 updates made to the first.
 
+The RSS counters of an mm use this: the task owning the mm updates the
+plain counter, and other tasks, such as reclaim, update the atomic
+counter. The tree is activated when a second thread shares the mm,
+under mm->rss_stat_mutex, which serializes the activations.
+A single-threaded process therefore has exact RSS counters, cheap
+precise sums, and neither per-cpu memory nor tree items for them.
+
 Use Cases
 =========
 
fs/exec.c +5 -0
index 8d2b14e1d455..7a6f07a6d482 100644
@@ -875,6 +875,8 @@ static int exec_mmap(struct linux_binprm *bprm)
 		}
 	}
 
+	/* This task owns the RSS counters of the new mm, see __add_mm_counter(). */
+	WRITE_ONCE(mm->rss_owner, tsk);
 	task_lock(tsk);
 	membarrier_exec_mmap(mm);
 
@@ -903,6 +905,9 @@ static int exec_mmap(struct linux_binprm *bprm)
 	if (old_mm) {
 		mmap_read_unlock(old_mm);
 		BUG_ON(active_mm != old_mm);
+		/* Updates of the old mm by this task are now atomic. */
+		if (READ_ONCE(old_mm->rss_owner) == tsk)
+			WRITE_ONCE(old_mm->rss_owner, NULL);
 		/* Defer teardown to setup_new_exec(), outside the exec locks. */
 		bprm->old_mm = old_mm;
 	} else {
include/linux/mm.h +21 -3
index 2b40f382da35..99a21a7c69b8 100644
@@ -3621,23 +3621,41 @@ static inline unsigned long get_mm_counter_sum(struct mm_struct *mm, int member)
 
 void mm_trace_rss_stat(struct mm_struct *mm, int member);
 
+/*
+ * Until a second thread shares the mm, the RSS counters are exact single
+ * counters: the task which owns the mm updates a plain counter, and other
+ * tasks (reclaim, khugepaged, the OOM reaper, remote GUP, ...) an atomic
+ * one. See copy_mm(). Once the tree is active, all updates go to it:
+ * rss_owner is not read, so the updates of the threads of a process do not
+ * touch its cache line.
+ */
+static inline void __add_mm_counter(struct mm_struct *mm, int member, long value)
+{
+	struct percpu_counter_tree *counter = &mm->rss_stat[member];
+
+	if (!percpu_counter_tree_active(counter) && current == READ_ONCE(mm->rss_owner))
+		percpu_counter_tree_add_owner(counter, value);
+	else
+		percpu_counter_tree_add(counter, value);
+}
+
 static inline void add_mm_counter(struct mm_struct *mm, int member, long value)
 {
-	percpu_counter_tree_add(&mm->rss_stat[member], value);
+	__add_mm_counter(mm, member, value);
 
 	mm_trace_rss_stat(mm, member);
 }
 
 static inline void inc_mm_counter(struct mm_struct *mm, int member)
 {
-	percpu_counter_tree_add(&mm->rss_stat[member], 1);
+	__add_mm_counter(mm, member, 1);
 
 	mm_trace_rss_stat(mm, member);
 }
 
 static inline void dec_mm_counter(struct mm_struct *mm, int member)
 {
-	percpu_counter_tree_add(&mm->rss_stat[member], -1);
+	__add_mm_counter(mm, member, -1);
 
 	mm_trace_rss_stat(mm, member);
 }
include/linux/mm_types.h +16 -0
index 20b4517b7329..f0d315d72adb 100644
@@ -1352,6 +1352,22 @@ struct mm_struct {
 #endif
 
 		struct percpu_counter_tree rss_stat[NR_MM_COUNTERS];
+		/*
+		 * Task updating rss_stat with percpu_counter_tree_add_owner()
+		 * until the counter tree is activated by a second thread: the
+		 * task running on this mm, set by dup_mm() and exec_mmap(),
+		 * cleared when that task exits or execs, NULL for the other
+		 * users of mm_alloc(). Only compared with current, never
+		 * dereferenced. Not mm->owner, which depends on CONFIG_MEMCG
+		 * and which mm_update_next_owner() hands over to another task
+		 * while a vfork() child may still update the counters.
+		 */
+		struct task_struct *rss_owner;
+		/*
+		 * Serializes the activations of the rss_stat counter tree,
+		 * until the tree is active. See mm_activate_rss_stat().
+		 */
+		struct mutex rss_stat_mutex;
 
 		struct linux_binfmt *binfmt;
 
kernel/exit.c +3 -0
index d5e7bc2af804..c153cd064987 100644
@@ -582,6 +582,9 @@ static void exit_mm(void)
 	local_irq_enable();
 	task_unlock(current);
 	mmap_read_unlock(mm);
+	/* From now on, this task updates the RSS counters of @mm atomically. */
+	if (READ_ONCE(mm->rss_owner) == current)
+		WRITE_ONCE(mm->rss_owner, NULL);
 	mm_update_next_owner(mm);
 	mmput(mm);
 	if (test_thread_flag(TIF_MEMDIE))
kernel/fork.c +33 -2
index d9bdaf2bd998..dc1db6cb5da0 100644
@@ -1108,6 +1108,7 @@ static struct mm_struct *mm_init(struct mm_struct *mm, struct task_struct *p)
 	memset(&mm->rss_stat, 0, sizeof(mm->rss_stat));
 	spin_lock_init(&mm->page_table_lock);
 	spin_lock_init(&mm->arg_lock);
+	mutex_init(&mm->rss_stat_mutex);
 	mm_init_cpumask(mm);
 	mm_init_aio(mm);
 	mm_init_owner(mm, p);
@@ -1148,8 +1149,7 @@ 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_tree_init_many(mm->rss_stat, NR_MM_COUNTERS, RSS_STAT_BATCH_SIZE,
-					  GFP_KERNEL_ACCOUNT))
+	if (percpu_counter_tree_init_many_lazy(mm->rss_stat, NR_MM_COUNTERS, RSS_STAT_BATCH_SIZE))
 		goto fail_pcpu;
 
 	lru_gen_init_mm(mm);
@@ -1550,6 +1550,8 @@ static struct mm_struct *dup_mm(struct task_struct *tsk,
 		mmap_write_unlock(oldmm);
 		goto fail_uprobe;
 	}
+	/* The child owns its RSS counters, see __add_mm_counter(). */
+	mm->rss_owner = tsk;
 
 	err = dup_mmap(mm, oldmm);
 	if (err)
@@ -1577,6 +1579,23 @@ static struct mm_struct *dup_mm(struct task_struct *tsk,
 	return NULL;
 }
 
+/*
+ * Serialize the activations of the RSS counter tree, whichever tasks create
+ * threads. Once the last counter is active, the activation is complete and
+ * thread creation skips the mutex. That check needs no acquire: the updates
+ * and the sums of the counters order their own accesses to the tree. Not
+ * observing the other counters active yet only delays their updates going
+ * to the tree.
+ */
+static int mm_activate_rss_stat(struct mm_struct *mm)
+{
+	if (percpu_counter_tree_active(&mm->rss_stat[NR_MM_COUNTERS - 1]))
+		return 0;
+	guard(mutex)(&mm->rss_stat_mutex);
+	return percpu_counter_tree_activate_many(mm->rss_stat, NR_MM_COUNTERS,
+						 GFP_KERNEL_ACCOUNT);
+}
+
 static int copy_mm(u64 clone_flags, struct task_struct *tsk)
 {
 	struct mm_struct *mm, *oldmm;
@@ -1601,6 +1620,18 @@ static int copy_mm(u64 clone_flags, struct task_struct *tsk)
 		return 0;
 
 	if (clone_flags & CLONE_VM) {
+		int err = 0;
+
+		/*
+		 * A second thread shares the mm: activate the RSS counter
+		 * tree. A vfork child shares the mm while the parent waits,
+		 * so the single counters still fit. The tree stays active if
+		 * the clone fails later, which is harmless.
+		 */
+		if (!(clone_flags & CLONE_VFORK))
+			err = mm_activate_rss_stat(oldmm);
+		if (err)
+			return err;
 		mmget(oldmm);
 		mm = oldmm;
 	} else {
Signature · 1 line
2.47.3
#10 lore raw

Re: [RFC PATCH v25 07/14] mm: keep the RSS counters of single-threaded processes exact

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] mm: clear mm->rss_owner on fork failure in dup_mm() and copy_process() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] mm: clear mm->rss_owner on fork failure in dup_mm() and copy_process()
--

commit 388976e575ede4fc50ab3cc88ddde7c67d80cb2e
Author: Mathieu Desnoyers <[email protected]>

mm: keep the RSS counters of single-threaded processes exact

This commit initializes the RSS counter tree lazily when a second thread shares the mm, using a plain owner counter and an atomic counter for single-threaded processes.

Quoted 4 lines
kernel/fork.c +0 -0
index d9bdaf2bd9984..dc1db6cb5da04 100644

[ ... ]

kernel/fork.c static struct mm_struct *dup_mm(struct task_struct *tsk, · line 1557

Quoted 9 lines
kernel/fork.c +2 -0
@@ -1550,6 +1550,8 @@ static struct mm_struct *dup_mm(struct task_struct *tsk,
 		mmap_write_unlock(oldmm);
 		goto fail_uprobe;
 	}
+	/* The child owns its RSS counters, see __add_mm_counter(). */
+	mm->rss_owner = tsk;
 
 	err = dup_mmap(mm, oldmm);
 	if (err)

[Severity: Medium]
Can a failed fork leave mm->rss_owner pointing to a freed task_struct?

Once dup_mmap() succeeds, the new mm is reachable by external mmget_not_zero() callers such as userfaultfd or swapoff. If the fork then fails in dup_mm() at try_module_get() or later in copy_process() (for example when put_user(pidfd, args->pidfd) returns -EFAULT), both error paths clear mm->owner before mmput(), but neither clears mm->rss_owner:

kernel/fork.c:dup_mm() {
	...
free_pt:
	/* don't put binfmt in mmput, we haven't got module yet */
	mm->binfmt = NULL;
	mm_init_owner(mm, NULL);
	mmput(mm);
	...
}
kernel/fork.c:copy_process() {
	...
bad_fork_cleanup_mm:
	sched_cache_fork_cleanup(p);
	if (p->mm) {
		mm_clear_owner(p->mm, p);
		mmput(p->mm);
	}
	...
}

If an external reference holds mm->mm_users > 1 across that mmput(), mm outlives tsk. A new task allocated at the same slab address as tsk can then match current == READ_ONCE(mm->rss_owner) in __add_mm_counter() and perform unsynchronized non-atomic updates via percpu_counter_tree_add_owner(), losing counter updates or triggering a Bad rss-counter state report in check_mm().

Clearing mm->rss_owner alongside mm->owner on both error paths before mmput() would avoid leaving the dangling pointer.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
author reviewer
#11 lore raw

Re: [RFC PATCH v25 07/14] mm: keep the RSS counters of single-threaded processes exact

Quoted 2 lines

[Severity: Medium]
Can a failed fork leave mm->rss_owner pointing to a freed task_struct?

[...]

Quoted 9 lines

If an external reference holds mm->mm_users > 1 across that mmput(), mm outlives tsk. A new task allocated at the same slab address as tsk can then match current == READ_ONCE(mm->rss_owner) in __add_mm_counter() and perform unsynchronized non-atomic updates via percpu_counter_tree_add_owner(), losing counter updates or triggering a Bad rss-counter state report in check_mm().

Clearing mm->rss_owner alongside mm->owner on both error paths before mmput() would avoid leaving the dangling pointer.

Yes, both error paths leave rss_owner pointing to the child. This was found by reading the code, I did not reproduce it.

No update would be lost, though. rss_owner is only compared with current, never dereferenced. At most one live task has that address at a time, so the plain counter still has a single writer. The other tasks update the atomic counter. The counters would still work.

What breaks is the identity of the owner: a task which does not run on the mm would update the plain counter as its owner. The owner should stay the task running on the mm.

Planned fix for the next round: clear mm->rss_owner next to mm->owner on both error paths. In copy_process() this is done only when rss_owner is the child, because with CLONE_VM the mm is the parent's.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
author reviewer
#12 lore raw

RFC PATCH v25 8/14 lib: percpu_counter_tree: add limit counters

In reply to Mathieu Desnoyers

A limit counter keeps a value below a limit. An addition fails rather than take the value above it. The tmpfs size limit uses percpu_counter_limited_add() for this. It takes no lock while the value is more than batch * nr_cpus below the limit. With the default batch size, this range grows as nr_cpus^2: 1.1 GB of pages at 384 CPUs. Closer to the limit, each addition takes the counter spinlock and sums all CPUs.

A tree counter has a smaller error bound. But its carries break a strict check. A carry leaves a level before it arrives at the next one. A sum taken in between misses it. A carry which arrives first can be counted twice instead. This is as bad for a negative carry.

So split the value by sign, into two counters which only grow: the additions and the subtractions. Each one errs in one direction only:

- The additions carry to the next level before they leave the level below. A sum read from level 0 up never misses a carry.
- The subtractions carry as usual. A sum read from the root down never counts a carry twice.

A carry about to leave an item takes what earlier additions left there. Until it reaches the root, the check does not see that part. So an item holding such a carry takes no new arrival. The next carries go straight to the root. The value is then at most:

root(additions) + accuracy - root(subtractions)

An addition first adds, then checks after a full barrier. If this bound is within the limit, it succeeds without a sum or a lock. Within the accuracy of the limit, the precise sums decide. An addition which does not fit is undone. The last addition checked sees all the others, so the limit is never exceeded. Additions must not be made from interrupt context, and percpu_counter_tree_limit_add() warns if they are.

An addition about to be undone can make a concurrent one fail, although that one fits. So an amount larger than the batch size is checked before it is added. If it cannot fit, it fails without being added. A smaller failed addition retries once if the value leaves room for it.

The API is percpu_counter_tree_limit_init(), _destroy(), _add(), _sub() and _precise_sum(). percpu_counter_tree_batch_for_accuracy() chooses the batch size from the limit.

The shim of the userspace test gains the primitives which the library now uses.

---
 include/linux/percpu_counter_tree.h    |  73 ++++++
 lib/percpu_counter_tree.c              | 322 +++++++++++++++++++++++++
 tools/testing/hpcc/include/hpcc_shim.h |  18 +-
 3 files changed, 411 insertions(+), 2 deletions(-)
include/linux/percpu_counter_tree.h +73 -0
index 2c27350ce836..dcdb91660bc0 100644
@@ -130,6 +130,28 @@ long percpu_counter_tree_approximate_sum(struct percpu_counter_tree *counter)
 }
 
 unsigned long percpu_counter_tree_approximate_accuracy(struct percpu_counter_tree *counter);
+unsigned long percpu_counter_tree_batch_for_accuracy(unsigned long accuracy);
+
+/*
+ * A value kept below a limit, such as the blocks used by a file system
+ * with a size limit. It is split by sign into two counters which only
+ * grow: the additions and the subtractions. Each one carries in the
+ * direction that keeps the limit check strict. See "Limit counters" in
+ * lib/percpu_counter_tree.c.
+ */
+struct percpu_counter_tree_limit {
+	/* [0]: the additions, [1]: the subtractions. */
+	struct percpu_counter_tree counters[2];
+};
+
+int percpu_counter_tree_limit_init(struct percpu_counter_tree_limit *limit,
+				   unsigned long batch_size, gfp_t gfp_flags);
+void percpu_counter_tree_limit_destroy(struct percpu_counter_tree_limit *limit);
+bool percpu_counter_tree_limit_add(struct percpu_counter_tree_limit *limit,
+				   unsigned long max, unsigned long amount);
+void percpu_counter_tree_limit_sub(struct percpu_counter_tree_limit *limit,
+				   unsigned long amount);
+unsigned long percpu_counter_tree_limit_precise_sum(struct percpu_counter_tree_limit *limit);
 
 #if IS_ENABLED(CONFIG_KUNIT)
 unsigned int percpu_counter_tree_check_config(void);
@@ -284,6 +306,57 @@ int percpu_counter_tree_subsystem_init(void)
 	return 0;
 }
 
+static inline
+unsigned long percpu_counter_tree_batch_for_accuracy(unsigned long accuracy)
+{
+	return PERCPU_COUNTER_TREE_MAX_BATCH;
+}
+
+/* On UP, the value is a single atomic: the first counter. The second is unused. */
+struct percpu_counter_tree_limit {
+	struct percpu_counter_tree counters[2];
+};
+
+static inline
+int percpu_counter_tree_limit_init(struct percpu_counter_tree_limit *limit,
+				   unsigned long batch_size, gfp_t gfp_flags)
+{
+	return percpu_counter_tree_init(&limit->counters[0], batch_size, gfp_flags);
+}
+
+static inline
+void percpu_counter_tree_limit_destroy(struct percpu_counter_tree_limit *limit)
+{
+}
+
+static inline
+bool percpu_counter_tree_limit_add(struct percpu_counter_tree_limit *limit,
+				   unsigned long max, unsigned long amount)
+{
+	atomic_long_t *count = &limit->counters[0].count;
+	long old = atomic_long_read(count);
+
+	/* Add only an amount which fits. */
+	do {
+		if ((unsigned long)old + amount > max)
+			return false;
+	} while (!atomic_long_try_cmpxchg(count, &old, old + amount));
+	return true;
+}
+
+static inline
+void percpu_counter_tree_limit_sub(struct percpu_counter_tree_limit *limit,
+				   unsigned long amount)
+{
+	atomic_long_sub(amount, &limit->counters[0].count);
+}
+
+static inline
+unsigned long percpu_counter_tree_limit_precise_sum(struct percpu_counter_tree_limit *limit)
+{
+	return atomic_long_read(&limit->counters[0].count);
+}
+
 #endif	/* CONFIG_SMP */
 
 /**
lib/percpu_counter_tree.c +322 -0

340 lines not on this page · raw message

tools/testing/hpcc/include/hpcc_shim.h +16 -2
index d321c8363b0b..a455e6432b5c 100644
@@ -63,12 +63,16 @@ static inline int get_count_order(unsigned int count)
 }
 
 #define atomic_long_read(v)			READ_ONCE((v)->counter)
+#define atomic_long_read_acquire(v)		READ_ONCE((v)->counter)
 #define atomic_long_set(v, i)			WRITE_ONCE((v)->counter, (i))
 #define atomic_long_add(i, v)			((void)((v)->counter += (i)))
 #define atomic_long_add_return_relaxed(i, v)	((v)->counter += (i))
-#define atomic_long_add_return_release(i, v)	((v)->counter += (i))
-#define smp_rmb()				barrier()
+#define atomic_long_sub(i, v)			((void)((v)->counter -= (i)))
 /* The harness runs on one thread: ordering primitives are plain accesses. */
+#define smp_rmb()				barrier()
+#define smp_mb()				barrier()	/* One thread: no reordering. */
+#define preempt_disable()			barrier()
+#define preempt_enable()			barrier()
 #define smp_load_acquire(p)			READ_ONCE(*(p))
 #define smp_store_release(p, v)			WRITE_ONCE(*(p), (v))
 
@@ -82,11 +86,17 @@ static inline bool atomic_long_try_cmpxchg_relaxed(atomic_long_t *v, long *old,
 	return false;
 }
 
+#define atomic_long_add_return(i, v)		((v)->counter += (i))
+#define atomic_long_add_return_release(i, v)	((v)->counter += (i))
+#define atomic_long_try_cmpxchg(v, old, new)	atomic_long_try_cmpxchg_relaxed(v, old, new)
+
 /* Simulated topology, and CPU on which the current code runs. */
 extern unsigned int nr_cpu_ids;
 extern unsigned int hpcc_current_cpu;
 
 #define raw_smp_processor_id()		hpcc_current_cpu
+#define smp_processor_id()		hpcc_current_cpu
+#define in_task()			true
 #define for_each_possible_cpu(cpu)	for ((cpu) = 0; (cpu) < (int)nr_cpu_ids; (cpu)++)
 
 /*
@@ -193,6 +203,10 @@ static inline bool __hpcc_this_cpu_try_cmpxchg(s8 *pcp, s8 *old, s8 new)
 }
 
 #define this_cpu_read(pcp)	(*per_cpu_ptr(&(pcp), hpcc_current_cpu))
+#define this_cpu_write(pcp, v)	((void)(*per_cpu_ptr(&(pcp), hpcc_current_cpu) = (v)))
+#define this_cpu_ptr(ptr)	per_cpu_ptr(ptr, hpcc_current_cpu)
+#define __this_cpu_read(pcp)	this_cpu_read(pcp)
+#define __this_cpu_write(pcp, v)	this_cpu_write(pcp, v)
 #define this_cpu_try_cmpxchg(pcp, ovalp, nval)	\
 	__hpcc_this_cpu_try_cmpxchg(&(pcp), (ovalp), (nval))
 
Signature · 1 line
2.47.3
author reviewer
#13 lore raw

RFC PATCH v25 9/14 lib: percpu_counter_tree: test the limit counters

In reply to Mathieu Desnoyers

Test the limit counters of the previous patch. These tests cover them:

- The userspace harness checks each decision and the bounds of each counter.
- The harness also stalls an addition right after its carry fills an item, at each level and at the root. Then the other CPUs of that item add near the limit. An item holding such a carry must take no new arrival. Without this rule, they exceed the limit in 105 of the 191 configurations.
- A harness test makes an addition fail because of another one in flight, and checks that it retries and fits. Another one checks that a large amount which cannot fit is not added.
- The harness runs these tests again with both counters about to wrap, as unsigned and as signed values. It passes as a 32-bit build too.
- A KUnit test runs workers on all CPUs near the limit. An exact shadow of the successful additions never exceeds it.

For the stall test, the shim gains a stall hook. It runs a function right after the next fully ordered or release update of a chosen item.

---
 lib/tests/percpu_counter_tree_kunit.c  | 172 +++++++++++++
 tools/testing/hpcc/include/hpcc_shim.h |  42 ++-
 tools/testing/hpcc/main.c              | 342 +++++++++++++++++++++++++
 3 files changed, 553 insertions(+), 3 deletions(-)
lib/tests/percpu_counter_tree_kunit.c +172 -0
index 12bd5a4bbb45..bd99ab7ca1c0 100644
@@ -612,6 +612,177 @@ static void hpcc_test_contended_carries(struct kunit *test)
 		do_hpcc_test_contended_carries(test, 1UL << batch_size_order);
 }
 
+#define LIMIT_NR_OPS	100000
+
+struct limit_shared {
+	struct percpu_counter_tree_limit limit;
+	unsigned long max;
+	unsigned long target;		/* Amount each worker tries to hold. */
+	unsigned long batch_size;
+	atomic_long_t charged;		/* Exact total of the successful additions held. */
+	atomic_long_t nr_over;		/* Times charged exceeded max. */
+	atomic_long_t nr_added, nr_failed;
+	atomic_t nr_ready;
+	unsigned int nr_workers;
+	bool started;
+};
+
+struct limit_data {
+	struct limit_shared *sh;
+	unsigned long held;
+	u32 seed;
+} ____cacheline_aligned_in_smp;
+
+static DECLARE_WAIT_QUEUE_HEAD(limit_wq);
+
+static u32 limit_rnd(struct limit_data *ld)
+{
+	u32 x = ld->seed;
+
+	x ^= x << 13;
+	x ^= x >> 17;
+	x ^= x << 5;
+	ld->seed = x;
+	return x;
+}
+
+/*
+ * Each worker adds to the limit counter until it holds its target. Then
+ * it frees part of what it holds. Together, the workers hold about 1.5
+ * times the limit, so additions fail. A successful addition is added to
+ * charged after it succeeds. A free subtracts from charged before it
+ * reaches the limit counter. So charged is never above the value of the
+ * limit counter. Charged above max means the limit was exceeded.
+ */
+static int limit_worker_fn(void *data)
+{
+	struct limit_data *ld = data;
+	struct limit_shared *sh = ld->sh;
+	unsigned int i;
+
+	/* Pairs with the release of started: max, target and nr_workers are set. */
+	wait_event(limit_wq, smp_load_acquire(&sh->started));
+	/* Start together, so that the workers hold their amounts at the same time. */
+	atomic_inc(&sh->nr_ready);
+	while (atomic_read(&sh->nr_ready) < sh->nr_workers)
+		cpu_relax();
+	for (i = 0; i < LIMIT_NR_OPS; i++) {
+		u32 x = limit_rnd(ld);
+		unsigned long amount;
+
+		if (ld->held < sh->target) {
+			/* Mostly small amounts, and one in 16 of a huge page. */
+			if ((x >> 4) & 15)
+				amount = 1 + (x >> 8) % (4 * sh->batch_size);
+			else
+				amount = 512;
+			if (percpu_counter_tree_limit_add(&sh->limit, sh->max, amount)) {
+				unsigned long charged;
+
+				charged = atomic_long_add_return(amount, &sh->charged);
+				if (charged > sh->max)
+					atomic_long_inc(&sh->nr_over);
+				ld->held += amount;
+				atomic_long_inc(&sh->nr_added);
+			} else {
+				atomic_long_inc(&sh->nr_failed);
+			}
+		} else if (ld->held) {
+			amount = 1 + (x >> 8) % ld->held;
+			atomic_long_sub(amount, &sh->charged);
+			percpu_counter_tree_limit_sub(&sh->limit, amount);
+			ld->held -= amount;
+		}
+		if (!(i & 63))
+			cond_resched();
+	}
+	atomic_long_sub(ld->held, &sh->charged);
+	percpu_counter_tree_limit_sub(&sh->limit, ld->held);
+	ld->held = 0;
+	complete_work();
+	return 0;
+}
+
+static void do_hpcc_test_limit(struct kunit *test, unsigned long batch_size)
+{
+	struct limit_shared *sh;
+	struct limit_data *ld;
+	struct task_struct **task;
+	const struct cpumask *cpus;
+	unsigned int nr_workers = 0;
+	unsigned long accuracy;
+	int ret, cpu;
+
+	sh = kzalloc_obj(*sh);
+	ld = kvcalloc(nr_cpu_ids, sizeof(*ld), GFP_KERNEL);
+	task = kvcalloc(nr_cpu_ids, sizeof(*task), GFP_KERNEL);
+	KUNIT_EXPECT_NOT_NULL(test, sh);
+	KUNIT_EXPECT_NOT_NULL(test, ld);
+	KUNIT_EXPECT_NOT_NULL(test, task);
+	if (!sh || !ld || !task)
+		goto free;
+	ret = percpu_counter_tree_limit_init(&sh->limit, batch_size, GFP_KERNEL);
+	KUNIT_EXPECT_EQ(test, ret, 0);
+	if (ret)
+		goto free;
+	accuracy = percpu_counter_tree_approximate_accuracy(&sh->limit.counters[0]);
+	/* A limit of twice the accuracy, oversubscribed twice: mostly within its accuracy. */
+	sh->max = 2 * accuracy + 1;
+	sh->batch_size = batch_size;
+	init_kthreads();
+	cpus_read_lock();
+	cpus = select_worker_cpus();
+	sh->target = 2 * sh->max / cpumask_weight(cpus) + 512;
+	for_each_cpu(cpu, cpus) {
+		ld[cpu].sh = sh;
+		ld[cpu].seed = get_random_u32() | 1;
+		task[cpu] = kthread_create_on_cpu(limit_worker_fn, &ld[cpu], cpu,
+						  "kunit_hpcc_limit/%u");
+		KUNIT_EXPECT_FALSE(test, IS_ERR(task[cpu]));
+		if (IS_ERR(task[cpu]))
+			break;
+		atomic_inc(&kernel_threads_to_run);
+		get_task_struct(task[cpu]);
+		wake_up_process(task[cpu]);
+		nr_workers++;
+	}
+	sh->nr_workers = nr_workers;
+	/* Start the workers once their number is known, see limit_worker_fn(). */
+	smp_store_release(&sh->started, true);
+	wake_up_all(&limit_wq);
+	fini_kthreads();
+	for_each_cpu(cpu, cpus) {
+		if (!IS_ERR_OR_NULL(task[cpu]))
+			kthread_stop_put(task[cpu]);
+	}
+	cpus_read_unlock();
+
+	kunit_info(test, "batch_size=%lu workers=%u max=%lu added=%ld failed=%ld over=%ld\n",
+		   batch_size, nr_workers, sh->max, atomic_long_read(&sh->nr_added),
+		   atomic_long_read(&sh->nr_failed), atomic_long_read(&sh->nr_over));
+	KUNIT_EXPECT_EQ(test, atomic_long_read(&sh->nr_over), 0);
+	KUNIT_EXPECT_GT(test, atomic_long_read(&sh->nr_failed), 0);
+	KUNIT_EXPECT_EQ(test, percpu_counter_tree_limit_precise_sum(&sh->limit), 0);
+	percpu_counter_tree_limit_destroy(&sh->limit);
+free:
+	kvfree(task);
+	kvfree(ld);
+	kfree(sh);
+}
+
+/*
+ * Workers on all the worker CPUs add to and subtract from a limit counter
+ * held near its limit. The limit is never exceeded, and the value is back
+ * to 0 once all the workers freed what they held.
+ */
+static void hpcc_test_limit(struct kunit *test)
+{
+	if (num_online_cpus() < 2)
+		kunit_skip(test, "needs at least 2 online CPUs");
+	do_hpcc_test_limit(test, 2);
+	do_hpcc_test_limit(test, 32);
+}
+
 static void hpcc_test_init_one(struct kunit *test)
 {
 	struct percpu_counter_tree pct, zeroed = {};
@@ -1038,6 +1209,7 @@ static struct kunit_case hpcc_test_cases[] = {
 	KUNIT_CASE(hpcc_test_set),
 	KUNIT_CASE(hpcc_test_saturated_compare),
 	KUNIT_CASE(hpcc_test_contended_carries),
+	KUNIT_CASE_SLOW(hpcc_test_limit),
 	KUNIT_CASE(hpcc_test_lazy),
 	KUNIT_CASE(hpcc_test_lazy_activation_race),
 	{}
tools/testing/hpcc/include/hpcc_shim.h +39 -3

48 lines not on this page · raw message

tools/testing/hpcc/main.c +342 -0

372 lines not on this page · raw message

Signature · 1 line
2.47.3
#14 lore raw

Re: [RFC PATCH v25 09/14] lib: percpu_counter_tree: test the limit counters

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider: - [Medium] lib: percpu_counter_tree: unreachable subtraction in limit_worker_fn() - [Low] lib…

Thank you for your contribution! Sashiko AI review found 2 potential issues to consider:
- [Medium] lib: percpu_counter_tree: unreachable subtraction in limit_worker_fn()
- [Low] lib: percpu_counter_tree: unordered sh->charged sub in limit_worker_fn()
--

commit ffee3ed89eb2ac6dc7c1033ea104470f2a5faf4e
Author: Mathieu Desnoyers <[email protected]>

lib: percpu_counter_tree: test the limit counters

This commit adds KUnit and userspace hpcc harness tests for percpu_counter_tree_limit, along with a stall hook in the userspace shim to simulate concurrent updates while an addition carry is in flight.

Quoted 9 lines
lib/tests/percpu_counter_tree_kunit.c +1 -0
index 12bd5a4bbb459..bd99ab7ca1c07 100644
@@ -612,6 +612,177 @@ static void hpcc_test_contended_carries(struct kunit *test)
 		do_hpcc_test_contended_carries(test, 1UL << batch_size_order);
 }
 
+#define LIMIT_NR_OPS	100000

[ ... ]

Quoted 34 lines
lib/tests/percpu_counter_tree_kunit.c +34 -0
+static int limit_worker_fn(void *data)
+{
+	struct limit_data *ld = data;
+	struct limit_shared *sh = ld->sh;
+	unsigned int i;
+
+	/* Pairs with the release of started: max, target and nr_workers are set. */
+	wait_event(limit_wq, smp_load_acquire(&sh->started));
+	/* Start together, so that the workers hold their amounts at the same time. */
+	atomic_inc(&sh->nr_ready);
+	while (atomic_read(&sh->nr_ready) < sh->nr_workers)
+		cpu_relax();
+	for (i = 0; i < LIMIT_NR_OPS; i++) {
+		u32 x = limit_rnd(ld);
+		unsigned long amount;
+
+		if (ld->held < sh->target) {
+			/* Mostly small amounts, and one in 16 of a huge page. */
+			if ((x >> 4) & 15)
+				amount = 1 + (x >> 8) % (4 * sh->batch_size);
+			else
+				amount = 512;
+			if (percpu_counter_tree_limit_add(&sh->limit, sh->max, amount)) {
+				unsigned long charged;
+
+				charged = atomic_long_add_return(amount, &sh->charged);
+				if (charged > sh->max)
+					atomic_long_inc(&sh->nr_over);
+				ld->held += amount;
+				atomic_long_inc(&sh->nr_added);
+			} else {
+				atomic_long_inc(&sh->nr_failed);
+			}
+		} else if (ld->held) {

lib/tests/percpu_counter_tree_kunit.c static void hpcc_test_contended_carries(struct kunit *test) · line 700

Quoted 10 lines
lib/tests/percpu_counter_tree_kunit.c +10 -0
+			amount = 1 + (x >> 8) % ld->held;
+			atomic_long_sub(amount, &sh->charged);
+			percpu_counter_tree_limit_sub(&sh->limit, amount);
+			ld->held -= amount;
+		}
+		if (!(i & 63))
+			cond_resched();
+	}
+	atomic_long_sub(ld->held, &sh->charged);
+	percpu_counter_tree_limit_sub(&sh->limit, ld->held);

[Severity: Low]
Can the relaxed atomic_long_sub() on sh->charged be reordered after percpu_counter_tree_limit_sub() on weakly ordered architectures?

The comment above limit_worker_fn() notes that a free subtracts from sh->charged before it reaches the limit counter so sh->charged never exceeds the limit counter. However, non-value-returning atomic_long_sub() is unordered, and percpu_counter_tree_limit_sub() updates the per-CPU level 0 counter via this_cpu_try_cmpxchg() without a barrier when there is no carry:

CPU0 CPU1
limit_worker_fn() limit_worker_fn()
atomic_long_sub(..., &sh->charged) (reordered)
percpu_counter_tree_limit_sub()

                                    percpu_counter_tree_limit_add() -> true
                                    charged = atomic_long_add_return(...,
                                                              &sh->charged)
                                    if (charged > sh->max)
                                      atomic_long_inc(&sh->nr_over);

/* sh->charged sub becomes visible */

This can cause a false-positive KUnit failure on sh->nr_over. Using atomic_long_sub_return() or smp_mb__after_atomic() before percpu_counter_tree_limit_sub() in both the loop and the final cleanup would enforce the intended ordering.

Quoted 7 lines
lib/tests/percpu_counter_tree_kunit.c +7 -0
+	ld->held = 0;
+	complete_work();
+	return 0;
+}
+
+static void do_hpcc_test_limit(struct kunit *test, unsigned long batch_size)
+{

[ ... ]

lib/tests/percpu_counter_tree_kunit.c static void hpcc_test_contended_carries(struct kunit *test) · line 735

Quoted 8 lines
lib/tests/percpu_counter_tree_kunit.c +8 -0
+	accuracy = percpu_counter_tree_approximate_accuracy(&sh->limit.counters[0]);
+	/* A limit of twice the accuracy, oversubscribed twice: mostly within its accuracy. */
+	sh->max = 2 * accuracy + 1;
+	sh->batch_size = batch_size;
+	init_kthreads();
+	cpus_read_lock();
+	cpus = select_worker_cpus();
+	sh->target = 2 * sh->max / cpumask_weight(cpus) + 512;

[Severity: Medium]
Does setting sh->target to 2 * sh->max / cpumask_weight(cpus) + 512 prevent limit_worker_fn() from reaching its in-loop subtraction branch?

In limit_worker_fn(), a worker only subtracts when ld->held >= sh->target and never frees any held amount when percpu_counter_tree_limit_add() fails. Because the total held across all workers cannot exceed sh->max, no single worker can ever reach ld->held >= sh->target when sh->target > sh->max (which holds on 2 to 8 CPUs for both batch sizes, and up to 64 CPUs for batch_size = 2 due to the + 512 offset). Even with more CPUs where sh->target <= sh->max, all workers start together at sh->nr_ready and average sh->max / nr_workers each when the counter fills, so once total held reaches sh->max with every worker below sh->target, no further addition can succeed and no worker can subtract for the rest of LIMIT_NR_OPS.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=9
author reviewer
#15 lore raw

Re: [RFC PATCH v25 09/14] lib: percpu_counter_tree: test the limit counters

Quoted 3 lines

[Severity: Low]
Can the relaxed atomic_long_sub() on sh->charged be reordered after percpu_counter_tree_limit_sub() on weakly ordered architectures?

[...]

Quoted 4 lines

This can cause a false-positive KUnit failure on sh->nr_over. Using atomic_long_sub_return() or smp_mb__after_atomic() before percpu_counter_tree_limit_sub() in both the loop and the final cleanup would enforce the intended ordering.

Yes, this is a bug in the test. atomic_long_sub() gives no ordering, and the subtraction from the limit counter is a per-CPU update without a barrier when it does not carry. Another worker can then add into the freed room before it sees charged decrease, and count a false overrun. x86 does not reorder these stores, so our test runs could not hit it.

Planned fix for the next round: the free uses atomic_long_sub_return() at both sites.

Quoted 3 lines

[Severity: Medium]
Does setting sh->target to 2 * sh->max / cpumask_weight(cpus) + 512 prevent limit_worker_fn() from reaching its in-loop subtraction branch?

[...]

Yes. The workers together never hold more than max, and a worker only frees once it holds its target. The targets add up to more than twice max. So the branch is dead whenever the target is above max. Elsewhere the limit fills up while most workers are below their target. On 384 vCPUs, more than 97% of the operations were failed additions.

Planned fix for the next round: the target goes away. A worker frees part of what it holds when its addition fails, so the value keeps moving near the limit. The test also checks that such frees happened.

Thanks,

Mathieu

Signature · 3 lines
Mathieu Desnoyers
EfficiOS Inc.
https://www.efficios.com
author reviewer
#16 lore raw

RFC PATCH v25 10/14 tools/testing/hpcc: add litmus tests of the memory ordering

In reply to Mathieu Desnoyers

The limit counters rely on memory ordering. So do the carries and the publication of the tree by lazy activation. A test on real hardware cannot show that an ordering is needed: a missing barrier may never fail in practice. The userspace test runs on one thread only.

Check each of these orderings with the Linux kernel memory model instead. The litmus tests cover:

- The publication of the tree: the update fast path, the carry slow path, the precise sum and the approximate sum.
- The carries of percpu_counter_tree_add(), against the precise sum.
- The limit counters: the carries of the additions, an addition undone, an amount freed on another CPU, and two concurrent checks.

herd7 reports "Never" for the 12 tests of the code as it is. 9 variants drop one ordering each, and herd7 reports "Sometimes" for them. This shows that these orderings are needed. The README explains how to run the tests, and the comments of the library now point at them.

---
 lib/percpu_counter_tree.c                     |  8 ++-
 tools/testing/hpcc/litmus/README              | 61 +++++++++++++++++++
 .../leave-first-precise-sum-relaxed.litmus    | 37 +++++++++++
 .../litmus/leave-first-precise-sum.litmus     | 41 +++++++++++++
 .../litmus/limit-arrive-first-acquire.litmus  | 38 ++++++++++++
 .../limit-arrive-first-unordered.litmus       | 37 +++++++++++
 .../hpcc/litmus/limit-arrive-first.litmus     | 41 +++++++++++++
 .../hpcc/litmus/limit-free-level0-nomb.litmus | 40 ++++++++++++
 .../hpcc/litmus/limit-free-level0.litmus      | 43 +++++++++++++
 .../hpcc/litmus/limit-free-root.litmus        | 42 +++++++++++++
 .../litmus/limit-last-checker-nomb.litmus     | 28 +++++++++
 .../hpcc/litmus/limit-last-checker.litmus     | 33 ++++++++++
 .../hpcc/litmus/limit-undo-level0.litmus      | 35 +++++++++++
 .../hpcc/litmus/limit-undo-root-rmb.litmus    | 30 +++++++++
 .../litmus/limit-undo-root-unordered.litmus   | 29 +++++++++
 .../hpcc/litmus/limit-undo-root.litmus        | 32 ++++++++++
 .../litmus/publish-approximate-sum.litmus     | 40 ++++++++++++
 .../hpcc/litmus/publish-carry-normb.litmus    | 36 +++++++++++
 .../testing/hpcc/litmus/publish-carry.litmus  | 43 +++++++++++++
 .../publish-precise-sum-noacquire.litmus      | 38 ++++++++++++
 .../hpcc/litmus/publish-precise-sum.litmus    | 44 +++++++++++++
 .../litmus/publish-update-norelease.litmus    | 34 +++++++++++
 .../testing/hpcc/litmus/publish-update.litmus | 40 ++++++++++++
 23 files changed, 848 insertions(+), 2 deletions(-)
 create mode 100644 tools/testing/hpcc/litmus/README
 create mode 100644 tools/testing/hpcc/litmus/leave-first-precise-sum-relaxed.litmus
 create mode 100644 tools/testing/hpcc/litmus/leave-first-precise-sum.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-arrive-first-acquire.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-arrive-first-unordered.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-arrive-first.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-free-level0-nomb.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-free-level0.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-free-root.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-last-checker-nomb.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-last-checker.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-undo-level0.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-undo-root-rmb.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-undo-root-unordered.litmus
 create mode 100644 tools/testing/hpcc/litmus/limit-undo-root.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-approximate-sum.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-carry-normb.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-carry.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-precise-sum-noacquire.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-precise-sum.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-update-norelease.litmus
 create mode 100644 tools/testing/hpcc/litmus/publish-update.litmus
lib/percpu_counter_tree.c +6 -2
index 9c172fc3e4d7..fcffc3d073ca 100644
@@ -552,7 +552,9 @@ EXPORT_SYMBOL_GPL(percpu_counter_tree_init_many_lazy);
  * The read barriers between the levels of the precise sum are unrelated
  * to the publication: they order carries, see
  * percpu_counter_tree_precise_sum_unbiased().
-
+ *
+ * The litmus tests in tools/testing/hpcc/litmus check these orderings
+ * with the Linux kernel memory model, and those of the carries.
  */
 
 /**
@@ -1261,7 +1263,9 @@ EXPORT_SYMBOL_GPL(percpu_counter_tree_batch_for_accuracy);
  * retries once when the value leaves room for it.
  *
  * Both counters wrap around: all the arithmetic is modular.
-
+ *
+ * The litmus tests in tools/testing/hpcc/litmus check these orderings
+ * with the Linux kernel memory model.
  */
 
 /*
tools/testing/hpcc/litmus/README new file +61 -0

61 lines not on this page · raw message

tools/testing/hpcc/litmus/leave-first-precise-sum-relaxed.litmus new file +37 -0
new file mode 100644
index 000000000000..951b7c39bbbc
@@ -0,0 +1,37 @@
+C leave-first-precise-sum-relaxed
+
+(*
+ * Result: Sometimes
+ *
+ * Like leave-first-precise-sum, with a relaxed arrival at the middle
+ * item. The precise sum can then count the carry twice.
+ *)
+
+{
+	l0=1;
+}
+
+P0(int *l0, atomic_t *item, atomic_t *root)
+{
+	int r;
+
+	r = cmpxchg_relaxed(l0, 1, 0);
+	r = atomic_add_return_relaxed(1, item);
+	r = atomic_cmpxchg_relaxed(item, 1, 0);
+	r = atomic_add_return_release(1, root);
+}
+
+P1(int *l0, atomic_t *item, atomic_t *root)
+{
+	int r0;
+	int r1;
+	int r2;
+
+	r2 = atomic_read(root);
+	smp_rmb();
+	r1 = atomic_read(item);
+	smp_rmb();
+	r0 = READ_ONCE(*l0);
+}
+
+exists ((1:r2=1 /\ 1:r1=1) \/ (1:r2=1 /\ 1:r0=1) \/ (1:r1=1 /\ 1:r0=1))
tools/testing/hpcc/litmus/leave-first-precise-sum.litmus new file +41 -0

41 lines not on this page · raw message

tools/testing/hpcc/litmus/limit-arrive-first-acquire.litmus new file +38 -0
new file mode 100644
index 000000000000..f5f06dd0ff08
@@ -0,0 +1,38 @@
+C limit-arrive-first-acquire
+
+(*
+ * Result: Sometimes
+ *
+ * Like limit-arrive-first, with an acquire add at the root. The acquire
+ * only orders the read of the add. The departures can then be seen
+ * before the arrival at the root, and the sum misses the carry.
+ *)
+
+{
+	l0 = 1;
+}
+
+P0(int *l0, atomic_t *item, atomic_t *root)
+{
+	int r;
+
+	r = atomic_cmpxchg(item, 0, 1);
+	r = atomic_add_return_acquire(1, root);
+	atomic_sub(1, item);
+	WRITE_ONCE(*l0, 0);
+}
+
+P1(int *l0, atomic_t *item, atomic_t *root)
+{
+	int r0;
+	int r1;
+	int r2;
+
+	r0 = READ_ONCE(*l0);
+	smp_rmb();
+	r1 = atomic_read(item);
+	smp_rmb();
+	r2 = atomic_read(root);
+}
+
+exists (1:r0=0 /\ 1:r1=0 /\ 1:r2=0)
tools/testing/hpcc/litmus/limit-arrive-first-unordered.litmus new file +37 -0
new file mode 100644
index 000000000000..9d870c2e0aa2
@@ -0,0 +1,37 @@
+C limit-arrive-first-unordered
+
+(*
+ * Result: Sometimes
+ *
+ * Like limit-arrive-first, with an unordered add at the root. The sum
+ * can miss the carry.
+ *)
+
+{
+	l0 = 1;
+}
+
+P0(int *l0, atomic_t *item, atomic_t *root)
+{
+	int r;
+
+	r = atomic_cmpxchg(item, 0, 1);
+	atomic_add(1, root);
+	atomic_sub(1, item);
+	WRITE_ONCE(*l0, 0);
+}
+
+P1(int *l0, atomic_t *item, atomic_t *root)
+{
+	int r0;
+	int r1;
+	int r2;
+
+	r0 = READ_ONCE(*l0);
+	smp_rmb();
+	r1 = atomic_read(item);
+	smp_rmb();
+	r2 = atomic_read(root);
+}
+
+exists (1:r0=0 /\ 1:r1=0 /\ 1:r2=0)
tools/testing/hpcc/litmus/limit-arrive-first.litmus new file +41 -0

41 lines not on this page · raw message

tools/testing/hpcc/litmus/limit-free-level0-nomb.litmus new file +40 -0
new file mode 100644
index 000000000000..d220bab401ac
@@ -0,0 +1,40 @@
+C limit-free-level0-nomb
+
+(*
+ * Result: Sometimes
+ *
+ * Like limit-free-level0, without the full barrier after the addition.
+ * The release of the page does not order the addition before the
+ * unordered subtraction of CPU 1, for CPU 2. The precise sum can then
+ * see the subtraction without the addition.
+ *)
+
+{}
+
+P0(int *l0p, int *page)
+{
+	WRITE_ONCE(*l0p, 1);
+	smp_store_release(page, 1);
+}
+
+P1(int *l0n, int *page)
+{
+	int r0;
+	int r;
+
+	r0 = smp_load_acquire(page);
+	if (r0 == 1)
+		r = cmpxchg_relaxed(l0n, 0, 1);
+}
+
+P2(int *l0p, int *l0n)
+{
+	int r0;
+	int r1;
+
+	r0 = READ_ONCE(*l0n);
+	smp_rmb();
+	r1 = READ_ONCE(*l0p);
+}
+
+exists (1:r0=1 /\ 2:r0=1 /\ 2:r1=0)
tools/testing/hpcc/litmus/limit-free-level0.litmus new file +43 -0

43 lines not on this page · raw message

tools/testing/hpcc/litmus/limit-free-root.litmus new file +42 -0

42 lines not on this page · raw message

tools/testing/hpcc/litmus/limit-last-checker-nomb.litmus new file +28 -0
new file mode 100644
index 000000000000..2690fdf6e868
@@ -0,0 +1,28 @@
+C limit-last-checker-nomb
+
+(*
+ * Result: Sometimes
+ *
+ * Like limit-last-checker, without the full barrier. Both checks can
+ * miss the other addition, and both pass.
+ *)
+
+{}
+
+P0(int *a, int *b)
+{
+	int r0;
+
+	WRITE_ONCE(*a, 1);
+	r0 = READ_ONCE(*b);
+}
+
+P1(int *a, int *b)
+{
+	int r0;
+
+	WRITE_ONCE(*b, 1);
+	r0 = READ_ONCE(*a);
+}
+
+exists (0:r0=0 /\ 1:r0=0)
tools/testing/hpcc/litmus/limit-last-checker.litmus new file +33 -0
new file mode 100644
index 000000000000..891f20ec86a0
@@ -0,0 +1,33 @@
+C limit-last-checker
+
+(*
+ * Result: Never
+ *
+ * Two CPUs add to their level 0 counters a and b, then check with a
+ * precise sum, which reads the other counter. With a full barrier
+ * between the addition and the check, at least one of them sees the
+ * other addition. Of the additions which pass their check, the one
+ * checked last thus sees all of them.
+ *)
+
+{}
+
+P0(int *a, int *b)
+{
+	int r0;
+
+	WRITE_ONCE(*a, 1);
+	smp_mb();
+	r0 = READ_ONCE(*b);
+}
+
+P1(int *a, int *b)
+{
+	int r0;
+
+	WRITE_ONCE(*b, 1);
+	smp_mb();
+	r0 = READ_ONCE(*a);
+}
+
+exists (0:r0=0 /\ 1:r0=0)
tools/testing/hpcc/litmus/limit-undo-level0.litmus new file +35 -0
new file mode 100644
index 000000000000..1bda7b3835de
@@ -0,0 +1,35 @@
+C limit-undo-level0
+
+(*
+ * Result: Never
+ *
+ * An addition which does not fit is undone on the same CPU. Both stay
+ * in the level 0 counters, l0p for the additions and l0n for the
+ * subtractions. The full barrier of percpu_counter_tree_limit_add()
+ * comes between them. The precise sum of the limit counter reads l0n,
+ * then l0p after a read barrier. It never sees the subtraction without
+ * the addition.
+ *)
+
+{}
+
+P0(int *l0p, int *l0n)
+{
+	int r;
+
+	WRITE_ONCE(*l0p, 1);
+	smp_mb();
+	r = cmpxchg_relaxed(l0n, 0, 1);
+}
+
+P1(int *l0p, int *l0n)
+{
+	int r0;
+	int r1;
+
+	r0 = READ_ONCE(*l0n);
+	smp_rmb();
+	r1 = READ_ONCE(*l0p);
+}
+
+exists (0:r=0 /\ 1:r0=1 /\ 1:r1=0)
tools/testing/hpcc/litmus/limit-undo-root-rmb.litmus new file +30 -0
new file mode 100644
index 000000000000..3b43afbeb8e9
@@ -0,0 +1,30 @@
+C limit-undo-root-rmb
+
+(*
+ * Result: Never
+ *
+ * Like limit-undo-root, with a read barrier between the two reads
+ * instead of the acquire.
+ *)
+
+{}
+
+P0(atomic_t *p, atomic_t *n)
+{
+	int r;
+
+	r = atomic_add_return(1, p);
+	r = atomic_add_return_release(1, n);
+}
+
+P1(atomic_t *p, atomic_t *n)
+{
+	int r0;
+	int r1;
+
+	r0 = atomic_read(n);
+	smp_rmb();
+	r1 = atomic_read(p);
+}
+
+exists (1:r0=1 /\ 1:r1=0)
tools/testing/hpcc/litmus/limit-undo-root-unordered.litmus new file +29 -0
new file mode 100644
index 000000000000..65bc0f2900b2
@@ -0,0 +1,29 @@
+C limit-undo-root-unordered
+
+(*
+ * Result: Sometimes
+ *
+ * Like limit-undo-root, without ordering between the two reads. The
+ * check can then see the subtraction without the addition.
+ *)
+
+{}
+
+P0(atomic_t *p, atomic_t *n)
+{
+	int r;
+
+	r = atomic_add_return(1, p);
+	r = atomic_add_return_release(1, n);
+}
+
+P1(atomic_t *p, atomic_t *n)
+{
+	int r0;
+	int r1;
+
+	r0 = atomic_read(n);
+	r1 = atomic_read(p);
+}
+
+exists (1:r0=1 /\ 1:r1=0)
tools/testing/hpcc/litmus/limit-undo-root.litmus new file +32 -0
new file mode 100644
index 000000000000..72335ee2ee6c
@@ -0,0 +1,32 @@
+C limit-undo-root
+
+(*
+ * Result: Never
+ *
+ * An addition which does not fit is undone on the same CPU. Its carry
+ * reaches the root of the additions p. Then the undo reaches the root of
+ * the subtractions n, with a release. The check reads n with an acquire,
+ * then p. It never sees the subtraction without the addition, which
+ * would take the difference below the value.
+ *)
+
+{}
+
+P0(atomic_t *p, atomic_t *n)
+{
+	int r;
+
+	r = atomic_add_return(1, p);
+	r = atomic_add_return_release(1, n);
+}
+
+P1(atomic_t *p, atomic_t *n)
+{
+	int r0;
+	int r1;
+
+	r0 = atomic_read_acquire(n);
+	r1 = atomic_read(p);
+}
+
+exists (1:r0=1 /\ 1:r1=0)
tools/testing/hpcc/litmus/publish-approximate-sum.litmus new file +40 -0
new file mode 100644
index 000000000000..be4396a96ebc
@@ -0,0 +1,40 @@
+C publish-approximate-sum
+
+(*
+ * Result: Never
+ *
+ * percpu_counter_tree_activate_many() zeroes the per-CPU counter l0mem
+ * and the root rootmem, which held stale values, then publishes approx_sum
+ * and level0 with releases. See "Publication of the tree" in
+ * lib/percpu_counter_tree.c.
+ *
+ * The approximate sum reads approx_sum, then the root through it. The
+ * address dependency orders the two reads. It never sees the stale
+ * root.
+ *)
+
+{
+	level0=nolevel0;
+	approx_sum=noroot;
+	l0mem=1;
+	rootmem=1;
+}
+
+P0(int **level0, int **approx_sum, int *l0mem, int *rootmem)
+{
+	WRITE_ONCE(*l0mem, 0);
+	WRITE_ONCE(*rootmem, 0);
+	smp_store_release(approx_sum, rootmem);
+	smp_store_release(level0, l0mem);
+}
+
+P1(int **level0, int **approx_sum)
+{
+	int *r0;
+	int r1;
+
+	r0 = READ_ONCE(*approx_sum);
+	r1 = READ_ONCE(*r0);
+}
+
+exists (1:r0=rootmem /\ 1:r1=1)
tools/testing/hpcc/litmus/publish-carry-normb.litmus new file +36 -0
new file mode 100644
index 000000000000..bc5fa4a6aaad
@@ -0,0 +1,36 @@
+C publish-carry-normb
+
+(*
+ * Result: Sometimes
+ *
+ * Like publish-carry, without the read barrier. The carry slow path can
+ * then see approx_sum unpublished.
+ *)
+
+{
+	level0=nolevel0;
+	approx_sum=noroot;
+	l0mem=1;
+	rootmem=1;
+}
+
+P0(int **level0, int **approx_sum, int *l0mem, int *rootmem)
+{
+	WRITE_ONCE(*l0mem, 0);
+	WRITE_ONCE(*rootmem, 0);
+	smp_store_release(approx_sum, rootmem);
+	smp_store_release(level0, l0mem);
+}
+
+P1(int **level0, int **approx_sum)
+{
+	int *r0;
+	int *r1;
+	int r2;
+
+	r0 = READ_ONCE(*level0);
+	r1 = READ_ONCE(*approx_sum);
+	r2 = READ_ONCE(*r1);
+}
+
+exists (1:r0=l0mem /\ (1:r1=noroot \/ 1:r2=1))
tools/testing/hpcc/litmus/publish-carry.litmus new file +43 -0

43 lines not on this page · raw message

tools/testing/hpcc/litmus/publish-precise-sum-noacquire.litmus new file +38 -0
new file mode 100644
index 000000000000..b3fcfad22a61
@@ -0,0 +1,38 @@
+C publish-precise-sum-noacquire
+
+(*
+ * Result: Sometimes
+ *
+ * Like publish-precise-sum, with a plain read of level0. The precise sum
+ * can then see approx_sum unpublished.
+ *)
+
+{
+	level0=nolevel0;
+	approx_sum=noroot;
+	l0mem=1;
+	rootmem=1;
+}
+
+P0(int **level0, int **approx_sum, int *l0mem, int *rootmem)
+{
+	WRITE_ONCE(*l0mem, 0);
+	WRITE_ONCE(*rootmem, 0);
+	smp_store_release(approx_sum, rootmem);
+	smp_store_release(level0, l0mem);
+}
+
+P1(int **level0, int **approx_sum)
+{
+	int *r0;
+	int *r1;
+	int r2;
+	int r3;
+
+	r0 = READ_ONCE(*level0);
+	r1 = READ_ONCE(*approx_sum);
+	r2 = READ_ONCE(*r1);
+	r3 = READ_ONCE(*r0);
+}
+
+exists (1:r0=l0mem /\ (1:r1=noroot \/ 1:r2=1 \/ 1:r3=1))
tools/testing/hpcc/litmus/publish-precise-sum.litmus new file +44 -0

44 lines not on this page · raw message

tools/testing/hpcc/litmus/publish-update-norelease.litmus new file +34 -0
new file mode 100644
index 000000000000..44a3d387b760
@@ -0,0 +1,34 @@
+C publish-update-norelease
+
+(*
+ * Result: Sometimes
+ *
+ * Like publish-update, with plain stores instead of the releases. The
+ * update fast path can then see the stale per-CPU counter.
+ *)
+
+{
+	level0=nolevel0;
+	approx_sum=noroot;
+	l0mem=1;
+	rootmem=1;
+}
+
+P0(int **level0, int **approx_sum, int *l0mem, int *rootmem)
+{
+	WRITE_ONCE(*l0mem, 0);
+	WRITE_ONCE(*rootmem, 0);
+	WRITE_ONCE(*approx_sum, rootmem);
+	WRITE_ONCE(*level0, l0mem);
+}
+
+P1(int **level0, int **approx_sum)
+{
+	int *r0;
+	int r1;
+
+	r0 = READ_ONCE(*level0);
+	r1 = READ_ONCE(*r0);
+}
+
+exists (1:r0=l0mem /\ 1:r1=1)
tools/testing/hpcc/litmus/publish-update.litmus new file +40 -0
new file mode 100644
index 000000000000..55603a274b28
@@ -0,0 +1,40 @@
+C publish-update
+
+(*
+ * Result: Never
+ *
+ * percpu_counter_tree_activate_many() zeroes the per-CPU counter l0mem
+ * and the root rootmem, which held stale values, then publishes approx_sum
+ * and level0 with releases. See "Publication of the tree" in
+ * lib/percpu_counter_tree.c.
+ *
+ * The update fast path reads level0, then its per-CPU counter through
+ * it. The address dependency orders the two reads. It never sees the
+ * stale per-CPU counter.
+ *)
+
+{
+	level0=nolevel0;
+	approx_sum=noroot;
+	l0mem=1;
+	rootmem=1;
+}
+
+P0(int **level0, int **approx_sum, int *l0mem, int *rootmem)
+{
+	WRITE_ONCE(*l0mem, 0);
+	WRITE_ONCE(*rootmem, 0);
+	smp_store_release(approx_sum, rootmem);
+	smp_store_release(level0, l0mem);
+}
+
+P1(int **level0, int **approx_sum)
+{
+	int *r0;
+	int r1;
+
+	r0 = READ_ONCE(*level0);
+	r1 = READ_ONCE(*r0);
+}
+
+exists (1:r0=l0mem /\ 1:r1=1)
Signature · 1 line
2.47.3
author reviewer
#17 lore raw

RFC PATCH v25 11/14 mm: shmem: use a limit counter for the tmpfs size limit

In reply to Mathieu Desnoyers

The size limit of tmpfs (the size= mount option) is a struct percpu_counter. Each block allocation checks it with percpu_counter_limited_add(). That check takes no lock only while the mount is more than batch * nr_cpus pages below its size. With the default batch size of 768 at 384 CPUs, this is 294912 pages, 1.1 GB. A smaller mount, such as a 64 MB /dev/shm, takes the counter spinlock and sums all CPUs on every page. On a 384-CPU host with 384 processes allocating, 99.5% of the time goes to that spinlock.

Use a hierarchical limit counter instead. Its batch size is chosen from the size. When the size allows, its accuracy is within 1/4 of the size. Block allocations then sum the CPUs only in the last 1/4 of the size. They take no lock. The limit stays strict.

Near a full mount, an allocation can fail although it fits. This happens while a concurrent allocation of a few pages, which does not fit, is being undone. A large folio is checked before it is added, so a large folio which does not fit has no such effect.

A mount without a size limit never counts its blocks. A remount cannot add a limit. So such a mount no longer allocates the counter.

A remount keeps the batch size. A mount grown by remount thus keeps the smaller batch size of its first size. Under concurrent allocations, a remount to a smaller size can be refused although the use fits.

Test: fallocate() of one page at a time into one file per process, all on one mount. This is a will-it-scale variant. It ran in a 384-vCPU guest pinned to a 2-socket AMD EPYC 9654 host, on v7.4-rc2. In thousands of calls per second:

size= processes before after

  64 MB          1      208      483
  64 MB         64      256    17771
  64 MB        384      126    54275
  1 GB         384      125    93879
  2 GB         384    93851    93476
  16 GB        384    93737    94806

Below 1.1 GB, the mount scales again with the number of processes. At 2 GB and above, the results are within 1% of before. Within the last 1/4 of the size, each allocation sums both counters over all CPUs. With one process, this is 37% slower than before. With 384 processes, it is about 100 times faster.

---
 include/linux/shmem_fs.h |  3 ++-
 mm/shmem.c               | 33 +++++++++++++++++++++++----------
 2 files changed, 25 insertions(+), 11 deletions(-)
include/linux/shmem_fs.h +2 -1
index f89b4b151133..b37adf32e4ef 100644
@@ -7,6 +7,7 @@
 #include <linux/mempolicy.h>
 #include <linux/pagemap.h>
 #include <linux/percpu_counter.h>
+#include <linux/percpu_counter_tree.h>
 #include <linux/xattr.h>
 #include <linux/fs_parser.h>
 #include <linux/userfaultfd_k.h>
@@ -76,7 +77,7 @@ struct shmem_quota_limits {
 
 struct shmem_sb_info {
 	unsigned long max_blocks;   /* How many blocks are allowed */
-	struct percpu_counter used_blocks;  /* How many are allocated */
+	struct percpu_counter_tree_limit used_blocks; /* How many are allocated */
 	unsigned long max_inodes;   /* How many inodes are allowed */
 	unsigned long free_ispace;  /* How much ispace left for allocation */
 	raw_spinlock_t stat_lock;   /* Serialize shmem_sb_info changes */
mm/shmem.c +23 -10
index b8399bb71997..2e368d7b0e41 100644
@@ -231,13 +231,13 @@ int shmem_inode_acct_blocks(struct inode *inode, long pages)
 
 	might_sleep();	/* when quotas */
 	if (sbinfo->max_blocks) {
-		if (!percpu_counter_limited_add(&sbinfo->used_blocks,
-						sbinfo->max_blocks, pages))
+		if (!percpu_counter_tree_limit_add(&sbinfo->used_blocks,
+						   sbinfo->max_blocks, pages))
 			goto unacct;
 
 		err = dquot_alloc_block_nodirty(inode, pages);
 		if (err) {
-			percpu_counter_sub(&sbinfo->used_blocks, pages);
+			percpu_counter_tree_limit_sub(&sbinfo->used_blocks, pages);
 			goto unacct;
 		}
 	} else {
@@ -262,7 +262,7 @@ static void shmem_inode_unacct_blocks(struct inode *inode, long pages)
 	dquot_free_block_nodirty(inode, pages);
 
 	if (sbinfo->max_blocks)
-		percpu_counter_sub(&sbinfo->used_blocks, pages);
+		percpu_counter_tree_limit_sub(&sbinfo->used_blocks, pages);
 	shmem_unacct_blocks(info->flags, pages);
 }
 
@@ -4048,9 +4048,11 @@ static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
 	buf->f_namelen = NAME_MAX;
 	if (sbinfo->max_blocks) {
 		buf->f_blocks = sbinfo->max_blocks;
+		/* Under concurrent allocations, the sum can be above the size. */
 		buf->f_bavail =
 		buf->f_bfree  = sbinfo->max_blocks -
-				percpu_counter_sum(&sbinfo->used_blocks);
+				min(percpu_counter_tree_limit_precise_sum(&sbinfo->used_blocks),
+				    sbinfo->max_blocks);
 	}
 	if (sbinfo->max_inodes) {
 		buf->f_files = sbinfo->max_inodes;
@@ -5020,8 +5022,8 @@ static int shmem_reconfigure(struct fs_context *fc)
 			err = "Cannot retroactively limit size";
 			goto out;
 		}
-		if (percpu_counter_compare(&sbinfo->used_blocks,
-					   ctx->blocks) > 0) {
+		if (percpu_counter_tree_limit_precise_sum(&sbinfo->used_blocks) >
+		    ctx->blocks) {
 			err = "Too small a size for current use";
 			goto out;
 		}
@@ -5187,7 +5189,7 @@ static void shmem_put_super(struct super_block *sb)
 	shmem_disable_quotas(sb);
 #endif
 	free_percpu(sbinfo->ino_batch);
-	percpu_counter_destroy(&sbinfo->used_blocks);
+	percpu_counter_tree_limit_destroy(&sbinfo->used_blocks);
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
 	list_lru_destroy(&sbinfo->shrinklist);
 #endif
@@ -5212,6 +5214,7 @@ static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
 	static struct lock_class_key shmem_unused_huge_lock_key;
 #endif
 	struct shmem_options *ctx = fc->fs_private;
+	unsigned long batch;
 	struct inode *inode;
 	struct shmem_sb_info *sbinfo;
 	int error = -ENOMEM;
@@ -5286,8 +5289,18 @@ static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
 	ctx->mpol = NULL;
 
 	raw_spin_lock_init(&sbinfo->stat_lock);
-	if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
-		goto failed;
+	/*
+	 * A mount without a size limit never counts its blocks. A remount
+	 * cannot add a limit. Otherwise, pick the batch size from the size.
+	 * When the size allows, its accuracy is within 1/4 of the size. A
+	 * block allocation then sums all CPUs only within the last 1/4 of the
+	 * size. A remount keeps the batch size.
+	 */
+	if (sbinfo->max_blocks) {
+		batch = percpu_counter_tree_batch_for_accuracy(sbinfo->max_blocks / 4);
+		if (percpu_counter_tree_limit_init(&sbinfo->used_blocks, batch, GFP_KERNEL))
+			goto failed;
+	}
 
 #ifdef CONFIG_TRANSPARENT_HUGEPAGE
 	if (list_lru_init_memcg_key(&sbinfo->shrinklist, sb->s_shrink,
Signature · 1 line
2.47.3
author reviewer
#18 lore raw

RFC PATCH v25 12/14 lib: percpu_counter_tree: add the arity boot parameter

In reply to Mathieu Desnoyers

The fan-out of each tree level is selected at boot from nr_cpu_ids, the highest possible CPU number plus one, using a table tuned for the RSS counters on one machine, a 2-socket AMD EPYC 9654 with 192 cores and 384 logical CPUs. The best shape depends on the cost of cache line transfers on a given machine, which varies with the number of sockets, the cache topology and SMT, so it may differ on other hardware.

Add the percpu_counter_tree.arity= boot parameter, which overrides the tree shape with the fan-out of each level, from the per-cpu counters to the root, so the shapes can be compared on other machines, to improve the default table. For example, when nr_cpu_ids is 16, "16" is a flat tree and "4,4" a tree with 4 intermediate counters. Each fan-out is a power of 2, and their product must be nr_cpu_ids rounded up to a power of 2. An invalid shape is ignored with a warning.

The shape in use is printed at boot, and can be read from /sys/module/percpu_counter_tree/parameters/arity.

Cover the parsing of the parameter in the userspace test, with valid and invalid shapes, and run the counter tests on the valid ones.

---
 .../admin-guide/kernel-parameters.txt         | 14 +++
 .../core-api/percpu-counter-tree.rst          |  3 +-
 lib/percpu_counter_tree.c                     | 96 ++++++++++++++++++-
 tools/testing/hpcc/include/hpcc_shim.h        |  4 +
 .../testing/hpcc/include/linux/moduleparam.h  | 12 +++
 tools/testing/hpcc/main.c                     | 78 ++++++++++++++-
 6 files changed, 201 insertions(+), 6 deletions(-)
 create mode 100644 tools/testing/hpcc/include/linux/moduleparam.h
Documentation/admin-guide/kernel-parameters.txt +14 -0
index 0b3c140babd9..c368affa2115 100644
@@ -5342,6 +5342,20 @@ Kernel parameters
 			allocator.  This parameter is primarily	for debugging
 			and performance comparison.
 
+	percpu_counter_tree.arity=	[KNL,SMP]
+			Format: <fan-out>[,<fan-out>...]
+			Override the shape of the hierarchical per-cpu
+			counter trees (used for the RSS counters), listing
+			the fan-out of each tree level from the per-cpu
+			counters to the root. Each fan-out is a power of 2
+			and their product must be nr_cpu_ids (the highest
+			possible CPU number plus one) rounded up to a power
+			of 2, e.g. "16" (flat) or "4,4" when nr_cpu_ids
+			is 16. An invalid shape is ignored with a warning.
+			The shape in use is shown in
+			/sys/module/percpu_counter_tree/parameters/arity.
+			This parameter is meant for performance comparison.
+
 	pirq=		[SMP,APIC] Manual mp-table setup
 			See Documentation/arch/x86/i386/IO-APIC.rst.
 
Documentation/core-api/percpu-counter-tree.rst +2 -1
index 87babe2276c4..8aebf91aa133 100644
@@ -63,7 +63,8 @@ possible CPU, and the tree items, whose number depends on nr_cpu_ids, so
 struct percpu_counter_tree has a fixed size.
 
 The fan-out of each tree level is selected at boot from nr_cpu_ids, the
-highest possible CPU number plus one.
+highest possible CPU number plus one. It can be overridden with the
+percpu_counter_tree.arity= boot parameter for performance comparison.
 
 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
lib/percpu_counter_tree.c +92 -4

146 lines not on this page · raw message

tools/testing/hpcc/include/hpcc_shim.h +4 -0
index 5d96d68f79bd..38407ac7cbbf 100644
@@ -34,8 +34,12 @@
 #define abs(x) ({ typeof(x) __x = (x); __x < 0 ? -__x : __x; })
 
 #define pr_err(...)		fprintf(stderr, __VA_ARGS__)
+#define pr_warn(...)		fprintf(stderr, __VA_ARGS__)
 #define pr_info(...)		do { if (0) printf(__VA_ARGS__); } while (0)
 
+/* Implemented in main.c. */
+char *get_options(const char *str, int nints, int *ints);
+
 extern unsigned long hpcc_nr_warnings;
 
 #define WARN(cond, ...) ({						\
tools/testing/hpcc/include/linux/moduleparam.h new file +12 -0
new file mode 100644
index 000000000000..7e40df4295b2
@@ -0,0 +1,12 @@
+/* SPDX-License-Identifier: GPL-2.0+ OR MIT */
+#include "../hpcc_shim.h"
+
+struct kernel_param;
+
+struct kernel_param_ops {
+	int (*set)(const char *val, const struct kernel_param *kp);
+	int (*get)(char *buffer, const struct kernel_param *kp);
+};
+
+#define module_param_cb(name, ops, arg, perm)
+#define MODULE_PARM_DESC(parm, desc)
tools/testing/hpcc/main.c +77 -1

101 lines not on this page · raw message

Signature · 1 line
2.47.3
author reviewer
#19 lore raw

RFC PATCH v25 13/14 mm: add the rss_stat_batch boot parameter

In reply to Mathieu Desnoyers

The RSS counters use a batch size of 32: each CPU accumulates up to 31 pages in either direction before propagating a carry into the counter tree. A smaller batch improves the accuracy of the approximate RSS, and a larger batch reduces the cost of updates.

Add the rss_stat_batch= boot parameter to compare batch sizes on a given machine, along with the percpu_counter_tree.arity= boot parameter for the tree shape. It accepts a power of 2 between 2 and 128, and is ignored with a warning otherwise.

---
 .../admin-guide/kernel-parameters.txt         | 10 ++++++++
 kernel/fork.c                                 | 23 ++++++++++++++++---
 2 files changed, 30 insertions(+), 3 deletions(-)
Documentation/admin-guide/kernel-parameters.txt +10 -0
index c368affa2115..ba2bdeb1480b 100644
@@ -6792,6 +6792,16 @@ Kernel parameters
 			debug mode. Defaults to CONFIG_RSEQ_DEBUG_DEFAULT_ENABLE.
 			Format: <bool>
 
+	rss_stat_batch=	[KNL,SMP]
+			Format: <integer>
+			Batch size of the per-mm RSS counters: the number of
+			pages a CPU accumulates before propagating them into
+			the counter tree. A power of 2 between 2 and 128.
+			A smaller batch improves the accuracy of the
+			approximate RSS, a larger batch reduces the update
+			cost. Default: 32.
+			This parameter is meant for performance comparison.
+
 	rt_group_sched=	[KNL] Enable or disable SCHED_RR/FIFO group scheduling
 			when CONFIG_RT_GROUP_SCHED=y. Defaults to
 			!CONFIG_RT_GROUP_SCHED_DEFAULT_DISABLED.
kernel/fork.c +20 -3
index dc1db6cb5da0..f582c1b073fe 100644
@@ -138,9 +138,26 @@
 #define MAX_THREADS FUTEX_TID_MASK
 
 /*
- * Batch size of rss stat approximation
+ * Batch size of rss stat approximation, tunable with the rss_stat_batch=
+ * boot parameter to compare batch sizes on a given machine.
  */
-#define RSS_STAT_BATCH_SIZE	32
+static unsigned int rss_stat_batch_size __ro_after_init = 32;
+
+static int __init setup_rss_stat_batch(char *str)
+{
+	unsigned int batch;
+
+	if (kstrtouint(str, 0, &batch) || batch < 2 || !is_power_of_2(batch) ||
+	    batch > PERCPU_COUNTER_TREE_MAX_BATCH) {
+		pr_warn("rss_stat_batch: expecting a power of 2 between 2 and %u\n",
+			PERCPU_COUNTER_TREE_MAX_BATCH);
+		return 1;
+	}
+	rss_stat_batch_size = batch;
+	pr_info("rss_stat_batch: %u\n", batch);
+	return 1;
+}
+__setup("rss_stat_batch=", setup_rss_stat_batch);
 
 /*
  * Protected counters by write_lock_irq(&tasklist_lock)
@@ -1149,7 +1166,7 @@ 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_tree_init_many_lazy(mm->rss_stat, NR_MM_COUNTERS, RSS_STAT_BATCH_SIZE))
+	if (percpu_counter_tree_init_many_lazy(mm->rss_stat, NR_MM_COUNTERS, rss_stat_batch_size))
 		goto fail_pcpu;
 
 	lru_gen_init_mm(mm);
Signature · 1 line
2.47.3
author reviewer
#20 lore raw

RFC PATCH v25 14/14 lib: add a benchmark of hierarchical per-cpu counters

In reply to Mathieu Desnoyers

Add a KUnit benchmark comparing the hierarchical per-cpu counters with struct percpu_counter, so their performance can be compared on various machines:

- update: cost of an update with a kthread on each online CPU, on one shared counter, on one counter per thread, on groups of 4 counters initialized together like the RSS counters of an mm, and on one lazily initialized counter per thread updated by its owner, like a single-threaded process, with increments of +1, alternating +1/-1, and random increments up to 32 and 512.
- lifecycle: cost of initializing and destroying 4 counters together, like fork and exit of an mm, eagerly or lazily, from one thread or from all online CPUs.
- churn: like lifecycle, with a few updates, keeping some of the counters alive until the end, like long-lived processes.

The batch size of the hierarchical counters is selected with the percpu_counter_tree_bench.batch= parameter (32 by default, like the RSS counters), and the tree shape with the percpu_counter_tree.arity= boot parameter. The struct percpu_counter variants use their default batch size, like the RSS counters before the hierarchical counters.

The benchmark reports the accuracy of both counter implementations along with the timings. It runs for a few minutes on large machines, so it has its own config option, CONFIG_PERCPU_COUNTER_TREE_BENCH.

For example:

  ./tools/testing/kunit/kunit.py run --arch=x86_64 \
	--kconfig_add CONFIG_PERCPU_COUNTER_TREE_BENCH=y \
	--kconfig_add CONFIG_NR_CPUS=256 --qemu_args="-smp 64 -m 8192" \
	--kernel_args percpu_counter_tree.arity=8,8 \
	--kernel_args percpu_counter_tree_bench.batch=16 \
	--timeout 3000 percpu_counter_tree_bench

or, on a running kernel with CONFIG_PERCPU_COUNTER_TREE_BENCH=m:

modprobe percpu_counter_tree_bench batch=16

---
Changes since v23:
- Keep the lifecycle and churn sets of counters in struct bench_thread rather than on the stack, where debugobjects warns about a struct percpu_counter. (Reported by Sashiko.)

---
 MAINTAINERS                           |   1 +
 lib/Kconfig                           |  15 +
 lib/tests/Makefile                    |   1 +
 lib/tests/percpu_counter_tree_bench.c | 610 ++++++++++++++++++++++++++
 4 files changed, 627 insertions(+)
 create mode 100644 lib/tests/percpu_counter_tree_bench.c
MAINTAINERS +1 -0
index c9b266a5df54..8392c9ceea0f 100644
@@ -11958,6 +11958,7 @@ S:	Supported
 F:	Documentation/core-api/percpu-counter-tree.rst
 F:	include/linux/percpu_counter_tree.h
 F:	lib/percpu_counter_tree.c
+F:	lib/tests/percpu_counter_tree_bench.c
 F:	lib/tests/percpu_counter_tree_kunit.c
 F:	tools/testing/hpcc/
 
lib/Kconfig +15 -0
index 3921177a0d24..6ab9644a4cb8 100644
@@ -53,6 +53,21 @@ config PERCPU_COUNTER_TREE_KUNIT_TEST
 
 	  When in doubt, say N.
 
+config PERCPU_COUNTER_TREE_BENCH
+	tristate "Benchmark of hierarchical per-cpu counters"
+	depends on KUNIT && SMP
+	help
+	  This builds a KUnit benchmark comparing the hierarchical per-cpu
+	  counters with struct percpu_counter: update cost with all online
+	  CPUs updating shared and private counters, and init/destroy cost.
+	  It runs for a few minutes on large machines.
+
+	  The batch size and the tree shape can be changed with the
+	  percpu_counter_tree_bench.batch= and percpu_counter_tree.arity=
+	  parameters, see lib/tests/percpu_counter_tree_bench.c.
+
+	  When in doubt, say N.
+
 config BITREVERSE
 	tristate
 	select GENERIC_BITREVERSE if !HAVE_ARCH_BITREVERSE
lib/tests/Makefile +1 -0
index e98687da8706..d158a8be8a19 100644
@@ -60,5 +60,6 @@ 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_PERCPU_COUNTER_TREE_BENCH) += percpu_counter_tree_bench.o
 
 obj-$(CONFIG_TEST_RUNTIME_MODULE)		+= module/
lib/tests/percpu_counter_tree_bench.c new file +610 -0

610 lines not on this page · raw message

Signature · 1 line
2.47.3