perf/core: add AUX buffer kernel-consumer API
Subsystems (4)
v2 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 drain the AUX buffer directly.
Userspace allocates AUX buffers through perf_event_open() and mmap(). Kernel consumers created through perf_event_create_kernel_counter() currently lack an equivalent interface.
This series adds perf-core APIs for kernel consumers to allocate and release AUX buffers, read the producer head, copy trace data, and advance the consumer tail. The APIs keep perf's internal page layout private and follow the existing non-overwrite AUX ring-buffer protocol. Setup and release serialize buffer attachment and detachment through event->mmap_mutex; consumers must quiesce before releasing the buffer.
Patches 1-2 add the ownership, lifecycle, and access APIs. Patches 3-5 add KUnit tests, a userspace AUX 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.
Testing
=======
The series builds cleanly at each step.
arm64 (Kunpeng 920, 256 CPUs, SPEv1.1): built and booted the Image from this series. KUnit: pass:39 fail:0 skip:0. The arm_spe_0 userspace regression test passed, and the AUX head advanced under live SPE traffic. Selftest script: 92 passed, 0 failed, 2 skipped. perf record with arm_spe_0 captured data; dmesg showed no warnings.
x86_64 (vmlinux build, qemu/kvm): KUnit pass:39 fail:0 skip:0, including KASAN and lockdep (PROVE_LOCKING); 15 repeated boots produced no splats. The Intel PT userspace regression test passed.
Changes since v1 [2]:
- Fix double-release in KUnit error cleanup and make the coexistence test cleanup failure-safe.
- Make failure-sensitive userspace test outcomes report SKIP rather than PASS, read the AUX head after event disable to observe flushed trace data, and pass the PMU name from the script to the C test.
- Fix the selftest script exit-status handling, remove the /usr/src/linux fallback, and handle Intel PT event modifiers.
- Remove an unnecessary smp_rmb() from the tail update path.
Changes since RFC [1]:
- Serialize AUX teardown under event->mmap_mutex and fix lifetime handling around ring_buffer_attach().
- Improve KUnit cleanup and concurrent-release coverage.
- Extend userspace and selftest coverage.
- Document AUX lifecycle, ordering, and cursor validation.
[1] https://lore.kernel.org/linux-perf-users/[email protected]/
[2] https://lore.kernel.org/all/[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 | 1172 +++++++++++++++++ kernel/events/core.c | 164 +++ kernel/events/internal.h | 6 + kernel/events/ring_buffer.c | 212 ++- lib/Kconfig.debug | 14 + tools/testing/selftests/perf_events/Makefile | 2 + .../selftests/perf_events/aux_kernel.sh | 635 +++++++++ .../perf_events/aux_kernel_usermode.c | 645 +++++++++ tools/testing/selftests/perf_events/config | 2 + 12 files changed, 2928 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
PATCH v2 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
@@ -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
@@ -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
@@ -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
[email protected]
AI reviewRe: [PATCH v2 1/5] perf/core: add AUX buffer ownership for kernel events
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 ofperf_mmap_close():perf_pmu_output_stop()walksevent->rb->event_listandrb_free_aux()must run while the buffer is still referenced by the event. The singleevent->rbreference is dropped byring_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 aroundring_buffer_attach(). Concurrentperf_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_countdedicated to userspace mappings.perf_aux_output_begin()accepts a writer while either a userspace or kernel owner remains, preserving the existing teardown ordering.Co-developed-by Lian Wang (Processmission) <[email protected]>Signed-off-by Lian Wang (Processmission) <[email protected]>Signed-off-by Kunwu Chan <[email protected]>
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
Peter Zijlstra
maintainerRe: [PATCH v2 1/5] perf/core: add AUX buffer ownership for kernel events
In reply to Kunwu ChanQuoted 35 lines · Kunwu Chan
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 ofperf_mmap_close():perf_pmu_output_stop()walksevent->rb->event_listandrb_free_aux()must run while the buffer is still referenced by the event. The singleevent->rbreference is dropped byring_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 aroundring_buffer_attach(). Concurrentperf_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_countdedicated to userspace mappings.perf_aux_output_begin()accepts a writer while either a userspace or kernel owner remains, preserving the existing teardown ordering.kernel/events/internal.h +0
-0@@ -48,6 +48,12 @@ struct perf_buffer {int aux_nr_pages;int aux_overwrite;
kernel/events/internal.h struct perf_buffer { · line 59
Quoted 10 lines
kernel/events/internal.h +6
-0refcount_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;
This doesn't make sense to me. If the even is a kernel event, then there cannot be mmap users, so adding another refcount is just for giggles?
Re: [PATCH v2 1/5] perf/core: add AUX buffer ownership for kernel events
Quoted 42 lines · Peter Zijlstra
Quoted 40 lines · Kunwu Chan
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 ofperf_mmap_close():perf_pmu_output_stop()walksevent->rb->event_listandrb_free_aux()must run while the buffer is still referenced by the event. The singleevent->rbreference is dropped byring_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 aroundring_buffer_attach(). Concurrentperf_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_countdedicated to userspace mappings.perf_aux_output_begin()accepts a writer while either a userspace or kernel owner remains, preserving the existing teardown ordering.kernel/events/internal.h +4
-0@@ -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.
Quoted 8 lines
kernel/events/internal.h struct perf_buffer { · line 59
Quoted 5 lines
kernel/events/internal.h +2
-0+*/ +refcount_t aux_kernel_count;unsigned long aux_mmap_locked;void (*free_aux)(void *);refcount_t aux_refcount;This doesn't make sense to me. If the even is a kernel event, then there cannot be mmap users, so adding another refcount is just for giggles?
Hi Peter,
I added aux_kernel_count to keep aux_mmap_count specific to userspace mappings. The two paths have different teardown responsibilities: perf_mmap_close() handles mmap cleanup, while perf_event_release_aux() stops AUX output, frees the AUX pages and detaches the buffer for a kernel consumer.
perf_aux_output_begin() checks both counts so writers are admitted while either owner remains.
Would you suggest a simpler approach here?
Thanks,
Kunwu
Re: [PATCH v2 1/5] perf/core: add AUX buffer ownership for kernel events
Quoted 62 lines · KunWu Chan
Quoted 42 lines · Peter Zijlstra
Quoted 40 lines · Kunwu Chan
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 ofperf_mmap_close():perf_pmu_output_stop()walksevent->rb->event_listandrb_free_aux()must run while the buffer is still referenced by the event. The singleevent->rbreference is dropped byring_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 aroundring_buffer_attach(). Concurrentperf_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_countdedicated to userspace mappings.perf_aux_output_begin()accepts a writer while either a userspace or kernel owner remains, preserving the existing teardown ordering.kernel/events/internal.h +4
-0@@ -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. Quoted 8 lines
kernel/events/internal.h struct perf_buffer { · line 59
Quoted 5 lines
kernel/events/internal.h +2
-0+*/ +refcount_t aux_kernel_count;unsigned long aux_mmap_locked;void (*free_aux)(void *);refcount_t aux_refcount;This doesn't make sense to me. If the even is a kernel event, then there cannot be mmap users, so adding another refcount is just for giggles?
Hi Peter,
I added
aux_kernel_countto keepaux_mmap_countspecific to userspace mappings. The two paths have different teardown responsibilities:perf_mmap_close()handles mmap cleanup, whileperf_event_release_aux()stops AUX output, frees the AUX pages and detaches the buffer for a kernel consumer.
Quoted 7 lines
perf_aux_output_begin()checks both counts so writers are admitted while either owner remains.Would you suggest a simpler approach here?
Thanks,
Kunwu
Gentle ping.
On your aux_kernel_count question: the separate count is for teardown, not admission control.
When aux_mmap_count reaches zero, perf_mmap_close() subtracts from mmap_user->locked_vm and vma->vm_mm->pinned_vm before calling rb_free_aux().
A kernel owner has neither of these accounting requirements.
Reusing the count would therefore require either branching in perf_mmap_close() on owner type, or duplicating the teardown in release_aux().
Keeping separate counts lets each side handle its
own teardown without needing to know about the other.
If you'd prefer a single count with teardown selected by owner type, I'm happy to rework it.
Thanks,
Kunwu
PATCH v2 2/5 perf/core: add AUX ring accessors for kernel consumers
In reply to Kunwu ChanAdd 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 | 203 +++++++++++++++++- 3 files changed, 270 insertions(+), 2 deletions(-)
Documentation/userspace-api/perf_ring_buffer.rst +61 -1
@@ -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
@@ -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 +202 -1
215 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v2 2/5] perf/core: add AUX ring accessors for kernel consumers
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 11 lines
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 withsmp_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.
Quoted 8 lines
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.Co-developed-by Lian Wang (Processmission) <[email protected]>Signed-off-by Lian Wang (Processmission) <[email protected]>Signed-off-by Kunwu Chan <[email protected]>
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=2
PATCH v2 3/5 perf/core: add KUnit tests for AUX kernel-consumer API
In reply to Kunwu ChanFrom: 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 | 1172 +++++++++++++++++++++++++++++++ lib/Kconfig.debug | 14 + 3 files changed, 1187 insertions(+) create mode 100644 kernel/events/aux_kernel_test.c
kernel/events/Makefile +1 -0
@@ -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 +1172 -0
1,172 lines not on this page · raw message
lib/Kconfig.debug +14 -0
@@ -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
[email protected]
AI reviewRe: [PATCH v2 3/5] perf/core: add KUnit tests for AUX kernel-consumer API
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 18 lines
From: Lian Wang <[email protected]>
Add a KUnit test suite (
perf_aux_kernel) for theperf_event_setup_aux(),perf_event_release_aux(),perf_event_aux_head(),perf_event_aux_tail_set()andperf_event_aux_copy()functions.A self-contained dummy AUX PMU is registered in
suite_initso that every test is deterministic and needs no hardware. The dummysetup_auxpre-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 [ ... ]
Gated byCONFIG_PERF_AUX_KERNEL_KUNIT_TEST.
Quoted 3 lines
Co-developed-by Kunwu Chan <[email protected]>Signed-off-by Kunwu Chan <[email protected]>Signed-off-by Lian Wang <[email protected]>
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=3
PATCH v2 4/5 selftests/perf_events: add userspace AUX regression test
In reply to Kunwu ChanFrom: 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 | 645 ++++++++++++++++++ tools/testing/selftests/perf_events/config | 2 + 3 files changed, 648 insertions(+) create mode 100644 tools/testing/selftests/perf_events/aux_kernel_usermode.c
tools/testing/selftests/perf_events/Makefile +1 -0
@@ -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 +645 -0
645 lines not on this page · raw message
tools/testing/selftests/perf_events/config +2 -0
@@ -1 +1,3 @@ CONFIG_PERF_EVENTS=y +CONFIG_PERF_AUX_KERNEL_KUNIT_TEST=y +CONFIG_KUNIT_DEBUGFS=y
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v2 4/5] selftests/perf_events: add userspace AUX regression test
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] selftests/perf_events: truncation of 64-bit aux_head to 32-bit unsigned long and missing…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] selftests/perf_events: truncation of 64-bit aux_head to 32-bit unsigned long and missing -latomic
- [Low] selftests/perf_events: manual printf bypasses SKIP() macro and corrupts skipped test accounting --
commit 82dfe095e07a5fe7f9ac97c522ea08913124277f
Author: Lian Wang <[email protected]>
selftests/perf_events: add userspace AUX regression test
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.
Quoted 5 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +0
-0
[ ... ]
tools/testing/selftests/perf_events/aux_kernel_usermode.c line 226
Quoted 10 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +10
-0+/* +* Step 3: mmap the AUX area at aux_offset. +* The kernel reads aux_offset from the metadata page, verifies +* the mmap offset matches, and allocates the AUX buffer. +*/ + aux_base =mmap (NULL , aux_size,PROT_READ ,MAP_SHARED , fd, + aux_offset); +if (aux_base ==MAP_FAILED ) { +printf (" [SKIP] AUX mmap: AUX area mmap failed (%s)\n" , +strerror (errno));
[Severity: Low]
Is this manual printf() bypassing the SKIP() macro?
The test suite relies on the SKIP() macro to update the global skipped flag. By using printf() directly here in test_aux_mmap(), the flag isn't updated and the final note "=== Note: some tests were SKIPped (environment)" might be incorrectly omitted if this is the only skipped test.
Quoted 5 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +5
-0+munmap (mp, mmap_size); +close (fd); +return 0 ; + } +PASS ("AUX mmap: metadata mmap OK, AUX area mmap OK" );
[ ... ]
tools/testing/selftests/perf_events/aux_kernel_usermode.c line 526
Quoted 5 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +5
-0+static int test_aux_head_monotonic (int pmu_type) +{ +struct perf_event_attr attr = {}; +struct perf_event_mmap_page *mp; +unsigned long aux_size, mmap_size, head_before, head_after;
[Severity: Medium]
Will this truncate the 64-bit hardware trace cursors on 32-bit architectures?
The aux_head field in struct perf_event_mmap_page is defined as a 64-bit __u64. Since head_before and head_after are declared as unsigned long, they will be 32-bit on 32-bit architectures, causing the upper 32 bits to be silently discarded when reading aux_head.
Quoted 2 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +2
-0+void *aux_base; +int fd, ret;
[ ... ]
tools/testing/selftests/perf_events/aux_kernel_usermode.c line 569
Quoted 2 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +2
-0+/* Read initial head */ + head_before =__atomic_load_n (&mp->aux_head, __ATOMIC_RELAXED);
[Severity: Medium]
Can this atomic load of a 64-bit value cause a build failure on 32-bit architectures?
Using __atomic_load_n() on a 64-bit integer on 32-bit platforms often requires linking against libatomic. The Makefile modifications in this patch do not add -latomic to LDFLAGS, which might lead to link failures on those architectures.
Quoted 2 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +2
-0+ +usleep (100000 );/* 100ms */
[ ... ]
tools/testing/selftests/perf_events/aux_kernel_usermode.c line 622
Quoted 8 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +8
-0+/* Find an AUX-capable PMU: explicit name from argv, or auto-detect. */ +if (argc >1 ) + pmu_type =find_aux_pmu_type_by_name (argv[1 ]); +else + pmu_type =find_aux_pmu_type (); +if (pmu_type <0 ) { +printf ("--- 2-5. AUX Tests ---\n" ); +printf (" [SKIP] No AUX-capable PMU found\n" );
[Severity: Low]
Does this manual printf() also bypass the SKIP() macro?
Similar to the issue in test_aux_mmap(), bypassing the SKIP() macro here in main() prevents the skipped flag from being updated, which corrupts the skipped test accounting at the end of the run.
Quoted 3 lines
tools/testing/selftests/perf_events/aux_kernel_usermode.c new file +3
-0+ }else { +/* Test 2: AUX mmap lifecycle */ +printf ("\n--- 2. AUX Mmap Lifecycle ---\n" );
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
PATCH v2 5/5 selftests/perf_events: add AUX kernel API selftest script
In reply to Kunwu ChanAdd 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. Results go to a mktemp(1)-created directory rather than a predictable PID-suffixed path
(a symlink-overwrite hazard when run as root).
Usage: sudo ./aux_kernel.sh [--pmu arm_spe_0]
--- tools/testing/selftests/perf_events/Makefile | 1 + .../selftests/perf_events/aux_kernel.sh | 635 ++++++++++++++++++ 2 files changed, 636 insertions(+) create mode 100755 tools/testing/selftests/perf_events/aux_kernel.sh
tools/testing/selftests/perf_events/Makefile +1 -0
@@ -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 +635 -0
635 lines not on this page · raw message
Signature · 1 line
2.43.0
[email protected]
AI reviewRe: [PATCH v2 5/5] selftests/perf_events: add AUX kernel API selftest script
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider: - [Medium] selftests: bash syntax error due to missing line continuation - [Medium] selftests: manual C…
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
- [Medium] selftests: bash syntax error due to missing line continuation
- [Medium] selftests: manual C compiler invocation bypasses Makefile and CFLAGS
- [Low] selftests: incorrect translation of KSFT_SKIP exit code to failure
- [Low] selftests: git dependency for source tree path resolution fails in tarballs
- [Low] selftests: untracked TEST_GEN_PROGS binary missing from .gitignore
- [Low] selftests: brittle source code grep tests create maintenance burden --
commit b62175593d8e1e9cdad05106f3f506af47e718eb
Author: Kunwu Chan <[email protected]>
selftests/perf_events: add AUX kernel API selftest script
This commit adds a shell script to run the perf_aux_kernel KUnit suite, userspace regression program, hardware tests, and static checks. It is designed to work both in-tree and from an installed selftest location, with results written to a temporary directory.
tools/testing/selftests/perf_events/Makefile LDFLAGS += -lpthread · line 6
Quoted 8 lines
tools/testing/selftests/perf_events/Makefile +0
-0@@ -4,4 +4,5 @@ LDFLAGS += -lpthread TEST_GEN_PROGS := sigtrap_threads remove_on_exec watermark_signal mmap TEST_GEN_PROGS += aux_kernel_usermode
[Severity: Low]
Is aux_kernel_usermode missing from tools/testing/selftests/perf_events/.gitignore?
Building the selftests will leave this untracked binary in the working tree, polluting the repository status.
Quoted 2 lines
tools/testing/selftests/perf_events/Makefile +1
-0+TEST_PROGS += aux_kernel.sh include ../lib.mk
[ ... ]
Quoted 5 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +0
-0
[ ... ]
tools/testing/selftests/perf_events/aux_kernel.sh line 50
Quoted 2 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +2
-0+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel 2>/dev/null || true)"
[Severity: Low]
Will this git dependency fail when executed from a release tarball?
When testing from a kernel source tarball, the .git directory is absent and the git rev-parse command will fail. This causes $ROOT to be empty, silently skipping the source-level analysis despite the full source tree being available. Traversing parent directories via relative paths is a more robust approach.
[ ... ]
tools/testing/selftests/perf_events/aux_kernel.sh line 272
Quoted 2 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +2
-0+ echo " Building aux_kernel_usermode with ${CC}..." + if "$CC" -o "$UMODE_BIN" "$UMODE_SRC" -Wall -Wextra -O2; then
[Severity: Medium]
Does this manual compilation bypass the kselftest build infrastructure?
By avoiding make, variables such as cross-compilation CFLAGS, KHDR_INCLUDES, and LDFLAGS are discarded. For instance, LDFLAGS += -lpthread is explicitly set in the subsystem Makefile but is omitted here. Test dependencies should rely entirely on the TEST_GEN_PROGS infrastructure.
[ ... ]
tools/testing/selftests/perf_events/aux_kernel.sh line 291
Quoted 2 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +2
-0+ if [[ "$UMODE_RET" -ne 0 ]]; then + fail "Userspace API regression: C program failed"
[Severity: Low]
Does this check treat standard test skips as fatal failures?
In the kselftest framework, a test program returns 4 (KSFT_SKIP) when prerequisites are unmet (such as missing permissions or unsupported features). Evaluating any non-zero exit code as a failure improperly fails the overall test suite. Should this explicitly check for exit code 4 and translate it into a skip?
tools/testing/selftests/perf_events/aux_kernel.sh line 294
Quoted 3 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +3
-0+ else + pass "Userspace API regression: $UMODE_PASS passed, $UMODE_FAIL failed," + " $UMODE_SKIP skipped"
[Severity: Medium]
Is there a missing line continuation backslash here?
Because set -e is active at the top of the script, bash parses the second line (" $UMODE_SKIP skipped") as an independent command, causing a fatal command not found error. This immediately terminates the test script, preventing subsequent hardware AUX tests, DAMON checks, and the final summary from executing.
[ ... ]
tools/testing/selftests/perf_events/aux_kernel.sh line 407
Quoted 11 lines
tools/testing/selftests/perf_events/aux_kernel.sh new file +11
-0+# ---- Section 6: Memory ordering and concurrency checks ---- +echo "" +echo "--- 6. Memory Ordering & Concurrency ---" + +if [[ "$HAVE_SRC" -ne 1 ]]; then + skip "Memory ordering checks" "kernel source not available (installed run)" +else + +# Verify smp_rmb() in perf_event_aux_head() +if grep -q 'smp_rmb' "$SRC_EVENTS/ring_buffer.c" 2>/dev/null; then + pass "perf_event_aux_head(): smp_rmb() barrier present"
[Severity: Low]
Do these brittle source code grep tests create a maintenance burden?
This tightly couples the selftest to an exact textual representation rather than verifying behavioral API contracts. Routine kernel refactoring (such as renaming variables, extracting logic to helpers, or changing barrier primitives) will falsely fail these tests. Source-level constraints should be enforced by static analysis tools (like sparse or smatch) rather than regex matches in the selftest pipeline.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5