Skip to contentSkip to conversation

perf/core: add AUX buffer kernel-consumer API

PATCH Superseded Kunwu Chan 2 participants 11 messages Oct 4

Subsystems (4)

v1 of 2 Superseded Latest is v2 →

lore
Share & tools
lore

Kunwu Chan

author
#0 lore raw

cover perf/core: add AUX buffer kernel-consumer API

ARM SPE and other tracing PMUs write records directly to perf AUX buffers. Unlike ordinary sampling PMUs, they do not necessarily generate a perf_event_overflow() callback for each record. A kernel consumer therefore needs to own and drain an AUX buffer rather than rely on the overflow path.

Userspace obtains AUX storage through perf_event_open() and mmap(). Kernel consumers created through perf_event_create_kernel_counter() currently have no interface to allocate and manage AUX buffers.

This series adds the minimal perf-core interfaces needed for that use case. It was previously posted as RFC [1]; this version incorporates feedback from that posting and is intended for review toward merging. Patches 1-2 add the AUX owner interface, lifecycle helpers, and cursor/copy operations without exposing perf's internal page layout. Patches 3-5 exercise the new interfaces with KUnit, a userspace regression test, and a selftest script. The first consumer is a DAMON ARM SPE backend, but this series is independent of DAMON and adds no consumer-specific policy to perf.

The API follows the existing non-overwrite AUX ring-buffer protocol. Setup and release serialise buffer lifetime transitions through event->mmap_mutex. Cursor reads/writes use the same ordering rules as the userspace mmap consumer, and copy validates ranges in the absolute cursor domain before applying the ring mask.

Testing
=======

The series builds cleanly at each step.

arm64 (Kunpeng 920, 256 CPUs, SPEv1.1), Image built from this series and booted on the hardware:

KUnit: pass:39 fail:0 skip:0. Userspace regression (arm_spe_0): full pass; the producer head advances with live SPE traffic. Selftest
script: 92 passed, 0 failed, 2 skipped (both environment skips). perf record with arm_spe_0 captures data; dmesg stays clean.

x86_64 (vmlinux build, qemu/kvm): KUnit pass:39 fail:0 skip:0, also under KASAN + lockdep (PROVE_LOCKING) and 15 repeated boots with no splat. Userspace regression (Intel PT): full pass. The selftest script also runs from installed selftest locations.

Changes since RFC [1]:

- Serialize AUX teardown under event->mmap_mutex and fix lifetime handling around ring_buffer_attach().
- Improve KUnit cleanup, concurrent-release coverage, and buffer-full assertions.
- Extend userspace and selftest coverage, including environment handling fixes and installed selftest support.
- Clarify AUX lifecycle, ordering, and cursor validation documentation.

[1] https://lore.kernel.org/linux-perf-users/[email protected]/

Kunwu Chan (3):
perf/core: add AUX buffer ownership for kernel events perf/core: add AUX ring accessors for kernel consumers selftests/perf_events: add AUX kernel API selftest script

Lian Wang (2):
perf/core: add KUnit tests for AUX kernel-consumer API selftests/perf_events: add userspace AUX regression test

 .../userspace-api/perf_ring_buffer.rst        |   62 +-
 include/linux/perf_event.h                    |   18 +
 kernel/events/Makefile                        |    1 +
 kernel/events/aux_kernel_test.c               | 1152 +++++++++++++++++
 kernel/events/core.c                          |  164 +++
 kernel/events/internal.h                      |    6 +
 kernel/events/ring_buffer.c                   |  211 ++-
 lib/Kconfig.debug                             |   14 +
 tools/testing/selftests/perf_events/Makefile  |    2 +
 .../selftests/perf_events/aux_kernel.sh       |  631 +++++++++
 .../perf_events/aux_kernel_usermode.c         |  627 +++++++++
 tools/testing/selftests/perf_events/config    |    2 +
 12 files changed, 2885 insertions(+), 5 deletions(-)
 create mode 100644 kernel/events/aux_kernel_test.c
 create mode 100755 tools/testing/selftests/perf_events/aux_kernel.sh
 create mode 100644 tools/testing/selftests/perf_events/aux_kernel_usermode.c

base-commit: 6350de8671b94afb7691d110f63bcda42f658a69

Signature · 1 line
2.43.0
author
#1 lore raw

PATCH 1/5 perf/core: add AUX buffer ownership for kernel events

Add an in-kernel AUX owner reference and setup/release helpers for kernel-created perf events that need an AUX buffer without a userspace mmap. The setup path validates that the event is a kernel event with no parent, rejects non-power-of-two page counts and negative watermark values, allocates the perf buffer and AUX pages, records the kernel owner, and attaches the buffer under the same lock.

perf_event_release_aux() stops AUX writers, frees AUX storage, and detaches the buffer, in that order, matching the AUX teardown ordering of perf_mmap_close(): perf_pmu_output_stop() walks event->rb->event_list and rb_free_aux() must run while the buffer is still referenced by the event. The single event->rb reference is dropped by ring_buffer_attach(event, NULL) itself, so the release path does not put it again.

Both functions run under event->mmap_mutex, the lock that already serialises ring-buffer attach/detach transitions for an event:
perf_mmap(), perf_mmap_close(), _perf_event_set_output() and _free_event() all hold it around ring_buffer_attach(). Concurrent perf_event_release_aux() callers therefore go through the same serialisation point, and a second release call, or a release of a buffer this API does not own, is a no-op.

Keep aux_mmap_count dedicated to userspace mappings. perf_aux_output_begin() accepts a writer while either a userspace or kernel owner remains, preserving the existing teardown ordering.

---
 include/linux/perf_event.h  |  11 +++
 kernel/events/core.c        | 164 ++++++++++++++++++++++++++++++++++++
 kernel/events/internal.h    |   6 ++
 kernel/events/ring_buffer.c |  11 ++-
 4 files changed, 188 insertions(+), 4 deletions(-)
include/linux/perf_event.h +11 -0
index 7797ce207555..78fd2ed11fcf 100644
@@ -1255,6 +1255,17 @@ perf_event_create_kernel_counter(struct perf_event_attr *attr,
 				 perf_overflow_handler_t callback,
 				 void *context);
 
+/*
+ * AUX ring-buffer support for kernel-created events (no user mmap).
+ * perf_event_setup_aux() allocates the buffer the PMU writes into via
+ * perf_aux_output_begin()/perf_aux_output_end(); the paired
+ * perf_event_release_aux() must be called before
+ * perf_event_release_kernel().
+ */
+extern int perf_event_setup_aux(struct perf_event *event, int nr_pages,
+				long watermark);
+extern void perf_event_release_aux(struct perf_event *event);
+
 extern void perf_pmu_migrate_context(struct pmu *pmu,
 				     int src_cpu, int dst_cpu);
 extern int perf_event_read_local(struct perf_event *event, u64 *value,
kernel/events/core.c +164 -0

170 lines not on this page · raw message

kernel/events/internal.h +6 -0
index c03c4f2eea57..760b7659ad87 100644
@@ -48,6 +48,12 @@ struct perf_buffer {
 	int				aux_nr_pages;
 	int				aux_overwrite;
 	refcount_t			aux_mmap_count;
+	/*
+	 * In-kernel AUX owner reference, set by perf_event_setup_aux():
+	 * admits writers and ties the AUX teardown to
+	 * perf_event_release_aux() when no userspace mmap holds the buffer.
+	 */
+	refcount_t			aux_kernel_count;
 	unsigned long			aux_mmap_locked;
 	void				(*free_aux)(void *);
 	refcount_t			aux_refcount;
kernel/events/ring_buffer.c +7 -4
index 1b1ffe0533e5..eae28e42346c 100644
@@ -395,14 +395,17 @@ void *perf_aux_output_begin(struct perf_output_handle *handle,
 		goto err;
 
 	/*
-	 * If aux_mmap_count is zero, the aux buffer is in perf_mmap_close(),
-	 * about to get freed, so we leave immediately.
+	 * If no AUX owner remains, the buffer is in perf_mmap_close() or
+	 * perf_event_release_aux(), about to get freed, so we leave
+	 * immediately.  aux_mmap_count tracks user-space mmap owners;
+	 * aux_kernel_count tracks in-kernel owners (perf_event_setup_aux()).
 	 *
-	 * Checking rb::aux_mmap_count and rb::refcount has to be done in
+	 * Checking the AUX owner counts and rb::refcount has to be done in
 	 * the same order, see perf_mmap_close. Otherwise we end up freeing
 	 * aux pages in this path, which is a bug, because in_atomic().
 	 */
-	if (!refcount_read(&rb->aux_mmap_count))
+	if (!refcount_read(&rb->aux_mmap_count) &&
+	    !refcount_read(&rb->aux_kernel_count))
 		goto err;
 
 	if (!refcount_inc_not_zero(&rb->aux_refcount))
Signature · 1 line
2.43.0
author
#3 lore raw

PATCH 2/5 perf/core: add AUX ring accessors for kernel consumers

In reply to Kunwu Chan

Add kernel-consumer accessors for the published AUX producer head, the consumer tail, and copying a possibly wrapped AUX interval without exposing perf's internal page array.

Use the same memory ordering as mmap consumers: order data reads after the published head with smp_rmb() and order completed data reads before advancing the tail with smp_mb(). Validate cursor distances in the absolute cursor domain before applying the ring mask, so rewound, already-consumed, and future windows are rejected even across unsigned cursor wrap.

Hold an AUX reference while copying so storage cannot disappear under the consumer. Restrict the helpers to buffers owned by the kernel AUX setup API. Document the API in Documentation/userspace-api/perf_ring_buffer.rst.

---
 .../userspace-api/perf_ring_buffer.rst        |  62 +++++-
 include/linux/perf_event.h                    |   7 +
 kernel/events/ring_buffer.c                   | 202 +++++++++++++++++-
 3 files changed, 269 insertions(+), 2 deletions(-)
Documentation/userspace-api/perf_ring_buffer.rst +61 -1
index dc71544532ce..206c57ee6c35 100644
@@ -26,6 +26,7 @@ Perf ring buffer
     3.1  The relationship between AUX and regular ring buffers
     3.2  AUX events
     3.3  Snapshot mode
+    3.4  Kernel-consumer AUX buffer access
 
 
 1. Introduction
@@ -827,4 +828,63 @@ mode.
          |                 AUX Ring buffer 3     | <- aux_head
          +---------------------------------------+
 
-                Figure 9. Snapshot with system wide mode
+                 Figure 9. Snapshot with system wide mode
+
+3.4 Kernel-consumer AUX buffer access
+-------------------------------------
+
+The AUX ring buffer is normally consumed from user space via mmap()
+on the perf event fd.  Some tracing PMUs (e.g. ARM SPE) write trace
+records directly to the AUX buffer without generating a
+perf_event_overflow() callback for each record.  A kernel consumer
+therefore needs to own and drain the AUX buffer itself rather than
+rely on the overflow path.
+
+The perf core provides five exported functions for in-kernel
+consumers that do not have a user-space mmap:
+
+  - ``perf_event_setup_aux(event, nr_pages, watermark)`` — allocate
+    an AUX ring buffer for a kernel-created perf event.  The event
+    must be created by ``perf_event_create_kernel_counter()``; it
+    must not have a parent or an existing ring buffer.  ``nr_pages``
+    must be a power of two and ``watermark`` must be non-negative
+    (0 selects half the buffer).
+
+  - ``perf_event_release_aux(event)`` — tear down the AUX buffer
+    allocated by ``perf_event_setup_aux()``.  Must be called before
+    ``perf_event_release_kernel()``.  Safe to call on an event that
+    never had an AUX buffer, and on one whose buffer was already
+    released (no-op).  A ring buffer not owned by the kernel AUX API
+    is left attached.  The whole teardown is serialised on the
+    event's mmap mutex, so concurrent callers on the same event are
+    safe: one performs the teardown and the others return.
+
+  - ``perf_event_aux_head(event)`` — read the published producer
+    head.  Returns 0 if the event has no ring buffer.
+
+  - ``perf_event_aux_tail_set(event, tail)`` — advance the consumer
+    tail.  The new tail is an absolute cursor: it is accepted only
+    within the current produced window, not ahead of the published
+    producer cursor and no more than one buffer size behind it; an
+    out-of-range tail is rejected with ``-EINVAL``.
+
+  - ``perf_event_aux_copy(event, from, to, buf)`` — copy a possibly
+    wrapped AUX interval into a linear buffer.  The ``from``/``to``
+    cursors are absolute and must lie between the consumer cursor
+    (``tail``) and the published producer cursor (``head``).
+
+The owner reference is tracked by ``aux_kernel_count`` on the
+``perf_buffer``, separate from the userspace ``aux_mmap_count``.
+``perf_aux_output_begin()`` admits a writer while either owner
+count is non-zero, so a kernel consumer and a userspace consumer
+on different events for the same PMU do not interfere.
+
+A userspace mmap and a kernel ``perf_event_setup_aux()`` on the
+*same* event cannot coexist: the second call finds ``event->rb``
+already set and returns ``-EBUSY``.
+
+Memory ordering follows the same protocol as the userspace AUX
+mmap consumer: ``perf_event_aux_head()`` uses ``smp_rmb()`` to pair
+with the producer's data-write barrier before publishing ``aux_head``,
+and ``perf_event_aux_tail_set()`` uses ``smp_mb()`` to order prior
+data reads before advancing ``aux_tail``.
include/linux/perf_event.h +7 -0
index 78fd2ed11fcf..0d96145f75ed 100644
@@ -1266,6 +1266,13 @@ extern int perf_event_setup_aux(struct perf_event *event, int nr_pages,
 				long watermark);
 extern void perf_event_release_aux(struct perf_event *event);
 
+/* AUX ring accessors for kernel consumers (no user-space mmap). */
+extern unsigned long perf_event_aux_head(struct perf_event *event);
+extern int perf_event_aux_tail_set(struct perf_event *event,
+				   unsigned long tail);
+extern long perf_event_aux_copy(struct perf_event *event, unsigned long from,
+				unsigned long to, void *buf);
+
 extern void perf_pmu_migrate_context(struct pmu *pmu,
 				     int src_cpu, int dst_cpu);
 extern int perf_event_read_local(struct perf_event *event, u64 *value,
kernel/events/ring_buffer.c +201 -1

214 lines not on this page · raw message

Signature · 1 line
2.43.0
author
#5 lore raw

PATCH 3/5 perf/core: add KUnit tests for AUX kernel-consumer API

In reply to Kunwu Chan

From: Lian Wang <[email protected]>

Add a KUnit test suite (perf_aux_kernel) for the perf_event_setup_aux(), perf_event_release_aux(), perf_event_aux_head(), perf_event_aux_tail_set() and perf_event_aux_copy() functions.

A self-contained dummy AUX PMU is registered in suite_init so that every test is deterministic and needs no hardware. The dummy setup_aux pre-fills all pages with a recognisable pattern (0xAB); aux_test_produce() advances the published head via perf_aux_output_begin/end, and copy tests verify the pattern.

39 test cases cover setup/release lifecycle, writer admission and blocking, head/tail/copy accessor contract validation (including wrap-around, boundary cursors, and data correctness), buffer-full behaviour, negative watermark rejection, independence of two events on the same PMU, user/kernel coexistence simulation, and concurrent release on the same event.

Every test event is released through a kunit_add_action() cleanup, so a test aborted by a KUNIT_ASSERT_*() (which skips the remaining manual cleanup) still releases its events. The concurrent-release test waits on a struct completion instead of a lockless wait_event() condition, and does not kthread_stop() workers that exit on their own. The buffer-full test asserts that perf_aux_output_begin() refuses a full non-overwrite buffer.

Gated by CONFIG_PERF_AUX_KERNEL_KUNIT_TEST.

---
 kernel/events/Makefile          |    1 +
 kernel/events/aux_kernel_test.c | 1152 +++++++++++++++++++++++++++++++
 lib/Kconfig.debug               |   14 +
 3 files changed, 1167 insertions(+)
 create mode 100644 kernel/events/aux_kernel_test.c
kernel/events/Makefile +1 -0
index 91a62f566743..592604db2c76 100644
@@ -3,4 +3,5 @@ obj-y := core.o ring_buffer.o callchain.o
 
 obj-$(CONFIG_HAVE_HW_BREAKPOINT) += hw_breakpoint.o
 obj-$(CONFIG_HW_BREAKPOINT_KUNIT_TEST) += hw_breakpoint_test.o
+obj-$(CONFIG_PERF_AUX_KERNEL_KUNIT_TEST) += aux_kernel_test.o
 obj-$(CONFIG_UPROBES) += uprobes.o
kernel/events/aux_kernel_test.c new file +1152 -0

1,152 lines not on this page · raw message

lib/Kconfig.debug +14 -0
index 134b15a44625..7db7eb07c2f2 100644
@@ -3073,6 +3073,20 @@ config HW_BREAKPOINT_KUNIT_TEST
 
 	  If unsure, say N.
 
+config PERF_AUX_KERNEL_KUNIT_TEST
+	bool "Test perf AUX kernel-consumer API" if !KUNIT_ALL_TESTS
+	depends on PERF_EVENTS=y
+	depends on KUNIT=y
+	default KUNIT_ALL_TESTS
+	help
+	  Tests for the perf AUX kernel-consumer API functions:
+	  perf_event_setup_aux(), perf_event_release_aux(),
+	  perf_event_aux_head(), perf_event_aux_tail_set(), and
+	  perf_event_aux_copy().  Uses a dummy AUX PMU and does
+	  not require AUX-capable hardware.
+
+	  If unsure, say N.
+
 source "lib/crypto/tests/Kconfig"
 
 config SIPHASH_KUNIT_TEST
Signature · 1 line
2.43.0
author
#7 lore raw

PATCH 4/5 selftests/perf_events: add userspace AUX regression test

In reply to Kunwu Chan

From: Lian Wang <[email protected]>

Add a standalone C program that opens a perf event, mmaps the metadata and data ring, sets up the AUX area via a second mmap, enables tracing, reads aux_head from the mmap page, and tears down the mapping. This verifies the kernel-side aux_kernel_count changes do not break the existing userspace AUX mmap protocol.

Environment-dependent outcomes are reported as SKIP rather than PASS:
an AUX area mmap failure (PMU does not support userspace AUX), a PMU that allows only one open event (e.g. ARM SPE), or a 100 ms window in which no AUX data was generated are SKIP rather than PASS. The two-event independence test follows the full dual-mmap AUX protocol for both
events so both aux_mmap_count holders really exist, and the mmap-page-fields test checks the kernel-managed fields (data_offset/data_size) and the read-back of the user-published aux_offset/aux_size rather than expecting the kernel to set them.

---
 tools/testing/selftests/perf_events/Makefile  |   1 +
 .../perf_events/aux_kernel_usermode.c         | 627 ++++++++++++++++++
 tools/testing/selftests/perf_events/config    |   2 +
 3 files changed, 630 insertions(+)
 create mode 100644 tools/testing/selftests/perf_events/aux_kernel_usermode.c
tools/testing/selftests/perf_events/Makefile +1 -0
index 2e5d85770dfe..fbafbd43f097 100644
@@ -3,4 +3,5 @@ CFLAGS += -Wl,-no-as-needed -Wall $(KHDR_INCLUDES)
 LDFLAGS += -lpthread
 
 TEST_GEN_PROGS := sigtrap_threads remove_on_exec watermark_signal mmap
+TEST_GEN_PROGS += aux_kernel_usermode
 include ../lib.mk
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +627 -0

627 lines not on this page · raw message

tools/testing/selftests/perf_events/config +2 -0
index ba58ff2203e4..2508f331cfe0 100644
@@ -1 +1,3 @@
 CONFIG_PERF_EVENTS=y
+CONFIG_PERF_AUX_KERNEL_KUNIT_TEST=y
+CONFIG_KUNIT_DEBUGFS=y
Signature · 1 line
2.43.0
author
#9 lore raw

PATCH 5/5 selftests/perf_events: add AUX kernel API selftest script

In reply to Kunwu Chan

Add a shell script that runs the perf_aux_kernel KUnit suite through debugfs, builds and runs the userspace regression program, and performs static-analysis checks on the source tree (memory barriers, refcount types, boundary validation, EXPORT_SYMBOL_GPL coverage).

When an AUX-capable PMU is present, the script also runs a live perf record and checks dmesg for errors.

The script works both in-tree and from an installed selftest location:
the source-level static checks are SKIPped when no kernel source tree is found instead of failing, the installed userspace binary is run as-is when its source is absent, and runtime rebuilds honour $CC instead of hardcoding gcc.
Usage: sudo ./aux_kernel.sh [--pmu arm_spe_0]

---
 tools/testing/selftests/perf_events/Makefile  |   1 +
 .../selftests/perf_events/aux_kernel.sh       | 631 ++++++++++++++++++
 2 files changed, 632 insertions(+)
 create mode 100755 tools/testing/selftests/perf_events/aux_kernel.sh
tools/testing/selftests/perf_events/Makefile +1 -0
index fbafbd43f097..9b82c7ee1238 100644
@@ -4,4 +4,5 @@ LDFLAGS += -lpthread
 
 TEST_GEN_PROGS := sigtrap_threads remove_on_exec watermark_signal mmap
 TEST_GEN_PROGS += aux_kernel_usermode
+TEST_PROGS += aux_kernel.sh
 include ../lib.mk
tools/testing/selftests/perf_events/aux_kernel.sh new file +631 -0

631 lines not on this page · raw message

Signature · 1 line
2.43.0
#8 lore raw

Re: [PATCH 4/5] selftests/perf_events: add userspace AUX regression test

In reply to Kunwu Chan
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [Medium] selftests/perf_events: spurious failure on strict perf_event_paranoid - [Medium]…

Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [Medium] selftests/perf_events: spurious failure on strict perf_event_paranoid
- [Medium] selftests/perf_events: reading aux_head before disable causes spurious SKIP
- [Medium] selftests/perf_events: inconsistent PMU config rejection handling
- [Low] selftests/perf_events: missing -latomic causes 32-bit build failure --

commit d2d3116ff9e5d31817ce92f2b014df0cd0508f17
Author: Lian Wang <[email protected]>

selftests/perf_events: add userspace AUX regression test

This commit adds a C program to test the userspace AUX mmap protocol. It verifies that the perf event AUX setup handles configuration, memory mapping, and independent event buffers correctly without breaking user space.

tools/testing/selftests/perf_events/Makefile CFLAGS += -Wl,-no-as-needed -Wall $(KHDR_INCLUDES) · line 3

Quoted 6 lines
tools/testing/selftests/perf_events/Makefile +0 -0
index 2e5d85770dfea..fbafbd43f097e 100644
@@ -3,4 +3,5 @@ CFLAGS += -Wl,-no-as-needed -Wall $(KHDR_INCLUDES)
 LDFLAGS += -lpthread

[Severity: Low]
Since the tests in aux_kernel_usermode.c use 64-bit atomic operations on __u64 types, does the Makefile need the -latomic flag? Building on 32-bit architectures usually requires linking libatomic to avoid build failures on 64-bit atomic loads.

Quoted 4 lines
tools/testing/selftests/perf_events/Makefile +1 -0
 TEST_GEN_PROGS := sigtrap_threads remove_on_exec watermark_signal mmap
+TEST_GEN_PROGS += aux_kernel_usermode
 include ../lib.mk

[ ... ]

Quoted 6 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +0 -0
new file mode 100644
index 0000000000000..5c2da4bac0740
@@ -0,0 +1,627 @@

[ ... ]

Quoted 11 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +11 -0
+static int test_aux_mmap(int pmu_type)
+{
+	struct perf_event_attr attr = {};
+	struct perf_event_mmap_page *mp;
+	void *aux_base;
+	unsigned long aux_size, aux_offset, mmap_size;
+	int fd, ret;
+
+	attr.type = pmu_type;
+	attr.size = sizeof(attr);
+	attr.disabled = 1;

tools/testing/selftests/perf_events/aux_kernel_usermode.c line 163

Quoted 10 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +10 -0
+	attr.sample_period = 256;
+
+	/* ARM SPE requires period mode (freq=0) */
+	attr.freq = 0;
+
+	fd = perf_event_open(&attr, 0, -1, -1, 0);
+	if (fd < 0) {
+		FAIL("AUX mmap: perf_event_open failed (%s)", strerror(errno));
+		return 1;
+	}

[Severity: Medium]
Could this cause a false positive failure if the PMU legitimately rejects the zeroed configuration? Later in test_aux_head_monotonic, the same fd < 0 condition correctly uses SKIP to handle PMU rejection. Should this also skip rather than failing entirely on systems with strict AUX PMUs?

[ ... ]

Quoted 2 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +2 -0
+static int test_aux_head_monotonic(int pmu_type)
+{

[ ... ]

tools/testing/selftests/perf_events/aux_kernel_usermode.c line 546

Quoted 8 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +8 -0
+	/* Read initial head */
+	head_before = __atomic_load_n(&mp->aux_head, __ATOMIC_RELAXED);
+
+	usleep(100000); /* 100ms */
+
+	head_after = __atomic_load_n(&mp->aux_head, __ATOMIC_RELAXED);
+
+	ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);

[Severity: Medium]
Since head_after is read before the event is disabled, is there a chance the hardware trace data hasn't been flushed to the ring buffer yet? Hardware tracing PMUs typically only update the control page when explicitly disabled or during an interrupt, which could cause a spurious SKIP here. Would it be safer to disable the event before reading head_after?

[ ... ]

Quoted 2 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +2 -0
+int main(void)
+{

[ ... ]

tools/testing/selftests/perf_events/aux_kernel_usermode.c line 613

Quoted 12 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +12 -0
+	/* Test 6: Verify /proc/sys/kernel/perf_event_paranoid */
+	printf("\n--- 6. Perf Event Paranoid ---\n");
+	{
+		FILE *f = fopen("/proc/sys/kernel/perf_event_paranoid", "r");
+		int paranoid;
+
+		if (f) {
+			if (fscanf(f, "%d", &paranoid) == 1) {
+				printf("  perf_event_paranoid=%d\n", paranoid);
+				if (paranoid > 2)
+					FAIL("perf_event_paranoid=%d may block AUX",
+					     paranoid);

[Severity: Medium]
Since the selftest enforces root execution at the beginning of main, does this sysctl value actually restrict the test? A strict perf_event_paranoid value greater than 2 typically doesn't block root users. Could this logic incorrectly report a failure on systems with strict defaults?

Quoted 14 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +14 -0
+				else
+					PASS("perf_event_paranoid=%d (OK)", paranoid);
+			}
+			fclose(f);
+		} else {
+			printf("  [SKIP] Cannot read perf_event_paranoid\n");
+		}
+	}
+
+	printf("\n=== Result: %s ===\n", failed ? "FAIL" : "PASS");
+	if (skipped)
+		printf("=== Note: some tests were SKIPped (environment)\n");
+	return failed ? 1 : 0;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
#6 lore raw

Re: [PATCH 3/5] perf/core: add KUnit tests for AUX kernel-consumer API

In reply to Kunwu Chan
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] perf: double free of perf_event in aux_test_create_event() - [Medium] perf: memory leak of AUX…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] perf: double free of perf_event in aux_test_create_event()
- [Medium] perf: memory leak of AUX pages on KUnit assertion failure
--

commit 5c8a187a6ddc0c41bba18676f8fced4749f18392
Author: Lian Wang <[email protected]>

perf/core: add KUnit tests for AUX kernel-consumer API

This commit adds a KUnit test suite for the perf AUX kernel-consumer API. It registers a self-contained dummy AUX PMU and includes 39 test cases to cover the setup, release, and data copying lifecycle.

Quoted 4 lines
kernel/events/aux_kernel_test.c new file +0 -0
new file mode 100644

[ ... ]

Quoted 6 lines
kernel/events/aux_kernel_test.c new file +6 -0
+static struct perf_event *aux_test_create_event(struct kunit *test)
+{
+	struct perf_event_attr attr = {};
+	struct perf_event *event;
+
+	attr.type = dummy_aux_pmu_type;

kernel/events/aux_kernel_test.c line 152

Quoted 10 lines
kernel/events/aux_kernel_test.c new file +10 -0
+	attr.size = sizeof(attr);
+	attr.disabled = 1;
+
+	event = perf_event_create_kernel_counter(&attr, raw_smp_processor_id(),
+						 NULL, NULL, NULL);
+	if (IS_ERR(event))
+		return event;
+
+	if (kunit_add_action_or_reset(test, aux_test_event_release, event)) {
+		perf_event_release_kernel(event);

[Severity: Medium]
Will this cause a double free of the event object?

If kunit_add_action_or_reset() fails, it automatically executes the cleanup action, which in this case is aux_test_event_release(). That callback already invokes perf_event_release_kernel() on the event. Calling it a second time explicitly in this error path appears to trigger a double free.

Quoted 5 lines
kernel/events/aux_kernel_test.c new file +5 -0
+		return ERR_PTR(-ENOMEM);
+	}
+
+	return event;
+}

[ ... ]

Quoted 8 lines
kernel/events/aux_kernel_test.c new file +8 -0
+static void test_user_kernel_coexistence(struct kunit *test)
+{
+	struct perf_event *ev_a = aux_test_create_event(test);
+	struct perf_event *ev_b = aux_test_create_event(test);
+	struct perf_output_handle handle_a, handle_b;
+	unsigned long a_head_before, b_head_before;
+	void *addr;
+	int ret;

[ ... ]

kernel/events/aux_kernel_test.c line 999

Quoted 9 lines
kernel/events/aux_kernel_test.c new file +9 -0
+	/* Simulate userspace ownership: swap refcounts on B's rb.
+	 * perf_mmap() would set aux_mmap_count=1 for a userspace event.
+	 */
+	refcount_set(&ev_b->rb->aux_mmap_count, 1);
+	refcount_set(&ev_b->rb->aux_kernel_count, 0);
+
+	/* Produce on A — B's head stays 0 */
+	addr = perf_aux_output_begin(&handle_a, ev_a);
+	KUNIT_ASSERT_NOT_NULL(test, addr);

[Severity: Medium]
Does this leak the AUX pages if the assertion fails?

If this assertion or subsequent assertions fail while aux_kernel_count is set to 0, the test will immediately abort and skip the manual refcount restoration at the end of the function.

When KUnit runs the deferred cleanup action aux_test_event_release() on abort, perf_event_release_aux() observes that aux_kernel_count is 0 and returns early without tearing down the buffer, leaving the memory permanently leaked.

Quoted 1 line
kernel/events/aux_kernel_test.c new file +1 -0
+	perf_aux_output_end(&handle_a, 512);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
#4 lore raw

Re: [PATCH 2/5] perf/core: add AUX ring accessors for kernel consumers

In reply to Kunwu Chan
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] perf: misplaced smp_rmb() in perf_event_aux_tail_set() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] perf: misplaced smp_rmb() in perf_event_aux_tail_set()
--

commit bf06e748dd797d73b38eceb210cb85ac496712d0
Author: Kunwu Chan <[email protected]>

perf/core: add AUX ring accessors for kernel consumers

This commit adds kernel-consumer accessors for the published AUX producer head, the consumer tail, and copying a possibly wrapped AUX interval. It introduces these helpers to allow kernel consumers to own and drain the AUX buffer without relying on the overflow path.

Quoted 4 lines
kernel/events/ring_buffer.c +0 -0
index eae28e42346c7..2c6f260fcf91b 100644

[ ... ]

Quoted 12 lines
kernel/events/ring_buffer.c +12 -0
+int perf_event_aux_tail_set(struct perf_event *event, unsigned long tail)
+{
+	struct perf_buffer *rb = ring_buffer_get(event);
+	unsigned long advance, aux_size, head, old_tail;
+	int ret = -EINVAL;
+
+	if (!rb)
+		return -ENOENT;
+
+	if (!rb_has_kernel_aux(rb)) {
+		ret = -ENOENT;
+		goto out;

kernel/events/ring_buffer.c void *perf_get_aux(struct perf_output_handle *handle) · line 674

Quoted 10 lines
kernel/events/ring_buffer.c +10 -0
+	}
+
+	aux_size = (unsigned long)rb->aux_nr_pages << PAGE_SHIFT;
+	old_tail = READ_ONCE(rb->user_page->aux_tail);
+	/*
+	 * Pairs with the producer's AUX-data write barrier in
+	 * perf_aux_output_end() before it publishes aux_head.
+	 */
+	smp_rmb();
+	head = READ_ONCE(rb->user_page->aux_head);

[Severity: Low]
Is this smp_rmb() necessary here? Memory barriers order operations, they do not accelerate visibility. Since perf_event_aux_tail_set() performs no payload data reads, there is nothing for the smp_rmb() to order against the read of aux_head, rendering the barrier functionally inert.

The comment claims it pairs with the producer's AUX-data write barrier, but without trailing data reads, this pairing is meaningless. Does this result in unnecessary code complexity and a negligible performance overhead, while providing no structural safety risk since the subsequent smp_mb() correctly orders space release?

Quoted 14 lines
kernel/events/ring_buffer.c +14 -0
+	advance = tail - old_tail;
+
+	/* Modular distances keep the check valid when a cursor wraps. */
+	if (head - old_tail <= aux_size && advance <= head - old_tail) {
+		/* Order all prior AUX data reads before releasing the space. */
+		smp_mb();
+		WRITE_ONCE(rb->user_page->aux_tail, tail);
+		ret = 0;
+	}
+
+out:
+	ring_buffer_put(rb);
+	return ret;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
#10 lore raw

Re: [PATCH 5/5] selftests/perf_events: add AUX kernel API selftest script

In reply to Kunwu Chan
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider: - [Medium] selftests/perf_events: masked exit code of usermode binary - [Medium] selftests/perf_events…

Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
- [Medium] selftests/perf_events: masked exit code of usermode binary
- [Medium] selftests/perf_events: missed dmesg errors due to ring buffer wrap
- [Medium] selftests/perf_events: compilation failure due to quoted $CC
- [Medium] selftests/perf_events: hardcoded period breaks intel_pt PMU testing
- [Medium] selftests/perf_events: arbitrary fallback to /usr/src/linux breaks installed testing
- [Low] selftests/perf_events: pass() helper discards subsequent string arguments --

commit ae8124722ffc34fbe1b637d67fb27766b7c48d04
Author: Kunwu Chan <[email protected]>

selftests/perf_events: add AUX kernel API selftest script

Add a shell script that runs the perf_aux_kernel KUnit suite through debugfs, builds and runs the userspace regression program, and performs static-analysis checks on the source tree.

Quoted 8 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +2 -0
new file mode 100755
index 0000000000000..2271f105f55b7
@@ -0,0 +1,631 @@
+#!/bin/bash
+# SPDX-License-Identifier: GPL-2.0

[ ... ]

tools/testing/selftests/perf_events/aux_kernel.sh line 62

Quoted 13 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +13 -0
+ROOT="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel 2>/dev/null || true)"
+if [[ -z "$ROOT" ]]; then
+	ROOT="/usr/src/linux"
+fi
+
+# Source-level checks need the kernel tree; installed runs have none.
+SRC_EVENTS="$ROOT/kernel/events"
+if [[ -f "$SRC_EVENTS/core.c" ]]; then
+	HAVE_SRC=1
+else
+	HAVE_SRC=0
+	ROOT=""
+fi

[Severity: Medium]
Does falling back to /usr/src/linux in the main script logic break the skipping logic for installed selftests?

If the tests are run installed without a kernel tree, git rev-parse fails and ROOT becomes /usr/src/linux. If the system has host kernel headers installed there, HAVE_SRC evaluates to 1.

This causes the script to run static analysis against the mismatched host kernel, resulting in spurious test failures instead of gracefully skipping.

[ ... ]

tools/testing/selftests/perf_events/aux_kernel.sh line 277

Quoted 5 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +5 -0
+if [[ -x "$UMODE_BIN" && ( ! -f "$UMODE_SRC" || ! "$UMODE_SRC" -nt "$UMODE_BIN" ) ]]; then
+	:
+elif [[ -f "$UMODE_SRC" ]]; then
+	echo "  Building aux_kernel_usermode with ${CC}..."
+	if "$CC" -o "$UMODE_BIN" "$UMODE_SRC" -Wall -Wextra -O2; then

[Severity: Medium]
Will this compile command in the main script logic fail if the CC environment variable contains spaces?

By double-quoting "$CC", bash is prevented from performing word splitting.

If CC contains flags or prefixes like "ccache gcc" or "clang --target=...", bash attempts to execute a binary literally named with spaces and will fail with a command not found error.

tools/testing/selftests/perf_events/aux_kernel.sh line 289

Quoted 12 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +12 -0
+		:
+	else
+		echo "  $CC build failed"
+		UMODE_BIN=""
+	fi
+else
+	UMODE_BIN=""
+fi
+
+if [[ -n "$UMODE_BIN" && -x "$UMODE_BIN" ]]; then
+	if "$UMODE_BIN" "$PMU_NAME" 2>&1 | tee "$RESULTS_DIR/usermode.log" | \
+		grep -c '\[PASS\]' > /dev/null; then

[Severity: Medium]
Does this pipeline evaluate only the exit status of grep, swallowing the test binary's exit status?

Since the pipeline is evaluated without pipefail in the main script logic, if the test program emits at least one [PASS] before crashing, grep -c returns 0 and the if condition is satisfied.

Because UMODE_FAIL only counts explicit [FAIL] strings, crashes without explicit failure logs bypass the error checks.

tools/testing/selftests/perf_events/aux_kernel.sh line 295

Quoted 6 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +6 -0
+		# Count pass/fail from the output
+		UMODE_PASS=$(grep -c '\[PASS\]' "$RESULTS_DIR/usermode.log" || true)
+		UMODE_FAIL=$(grep -c '\[FAIL\]' "$RESULTS_DIR/usermode.log" || true)
+		UMODE_SKIP=$(grep -c '\[SKIP\]' "$RESULTS_DIR/usermode.log" || true)
+		pass "Userspace API regression: $UMODE_PASS passed," \
+			" $UMODE_FAIL failed, $UMODE_SKIP skipped"

[Severity: Low]
Because the pass() helper function only consumes $1, are the second and third string arguments dropped?

When invoked here with a multi-argument string, the pass() helper drops all arguments after the first. This truncates the test log output, losing the counts of failed and skipped tests.

[ ... ]

tools/testing/selftests/perf_events/aux_kernel.sh line 337

Quoted 4 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +4 -0
+		if [[ -n "$PERF_BIN" ]]; then
+			DMESG_BEFORE=$(dmesg 2>/dev/null | wc -l)
+			if "$PERF_BIN" record -e "$PMU_NAME/period=100000/" \
+				-o "$RESULTS_DIR/perf_hw.data" -- sleep 0.5 2>/dev/null; then

[Severity: Medium]
Could this hardcoded config term break compatibility with instruction tracing PMUs like intel_pt?

The script's usage advertises support for intel_pt. However, it hardcodes the /period=100000/ config term in the perf record command here in the main script logic.

Instruction tracing PMUs like Intel PT do not support sampling periods, causing the perf_event_open syscall to reject the configuration.

tools/testing/selftests/perf_events/aux_kernel.sh line 347

Quoted 10 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +10 -0
+				pass "Hardware AUX: perf record with $PMU_NAME succeeded"
+			else
+				fail "Hardware AUX: perf record with $PMU_NAME failed"
+			fi
+
+			DMESG_AFTER="$RESULTS_DIR/dmesg-hardware.log"
+			dmesg 2>/dev/null > "$DMESG_AFTER" || true
+			DMESG_LINES_AFTER=$(wc -l < "$DMESG_AFTER")
+			if [[ "$DMESG_LINES_AFTER" -ge "$DMESG_BEFORE" ]]; then
+				NEW_DMESG=$(tail -n "+$((DMESG_BEFORE + 1))" "$DMESG_AFTER")

[Severity: Medium]
Does this logic fail when the kernel log buffer wraps around and maintains a constant maximum line count?

dmesg outputs the contents of a circular buffer. If the buffer is full, DMESG_LINES_AFTER will equal DMESG_BEFORE (or be very close).

When DMESG_LINES_AFTER >= DMESG_BEFORE, the script uses
tail -n "+$((DMESG_BEFORE + 1))". If the line count hasn't increased because the buffer reached max capacity and wrapped, this command attempts to read past the end of the buffer, yielding zero lines and missing all new kernel messages.

Quoted 3 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +3 -0
+			else
+				NEW_DMESG=$(cat "$DMESG_AFTER")
+			fi
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
#2 lore raw

Re: [PATCH 1/5] perf/core: add AUX buffer ownership for kernel events

In reply to Kunwu Chan
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 23 lines

Add an in-kernel AUX owner reference and setup/release helpers for kernel-created perf events that need an AUX buffer without a userspace mmap. The setup path validates that the event is a kernel event with no parent, rejects non-power-of-two page counts and negative watermark values, allocates the perf buffer and AUX pages, records the kernel owner, and attaches the buffer under the same lock.

perf_event_release_aux() stops AUX writers, frees AUX storage, and detaches the buffer, in that order, matching the AUX teardown ordering of perf_mmap_close(): perf_pmu_output_stop() walks event->rb->event_list and rb_free_aux() must run while the buffer is still referenced by the event. The single event->rb reference is dropped by ring_buffer_attach(event, NULL) itself, so the release path does not put it again.

Both functions run under event->mmap_mutex, the lock that already serialises ring-buffer attach/detach transitions for an event:
perf_mmap(), perf_mmap_close(), _perf_event_set_output() and _free_event() all hold it around ring_buffer_attach(). Concurrent perf_event_release_aux() callers therefore go through the same serialisation point, and a second release call, or a release of a buffer this API does not own, is a no-op.

Quoted 7 lines

Keep aux_mmap_count dedicated to userspace mappings. perf_aux_output_begin() accepts a writer while either a userspace or kernel owner remains, preserving the existing teardown ordering.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1