Skip to contentSkip to conversation

perf bpf-filter / lock contention: Add lock_held() sample filter and RCU/SRCU support

PATCH Superseded Ian Rogers 4 participants 129 messages Oct 17 – Oct 23 Page 2 of 2

Subsystems (2)
lore
Share & tools
lore
#75 lore raw

Re: [PATCH v5 7/8] perf bpf-filter: Extend lock_held() to support RCU, Tasks Trace RCU, and SRCU

In reply to Ian Rogers
Sashiko has reviewed this patch and found no issues.
Quoted 17 lines

Extend the lock_held(<lock>) BPF sample filter to support RCU, Tasks Trace RCU, and SRCU locks:

- 'rcu' (supports both read/shared and write/exclusive modes):
- Read/shared ('lock_held_read(rcu)', 'lock_held(rcu:R)', 'lock_held(rcu_read_lock)'): directly inspects current->rcu_read_lock_nesting in perf_sample_filter via CO-RE (on CONFIG_PREEMPT_RCU kernels), accounting for the baseline rcu_read_lock() nesting acquired by the perf overflow handler itself (bpf_overflow_handler() and do_perf_sw_event()) with zero extra fentry/fexit tracing hooks.
- Write/exclusive ('lock_held_write(rcu)', 'lock_held(rcu:W)'):
attaches fentry/fexit hooks to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), and rcu_barrier() to track grace-period and barrier waits.
[ ... ]

Quoted 4 lines
  # perf record -a -g -e task-clock --filter 'lock_held(rcu:W)' -- sleep 1
  # perf record -a -g -e cycles --filter 'lock_held(srcu)' -- sleep 1

Sashiko has reviewed this patch and found no issues.

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

PATCH v5 8/8 perf lock contention: Extend BPF lock contention to RCU and SRCU

In reply to Ian Rogers

Extend 'perf lock contention --use-bpf' to track RCU and SRCU grace-period and barrier waits:

- Attach fentry/fexit programs to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), rcu_barrier(), synchronize_srcu(), synchronize_srcu_expedited(), and srcu_barrier() when available in BTF.
- Support filtering by lock type ('-Y rcu', '-Y rcu:W', '-Y srcu', '-Y srcu:W') and by lock name ('-L rcu' or specific srcu_struct symbol names).

Example usage:

  # perf lock con -a -b -Y rcu,srcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait         type   caller
       35.12 ms      8.78 ms        rcu:W   cleanup_net+0x284
        7.84 ms      3.92 ms       srcu:W   __fsnotify_parent+0x114
  # perf lock con -a -b -l -L rcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait            address   symbol
       35.12 ms      8.78 ms   ffffffff83754dc0   rcu (rcu)
---
 tools/perf/Documentation/perf-lock.txt        |   7 +-
 tools/perf/tests/shell/lock_contention.sh     |  14 ++
 tools/perf/util/bpf_lock_contention.c         | 171 ++++++++++++--
 .../perf/util/bpf_skel/lock_contention.bpf.c  | 221 ++++++++++++++----
 tools/perf/util/machine.c                     |  11 +
 5 files changed, 362 insertions(+), 62 deletions(-)
tools/perf/Documentation/perf-lock.txt +5 -2
index c17b3e318169..bfeb98c976e3 100644
@@ -188,11 +188,14 @@ CONTENTION OPTIONS
 	Show lock contention only for given lock types (comma separated list).
 	Available values are:
 	  semaphore, spinlock, rwlock, rwlock:R, rwlock:W, rwsem, rwsem:R, rwsem:W,
-	  rtmutex, rwlock-rt, rwlock-rt:R, rwlock-rt:W, percpu-rwmem, pcpu-sem,
-	  pcpu-sem:R, pcpu-sem:W, mutex
+	  rtmutex, rwlock-rt, rwlock-rt:R, rwlock-rt:W, percpu-rwsem, pcpu-sem,
+	  pcpu-sem:R, pcpu-sem:W, mutex, srcu, srcu:W, rcu, rcu:W
 
 	Note that RW-variant of locks have :R and :W suffix.  Names without the
 	suffix are shortcuts for the both variants.  Ex) rwsem = rwsem:R + rwsem:W.
+	For RCU and SRCU with --use-bpf, contention tracks grace-period and
+	barrier waits (synchronize_rcu*(), synchronize_srcu*(), rcu_barrier(),
+	srcu_barrier()).
 
 -L::
 --lock-filter=<value>::
tools/perf/tests/shell/lock_contention.sh +14 -0
index 5df9a0cd48a3..999dcfd1ef26 100755
@@ -181,6 +181,13 @@ test_type_filter()
 		err=1
 		exit
 	fi
+
+	perf lock con -a -b -Y rcu -q -- true > /dev/null 2> ${result}
+	if [ "$(grep -c -v -w rcu "${result}")" != "0" ]; then
+		echo "[Fail] BPF result should not have non-rcu locks:" "$(cat "${result}")"
+		err=1
+		exit
+	fi
 }
 
 test_lock_filter()
@@ -224,6 +231,13 @@ test_lock_filter()
 		err=1
 		exit
 	fi
+
+	perf lock con -a -b -L rcu -q -- true > /dev/null 2> ${result}
+	if [ "$(grep -c -v -w rcu "${result}")" != "0" ]; then
+		echo "[Fail] BPF result should not have non-rcu locks:" "$(cat "${result}")"
+		err=1
+		exit
+	fi
 }
 
 test_stack_filter()
tools/perf/util/bpf_lock_contention.c +158 -13

236 lines not on this page · raw message

tools/perf/util/bpf_skel/lock_contention.bpf.c +174 -47

360 lines not on this page · raw message

tools/perf/util/machine.c +11 -0
index 1d9d3bf57720..0a0f223b3335 100644
@@ -3379,6 +3379,17 @@ bool machine__is_lock_function(struct machine *machine, u64 addr)
 			return true;
 	}
 
+	{
+		struct symbol *sym = machine__find_kernel_symbol(machine, addr, NULL);
+
+		if (sym && (!strncmp(sym->name, "synchronize_rcu", 15) ||
+			    !strncmp(sym->name, "synchronize_srcu", 16) ||
+			    !strcmp(sym->name, "__synchronize_srcu") ||
+			    !strcmp(sym->name, "rcu_barrier") ||
+			    !strcmp(sym->name, "srcu_barrier")))
+			return true;
+	}
+
 	return false;
 }
 
Signature · 1 line
2.56.0.212.g129ede20d9-goog
#77 lore raw

Re: [PATCH v5 8/8] perf lock contention: Extend BPF lock contention to RCU and SRCU

Sashiko has reviewed this patch and found no issues.
Quoted 19 lines

Extend 'perf lock contention --use-bpf' to track RCU and SRCU grace-period and barrier waits:

- Attach fentry/fexit programs to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), rcu_barrier(), synchronize_srcu(), synchronize_srcu_expedited(), and srcu_barrier() when available in BTF.
- Support filtering by lock type ('-Y rcu', '-Y rcu:W', '-Y srcu', '-Y srcu:W') and by lock name ('-L rcu' or specific srcu_struct symbol names).

Example usage:

  # perf lock con -a -b -Y rcu,srcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait         type   caller
       35.12 ms      8.78 ms        rcu:W   cleanup_net+0x284
        7.84 ms      3.92 ms       srcu:W   __fsnotify_parent+0x114
Quoted 6 lines
  # perf lock con -a -b -l -L rcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait            address   symbol
       35.12 ms      8.78 ms   ffffffff83754dc0   rcu (rcu)

Sashiko has reviewed this patch and found no issues.

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

v6 cover perf bpf-filter / lock contention: Add lock_held() sample filter and RCU/SRCU support

In reply to Ian Rogers

This series adds a new BPF sample filter predicate, lock_held(<lock>) (along with lock_held_read(<lock>) / lock_held_shared(<lock>), lock_held_write(<lock>) / lock_held_exclusive(<lock>), and :R / :W mode suffixes), to perf record --filter, allowing perf event samples to be recorded only when a specified kernel lock is held (or not held with !) by the running kernel thread or CPU. It also fixes a bpf_link memory leak in perf_bpf_filter__prepare(), enables BPF sample filters on tracepoint events (PERF_TYPE_TRACEPOINT), and extends both lock_held() and perf lock contention --use-bpf to support RCU and SRCU.

For example:

  # perf record -a -g -e cycles --filter 'lock_held(cgroup_mutex)' -- ...
  # perf record -a -g -e cycles --filter 'lock_held_read(mmap_lock)' -- ...
  # perf record -a -g -e cycles --filter 'lock_held(mmap_lock:W)' -- ...
  # perf record -a -g -e cycles --filter 'lock_held_read(rcu)' -- ...
  # perf lock contention -a -b -Y rcu,srcu -- sleep 1

An important use-case is detecting memory allocations or direct memory reclaim occurring while kernel locks are held, which can stall lock waiters for extended periods under memory pressure:

# Direct memory reclaim triggered while holding any mutex or rwsem:

  # perf record -a -g -e vmscan:mm_vmscan_direct_reclaim_begin \
      --filter 'lock_held(mutex) || lock_held(rwsem)' -- ...

# Page allocations permitted to enter direct reclaim (__GFP_DIRECT_RECLAIM)

  # while holding a mutex or rwsem:
  # perf record -a -g -e kmem:mm_page_alloc \
      --filter 'gfp_flags & 0x400' \
      --filter 'lock_held(mutex) || lock_held(rwsem)' -- ...

# Major page faults occurring while holding a mutex or rwsem:

  # perf record -a -g -e major-faults \
      --filter 'lock_held(mutex) || lock_held(rwsem)' -- ...

Supported <lock> specifications match perf lock contention:
- Global/static kernel lock symbols (e.g. lock_held(cgroup_mutex))
- Hexadecimal kernel lock addresses
- Slab cache names prefixed with & (e.g. lock_held(&dentry), lock_held_read(&dentry))
- Well-known per-process, semi-global, and RCU locks: mmap_lock, siglock, rq_lock, zone_lock, rcu, rcu-trace
- Lock types and flags: mutex, spinlock, rwsem, rwsem:R, rwsem:W, rwlock, rwlock:R, rwlock:W, rt-mutex, percpu-rwsem, pcpu-sem:W, srcu, srcu:R, srcu:W, rcu:R, rcu:W, semaphore

Limitations and weaknesses in determining whether a lock is held:
- Inlined lock/unlock operations:
- When the kernel is configured to inline spinlock or rwlock operations (CONFIG_INLINE_SPIN_LOCK, CONFIG_INLINE_READ_LOCK, CONFIG_INLINE_WRITE_LOCK, !CONFIG_UNINLINE_SPIN_UNLOCK, CONFIG_INLINE_*_UNLOCK*, etc.), _raw_spin_lock* / _raw_spin_unlock* and _raw_read_lock* / _raw_write_lock* are inlined into callers and have no BTF function entry points for fentry/fexit to attach to. configure_lock_progs() verifies that both acquire and release entry points exist in BTF before enabling a lock family.
- Fast-path percpu_down_read() / percpu_up_read() and srcu_read_lock_fast() / srcu_read_unlock_fast() are inlined per-CPU counter increments without function calls, so only percpu_down_write() / percpu_up_write() and out-of-line __srcu_read_lock*() / __srcu_read_unlock*() can be hooked.
- On !CONFIG_PREEMPT_RCU kernels, rcu_read_lock() compiles to preempt_disable() and does not maintain current->rcu_read_lock_nesting in task_struct, so lock_held(rcu) read-side inspection requires CONFIG_PREEMPT_RCU.
- Lack of an inspectable owner field on non-exclusive / spinning locks:
- While struct mutex, struct rt_mutex, and write-locked struct rw_semaphore store the owning task_struct * in lock->owner (allowing perf_sample_filter to inspect kernel memory directly on sample overflow when filtering by lock address without attaching any fentry/fexit hooks for *_mutex, *_rt_mutex, and mmap_lock:W), spinlocks, rwlocks, semaphores, SRCU, and reader-locked rw_semaphores (where __up_read() does not clear sem->owner when !CONFIG_DEBUG_RWSEMS) do not maintain an authoritative per-task owner pointer.
- Tracking these locks (as well as slab-cache and lock-type filters) relies on fexit (acquire) and fentry (release) BPF hooks maintaining the held_locks BPF LRU hash map:
- Any such lock already held before perf record attaches its BPF programs will not be present in held_locks until it is released and re-acquired.
- The attached fentry/fexit hooks execute on every kernel lock acquire and release for the hooked lock family across the system, adding tracing overhead outside of perf sample handling.
- Cross-task semaphore signaling (down*() / up()):
- Counting struct semaphores do not enforce same-task ownership in the
kernel: when a semaphore is used as a completion/signaling mechanism (down() in one task woken by up() in another task or interrupt handler, which proposed kernel dependency trackers like CONFIG_DEPT model as wait/event dependencies bounded by execution context rather than lock ownership), fexit/down and fentry/up do not pair on the same task ID. Semaphore hooks are therefore only enabled when semaphore or a *_sem symbol (such as console_sem) is explicitly specified, and held_locks uses BPF_MAP_TYPE_LRU_HASH so any unpaired cross-task entries are automatically evicted.
- Shared trace_event_call->prog_array on PERF_TYPE_TRACEPOINT:
- In kernel/events/core.c, __perf_event_set_bpf_prog() requires BPF_PROG_TYPE_TRACEPOINT for PERF_TYPE_TRACEPOINT events and attaches the program to event->tp_event->prog_array on the shared trace_event_call. Because perf_trace_run_bpf_submit() executes trace_call_bpf() before perf_tp_event(), returning 0 from perf_tp_sample_filter filters that tracepoint invocation before perf_tp_event() iterates call->perf_events (affecting concurrent perf_event listeners on the same tracepoint while the privileged perf record session is active).

Patch overview (patches 1-2 are standalone fixes independent of the rest of the series):
1. "perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF":
Attaches perf_sample_filter directly via PERF_EVENT_IOC_SET_BPF in perf_bpf_filter__prepare(), matching the pinned filter path and avoiding leaking struct bpf_link_perf or double-closing FD(evsel, x, y).
2. "perf bpf-filter: Support BPF sample filters on tracepoint events":
Adds SEC("tracepoint") int perf_tp_sample_filter(void *ctx) so BPF sample filters can attach to PERF_TYPE_TRACEPOINT events (where __perf_event_set_bpf_prog() in kernel/events/core.c requires BPF_PROG_TYPE_TRACEPOINT rather than BPF_PROG_TYPE_PERF_EVENT).
3. "perf lock contention: Share common BPF and lock type definitions in lock_data.h": Pure refactoring moving lock_type_table to util/lock-contention.c and LCB_F_* flags, CO-RE structs, and common BPF lock helpers into tools/perf/util/bpf_skel/lock_data.h.
4. "perf lock contention: Extend get_lock_owner() for rt_mutex and mutex handoff": Extends get_lock_owner() in lock_data.h to support rt_mutex (LCB_F_RT), CONFIG_PREEMPT_RT mutexes, and MUTEX_FLAG_HANDOFF.
5. "perf bpf-filter: Add lock_held() sample filter for global mutexes":
Adds the lock_held(), lock_held_read()/lock_held_shared(), lock_held_write()/lock_held_exclusive(), and :R/:W filter syntax and evaluates global/static kernel mutexes via direct lock->owner inspection.
6. "perf bpf-filter: Extend lock_held() to other kernel lock types":
Extends lock_held() to spinlocks, rwsems, rwlocks, rt-mutexes, percpu-rwsems, and semaphores (as well as hex addresses and lock type filters) using a held_locks BPF LRU hash map updated by selectively attached fentry/fexit hooks.
7. "perf bpf-filter: Support per-process and semi-global locks in lock_held()": Adds support for mmap_lock, siglock, rq_lock, and zone_lock.
8. "perf bpf-filter: Support slab cache locks (&<name>) in lock_held()":
Adds support for slab cache locks prefixed with & (e.g. lock_held(&dentry)) using the kmem_cache BPF iterator and slab_caches map.
9. "perf test: Add tests for lock_held() BPF sample filter": Adds unit tests in tests/parse-events.c and shell tests in tests/shell/record_bpf_filter.sh.
10. "perf bpf-filter: Extend lock_held() to support RCU, Tasks Trace RCU,

    and SRCU": Supports `rcu` (`rcu:R` via direct
    `current->rcu_read_lock_nesting` inspection with zero tracing hooks;
    `rcu:W` via `synchronize_rcu*()` / `rcu_barrier()` hooks),
    `rcu-trace` (via `current->trc_reader_nesting`), and `srcu`
    (`srcu:R` via `__srcu_read_lock*` / `__srcu_read_unlock*`; `srcu:W`
    via `synchronize_srcu*()` / `srcu_barrier()`).

11. "perf lock contention: Extend BPF lock contention to RCU and SRCU":
Extends perf lock contention --use-bpf to track RCU and SRCU grace-period and barrier waits (-Y rcu, -Y srcu, -L rcu).

Changes in v6:
- Drop "perf lock contention: Filter events before creating lock_stat"
as Arnaldo cherry-picked it.
- Add an inline comment above pin_filter_object() in util/bpf-filter.c
in patch 2 explaining why bpf_object__pin() / bpf_object__unpin()
cannot be used when programs in sample_filter.bpf.c have autoload
disabled (Namhyung).
- Split the lock_data.h refactoring into a pure code-movement commit
(patch 3) and a separate commit extending get_lock_owner() for
rt_mutex and MUTEX_FLAG_HANDOFF (patch 4), keep lock_syms in its
original location in lock_contention.bpf.c, and add a comment above
#ifdef __BPF__ in lock_data.h explaining that the header is shared
between userspace and BPF programs (Namhyung).
- Split the lock_held() implementation into 4 incremental commits
(patches 5-8): (5) core parser, expression evaluation, and global mutex
support; (6) other kernel lock types (spinlock, rwsem, rwlock,
rt-mutex, percpu-rwsem, semaphore), hex addresses, and lock type
filters; (7) per-process (mmap_lock, siglock) and semi-global
(rq_lock, zone_lock) locks; and (8) slab cache locks (&<name>)
(Namhyung).
- Update is_possible_tp_filter() in util/parse-events.c in patch 2
to check all tracepoint BPF sample filter terms enabled by that patch
(uid, gid, tid, pid, cpu, time, cgroup) using
word-boundary matching (has_filter_word()) and !evsel__field() so
they are routed to evsel->bpf_filters when not matching a tracepoint
format field, and extend bpf_tp_terms[] with lock_held* in patch 5.
- Replace strtailcmp(base, ...) with str_ends_with(base, ...) in prescan_one_lock_expr() and resolve_lock_expr() in
util/bpf-filter.c (patches 5, 6, and 10) so lock symbol names shorter
than a tested suffix (such as lock vs spinlock, or u_rwsem vs percpu_rwsem) are not misclassified.
- Use a CO-RE flavor struct struct rt_mutex_base___new in lock_data.h
(patch 4) and add explicit standard C header includes (<errno.h>,
<stdio.h>, <unistd.h>, <string.h>, <stddef.h>, <stdlib.h>) in
patches 1, 2, and 11 for musl libc compatibility.
- Reject kernel text functions, module text functions, and absolute or
undefined symbols when resolving lock addresses from /proc/kallsyms,
and check for __percpu_rwsem_rc_<name> in BTF so percpu_rw_semaphore
symbols ending in _rwsem (such as cgroup_threadgroup_rwsem or
file_rwsem) do not set PBF_LOCK_DIRECT_RWSEM or allow read-only mode.
- Link to v5: https://lore.kernel.org/linux-perf-users/[email protected]/

Changes in v5:
- Add patch 2 ("perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF") attaching BPF sample filters via ioctl(..., PERF_EVENT_IOC_SET_BPF, fd) instead of bpf_program__attach_perf_event_opts(), fixing the bpf_link memory leak without double-closing FD(evsel, x, y), and use the same attachment in patch 3 for tracepoint sample filters (Namhyung).
- Expand patch 3's commit message to detail why pin_filter_object() and unpin_filter_object() replace bpf_object__pin() and bpf_object__unpin() when autoload is disabled on perf_tp_sample_filter (Namhyung).
- Store the resolved lock target in perf_bpf_filter_entry.value (with op normalized to PBF_OP_EQ or PBF_OP_NEQ), keeping struct perf_bpf_filter_entry unchanged at 24 bytes for backwards compatibility with pinned filters maps.
- Add a CO-RE struct rt_mutex___old fallback in get_lock_owner() in lock_data.h for kernels prior to v5.15, and pass baseline nesting depth to is_rcu_trace_lock_held() for syscall tracepoints.

Changes in v4:
- Move the two bugfix commits (Filter events before creating lock_stat and Support BPF sample filters on tracepoint events) to patches 1 and 2 at the start of the series for easier cherry-picking.
- Reserve leading & strictly for slab cache locks (e.g. lock_held(&dentry)) so global/static lock symbols and well-known locks do not use & (e.g. lock_held(cgroup_mutex), lock_held_read(mmap_lock)), matching perf lock contention (Namhyung).
- Skip attaching fentry/fexit hooks when filtering on a specific mutex symbol (*_mutex), rt_mutex symbol (*_rt_mutex), or write-locked mmap_lock (mmap_lock:W / lock_held_write(mmap_lock)), evaluating them purely via direct owner inspection (Namhyung).
- Use a CO-RE flavor struct struct mutex___non_rt in get_lock_owner() in lock_data.h so GEN_VMLINUX_H=1 builds succeed on CONFIG_PREEMPT_RT=y kernels.
- Switch held_locks to BPF_MAP_TYPE_LRU_HASH, exclude LOCK_PROG_SEM from LOCK_PROG_ALL unless semaphore or a *_sem symbol is explicitly requested, and document cross-task semaphore signaling limitations (and comparison with CONFIG_DEPT).
- Skip LCB_F_MUTEX | LCB_F_SPIN in parse_lock_type_name(), reject read-only mode on exclusive-only lock symbol suffixes in resolve_lock_expr(), and check needed_groups & supported_groups before masking needed_groups in configure_lock_progs().
- Recursively traverse anonymous structs/unions in btf_has_task_field() so lock_held(rcu) and lock_held(rcu-trace) work on CONFIG_RANDSTRUCT kernels.

Changes in v3:
- Move the writer-only rw_semaphore check out of get_lock_owner() in lock_data.h into is_rwsem_writer_owner() in sample_filter.bpf.c so perf lock contention -b -o still reports reader owners when a writer contends on a reader-owned rw_semaphore, and scope is_direct_lock_owner() by lock type (PBF_LOCK_DIRECT_MUTEX, PBF_LOCK_DIRECT_RWSEM, PBF_LOCK_DIRECT_RTMUTEX).
- Add SEC("tracepoint") int perf_tp_sample_filter(void *ctx) so BPF sample filters (lock_held(), uid, gid, etc.) can attach to PERF_TYPE_TRACEPOINT events (such as kmem:mm_page_alloc and vmscan:mm_vmscan_direct_reclaim_begin), check libbpf_get_error() when attaching, and document memory allocation / direct reclaim filtering with lock_held().
- Return early in init_numa_data() in bpf-filter.c when node_data cannot be resolved and check node_data_addr != 0 in do_collect_zone_lock().
- Avoid double-counting _raw_read_lock_irq / _raw_read_lock_bh in sample_filter.bpf.c on CONFIG_GENERIC_LOCKBREAK=y && !CONFIG_DEBUG_LOCK_ALLOC kernels where they call _raw_read_lock_irqsave().
- Offset rcu_state_addr by 1 byte so it is distinct from &rcu_state.node[0].lock at offset 0 of rcu_state, and pass bool is_rcu to do_contention_end() in lock_contention.bpf.c so tp_btf/contention_end and RCU/SRCU fexit hooks never cross-match timestamp maps.

Changes in v2:
- Guard BPF_CORE_READ(mutex, owner.counter) with bpf_core_field_exists and fall back to struct rt_mutex_base in get_lock_owner() so CO-RE relocation succeeds on CONFIG_PREEMPT_RT=y kernels.
- Add CONFIG_DEBUG_LOCK_ALLOC=y lock entry points (_mutex_lock_nest_lock, _mutex_lock_killable, _mutex_trylock_nest_lock, _down_write_nest_lock, _raw_spin_lock_nest_lock, _rt_mutex_lock_nest_lock) to sample_filter.bpf.c and lock_progs[].
- Verify in supported_lock_prog_groups() that both acquire and all unlock BTF entry points exist for a lock family before enabling its tracing hooks, preventing acquire-only attachment when spinlock/rwlock unlock functions are inlined.
- Enable LOCK_PROG_PERCPU_RWSEM alongside LOCK_PROG_RWSEM_WRITE when a symbol name ends in rwsem (such as cgroup_threadgroup_rwsem).
- Gate record_lock_acquired(ctx, LCB_F_READ) in fexit_downgrade_write on track_rwsem_read and verify non-zero read/write counts in record_lock_released_addr() before decrementing aggregate slab/type counts.
- Adjust stack skip depth by 2 for fentry RCU/SRCU programs in lock_contention.bpf.c and recognize synchronize_rcu*, synchronize_srcu*, rcu_barrier, and srcu_barrier in machine__is_lock_function().
- Add patch fixing report_lock_contention_begin_event() to check type, address, and callstack filters before creating lock_stat entries.

Assisted-by Antigravity:gemini-3.1-pro

Ian Rogers (11):
perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF perf bpf-filter: Support BPF sample filters on tracepoint events perf lock contention: Share common BPF and lock type definitions in
lock_data.h
perf lock contention: Extend get_lock_owner() for rt_mutex and mutex
handoff
perf bpf-filter: Add lock_held() sample filter for global mutexes perf bpf-filter: Extend lock_held() to other kernel lock types perf bpf-filter: Support per-process and semi-global locks in

    lock_held()

perf bpf-filter: Support slab cache locks (&<name>) in lock_held() perf test: Add tests for lock_held() BPF sample filter perf bpf-filter: Extend lock_held() to support RCU, Tasks Trace RCU,
and SRCU
perf lock contention: Extend BPF lock contention to RCU and SRCU

 tools/perf/Documentation/perf-lock.txt        |    7 +-
 tools/perf/Documentation/perf-record.txt      |   74 +-
 tools/perf/builtin-lock.c                     |   27 -
 tools/perf/tests/parse-events.c               |  121 ++
 tools/perf/tests/shell/lock_contention.sh     |   14 +
 tools/perf/tests/shell/record_bpf_filter.sh   |  142 ++
 tools/perf/util/bpf-filter.c                  | 1475 ++++++++++++++++-
 tools/perf/util/bpf-filter.h                  |   13 +
 tools/perf/util/bpf-filter.l                  |   31 +-
 tools/perf/util/bpf-filter.y                  |   47 +-
 tools/perf/util/bpf_lock_contention.c         |  174 +-
 .../perf/util/bpf_skel/lock_contention.bpf.c  |  431 ++---
 tools/perf/util/bpf_skel/lock_data.h          |  394 ++++-
 tools/perf/util/bpf_skel/sample-filter.h      |   80 +
 tools/perf/util/bpf_skel/sample_filter.bpf.c  | 1241 ++++++++++++++
 tools/perf/util/bpf_skel/vmlinux/vmlinux.h    |    7 +
 tools/perf/util/lock-contention.c             |   23 +
 tools/perf/util/lock-contention.h             |   15 +
 tools/perf/util/machine.c                     |   11 +
 tools/perf/util/parse-events.c                |   40 +-
 20 files changed, 4008 insertions(+), 359 deletions(-)
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
author reviewer
#79 lore raw

PATCH v6 1/11 perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF

In perf_bpf_filter__prepare(), the unpinned filter path attaches skel->progs.perf_sample_filter to each FD(evsel, x, y) using bpf_program__attach_perf_event_opts() and ignores the returned struct bpf_link *, leaking the allocated struct bpf_link_perf and its BPF_PERF_EVENT link fd.

Furthermore, bpf_program__attach_perf_event_opts() is designed for callers that transfer ownership of the perf_event fd to the returned
bpf_link: when bpf_link__destroy() is called, bpf_link_perf_detach() unconditionally disables and closes perf_link->perf_event_fd. Because evsel->core.fd owns FD(evsel, x, y) and closes them in evlist__close(), destroying the returned bpf_link would double-close the perf_event file descriptors.

Fix this by attaching the program directly with ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd), matching the pinned filter path right above it in perf_bpf_filter__prepare(). In the kernel, PERF_EVENT_IOC_SET_BPF takes a reference on the BPF program and _free_event() -> perf_event_free_bpf_prog() automatically detaches and releases it when the perf_event fd is closed. This also avoids enabling the event prematurely, allowing pe_opts (.dont_enable = true) and the LIBBPF_CURRENT_VERSION_GEQ(1, 7) guard to be dropped.

Before (built with EXTRA_CFLAGS="-fsanitize=address"):

  # perf record -e cycles --filter 'period > 1000' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data ]

=================================================================
==51328==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 1568 byte(s) in 28 object(s) allocated from:

      #0 0x7ffbe76ef24f in calloc (/lib64/libasan.so.8+0xef24f)
      #1 0x625df7 in bpf_program__attach_perf_event_opts (tools/perf/perf+0x625df7)
      #2 0xbeddc0 in perf_bpf_filter__prepare util/bpf-filter.c:507
      #3 0x8f3def in evlist__apply_filters util/evlist.c:1421
      #4 0x44bbcf in record__open tools/perf/builtin-record.c:1469
      #5 0x453f9e in __cmd_record tools/perf/builtin-record.c:2594
      #6 0x45dadb in cmd_record tools/perf/builtin-record.c:4427
      #7 0x5df56b in run_builtin tools/perf/perf.c:383
      #8 0x5dfa0e in handle_internal_command tools/perf/perf.c:436
      #9 0x5dfddc in run_argv tools/perf/perf.c:480
      #10 0x5e0333 in main tools/perf/perf.c:581

SUMMARY: AddressSanitizer: 1568 byte(s) leaked in 28 allocation(s).

After (built with EXTRA_CFLAGS="-fsanitize=address"):

  # perf record -e cycles --filter 'period > 1000' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data ]
Fixes 56ec9457a4a2 ("perf bpf filter: Implement event sample filtering")
---
 tools/perf/util/bpf-filter.c | 18 +++++-------------
 1 file changed, 5 insertions(+), 13 deletions(-)
tools/perf/util/bpf-filter.c +5 -13
index 72e83ac1d6a4..506414e5c407 100644
@@ -40,6 +40,7 @@
  * The 'dropped' map is to keep how many samples it dropped by the filter and
  * it will be reported as lost samples.
  */
+#include <errno.h>
 #include <stdlib.h>
 #include <fcntl.h>
 #include <sys/ioctl.h>
@@ -423,16 +424,8 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 {
 	int i, x, y, fd, ret;
 	struct sample_filter_bpf *skel = NULL;
-	struct bpf_program *prog;
-	struct bpf_link *link;
 	struct perf_bpf_filter_entry *entry;
 	bool needs_idx_hash = !target__has_cpu(target);
-#if LIBBPF_CURRENT_VERSION_GEQ(1, 7)
-	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts,
-			    .dont_enable = true);
-#else
-	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
-#endif
 
 	entry = calloc(MAX_FILTERS, sizeof(*entry));
 	if (entry == NULL)
@@ -501,14 +494,13 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		goto err;
 	}
 
-	prog = skel->progs.perf_sample_filter;
+	fd = bpf_program__fd(skel->progs.perf_sample_filter);
 	for (x = 0; x < xyarray__max_x(evsel->core.fd); x++) {
 		for (y = 0; y < xyarray__max_y(evsel->core.fd); y++) {
-			link = bpf_program__attach_perf_event_opts(prog, FD(evsel, x, y),
-								   &pe_opts);
-			if (IS_ERR(link)) {
+			ret = ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd);
+			if (ret < 0) {
+				ret = -errno;
 				pr_err("Failed to attach perf sample-filter program\n");
-				ret = PTR_ERR(link);
 				goto err;
 			}
 		}
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#80 lore raw

Re: [PATCH v6 01/11] perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

In perf_bpf_filter__prepare(), the unpinned filter path attaches skel->progs.perf_sample_filter to each FD(evsel, x, y) using bpf_program__attach_perf_event_opts() and ignores the returned struct bpf_link *, leaking the allocated struct bpf_link_perf and its BPF_PERF_EVENT link fd.

Furthermore, bpf_program__attach_perf_event_opts() is designed for callers that transfer ownership of the perf_event fd to the returned
bpf_link: when bpf_link__destroy() is called, bpf_link_perf_detach() unconditionally disables and closes perf_link->perf_event_fd. Because evsel->core.fd owns FD(evsel, x, y) and closes them in evlist__close(), destroying the returned bpf_link would double-close the perf_event file descriptors.

Quoted 7 lines

Fix this by attaching the program directly with
[ ... ]

Fixes 56ec9457a4a2 ("perf bpf filter: Implement event sample filtering")

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
maintainer Tested-by on v6 1/11
#81 lore raw

Re: [PATCH v6 01/11] perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF

In reply to Ian Rogers
Quoted 47 lines · Ian Rogers

In perf_bpf_filter__prepare(), the unpinned filter path attaches skel->progs.perf_sample_filter to each FD(evsel, x, y) using bpf_program__attach_perf_event_opts() and ignores the returned struct bpf_link *, leaking the allocated struct bpf_link_perf and its BPF_PERF_EVENT link fd.

Furthermore, bpf_program__attach_perf_event_opts() is designed for callers that transfer ownership of the perf_event fd to the returned
bpf_link: when bpf_link__destroy() is called, bpf_link_perf_detach() unconditionally disables and closes perf_link->perf_event_fd. Because evsel->core.fd owns FD(evsel, x, y) and closes them in evlist__close(), destroying the returned bpf_link would double-close the perf_event file descriptors.

Fix this by attaching the program directly with ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd), matching the pinned filter path right above it in perf_bpf_filter__prepare(). In the kernel, PERF_EVENT_IOC_SET_BPF takes a reference on the BPF program and _free_event() -> perf_event_free_bpf_prog() automatically detaches and releases it when the perf_event fd is closed. This also avoids enabling the event prematurely, allowing pe_opts (.dont_enable = true) and the LIBBPF_CURRENT_VERSION_GEQ(1, 7) guard to be dropped.

Before (built with EXTRA_CFLAGS="-fsanitize=address"):

  # perf record -e cycles --filter 'period > 1000' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data ]

=================================================================
==51328==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 1568 byte(s) in 28 object(s) allocated from:

      #0 0x7ffbe76ef24f in calloc (/lib64/libasan.so.8+0xef24f)
      #1 0x625df7 in bpf_program__attach_perf_event_opts (tools/perf/perf+0x625df7)
      #2 0xbeddc0 in perf_bpf_filter__prepare util/bpf-filter.c:507
      #3 0x8f3def in evlist__apply_filters util/evlist.c:1421
      #4 0x44bbcf in record__open tools/perf/builtin-record.c:1469
      #5 0x453f9e in __cmd_record tools/perf/builtin-record.c:2594
      #6 0x45dadb in cmd_record tools/perf/builtin-record.c:4427
      #7 0x5df56b in run_builtin tools/perf/perf.c:383
      #8 0x5dfa0e in handle_internal_command tools/perf/perf.c:436
      #9 0x5dfddc in run_argv tools/perf/perf.c:480
      #10 0x5e0333 in main tools/perf/perf.c:581

SUMMARY: AddressSanitizer: 1568 byte(s) leaked in 28 allocation(s).

After (built with EXTRA_CFLAGS="-fsanitize=address"):

Quoted 8 lines
  # perf record -e cycles --filter 'period > 1000' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data ]
Fixes 56ec9457a4a2 ("perf bpf filter: Implement event sample filtering")

Thanks,
Namhyung

Quoted 55 lines
---
 tools/perf/util/bpf-filter.c | 18 +++++-------------
 1 file changed, 5 insertions(+), 13 deletions(-)
tools/perf/util/bpf-filter.c +5 -13
index 72e83ac1d6a4..506414e5c407 100644
@@ -40,6 +40,7 @@
  * The 'dropped' map is to keep how many samples it dropped by the filter and
  * it will be reported as lost samples.
  */
+#include <errno.h>
 #include <stdlib.h>
 #include <fcntl.h>
 #include <sys/ioctl.h>
@@ -423,16 +424,8 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 {
 	int i, x, y, fd, ret;
 	struct sample_filter_bpf *skel = NULL;
-	struct bpf_program *prog;
-	struct bpf_link *link;
 	struct perf_bpf_filter_entry *entry;
 	bool needs_idx_hash = !target__has_cpu(target);
-#if LIBBPF_CURRENT_VERSION_GEQ(1, 7)
-	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts,
-			    .dont_enable = true);
-#else
-	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
-#endif
 
 	entry = calloc(MAX_FILTERS, sizeof(*entry));
 	if (entry == NULL)
@@ -501,14 +494,13 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		goto err;
 	}
 
-	prog = skel->progs.perf_sample_filter;
+	fd = bpf_program__fd(skel->progs.perf_sample_filter);
 	for (x = 0; x < xyarray__max_x(evsel->core.fd); x++) {
 		for (y = 0; y < xyarray__max_y(evsel->core.fd); y++) {
-			link = bpf_program__attach_perf_event_opts(prog, FD(evsel, x, y),
-								   &pe_opts);
-			if (IS_ERR(link)) {
+			ret = ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd);
+			if (ret < 0) {
+				ret = -errno;
 				pr_err("Failed to attach perf sample-filter program\n");
-				ret = PTR_ERR(link);
 				goto err;
 			}
 		}
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
author reviewer
#82 lore raw

PATCH v6 2/11 perf bpf-filter: Support BPF sample filters on tracepoint events

In reply to Ian Rogers

Commit 466db4275edd ("perf parse-events: Add parse_uid_filter helper") updated set_filter() to route non-tracepoint filter terms (such as uid and gid) on PERF_TYPE_TRACEPOINT events to evsel->bpf_filters instead of the ftrace tracepoint predicate filter.

However, in the kernel's __perf_event_set_bpf_prog() (kernel/events/core.c), attaching a BPF program to a perf_event fd branches on perf_event_is_tracing(event):
- Non-tracing events (hardware PMU, software events, breakpoints) call perf_event_set_bpf_handler(), which requires BPF_PROG_TYPE_PERF_EVENT (SEC("perf_event")).
- Tracepoint events (event->pmu == &perf_tracepoint) reject BPF_PROG_TYPE_PERF_EVENT with -EINVAL and instead require BPF_PROG_TYPE_TRACEPOINT (SEC("tracepoint")), which is attached to event->tp_event->prog_array and executed in perf_trace_run_bpf_submit() before perf_tp_event(), dropping the sample if the BPF program returns 0. Furthermore, the bpf_cast_to_kern_ctx() kfunc is only permitted in BPF_PROG_TYPE_PERF_EVENT programs.

Add SEC("tracepoint") int perf_tp_sample_filter(void *ctx) in sample_filter.bpf.c to evaluate context-independent filter terms (uid, gid, tid, cpu, time, cgroup) using BPF helpers without calling bpf_cast_to_kern_ctx(). When preparing a BPF filter on a PERF_TYPE_TRACEPOINT evsel, autoload perf_tp_sample_filter instead of perf_sample_filter and attach it once to the shared trace_event_call. Because returning 0 from a BPF_PROG_TYPE_TRACEPOINT program filters at the shared trace_event_call->prog_array prior to perf_tp_event(), tracepoint BPF filters are never pinned for unprivileged use and require CAP_BPF or root privileges.

Because perf_bpf_filter__pin() and perf_bpf_filter__unpin() only load perf_sample_filter and disable autoload on perf_tp_sample_filter, libbpf's bpf_object__pin() and bpf_object__unpin() can no longer be used directly (as bpf_object__pin_programs() and bpf_object__unpin_programs() iterate over all programs in the object without checking autoload and fail with -EINVAL when a program has not been loaded). Introduce pin_filter_object() and unpin_filter_object() to pin/unpin the maps and only the loaded perf_sample_filter program.

Before:

  # perf record -e kmem:mm_page_alloc --filter 'uid == 0' -- true
  libbpf: prog 'perf_sample_filter': failed to attach to perf_event FD 3: Invalid argument
  Failed to attach perf sample-filter program
  failed to set filter "BPF" on event kmem:mm_page_alloc with 22 (Invalid argument)

After:

  # perf record -e kmem:mm_page_alloc --filter 'uid == 0' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data (42 samples) ]
Fixes 466db4275edd ("perf parse-events: Add parse_uid_filter helper")
---
 tools/perf/Documentation/perf-record.txt     |   8 +-
 tools/perf/util/bpf-filter.c                 | 144 ++++++++++++++++---
 tools/perf/util/bpf_skel/sample_filter.bpf.c |  95 ++++++++++++
 tools/perf/util/parse-events.c               |  38 ++++-
 4 files changed, 262 insertions(+), 23 deletions(-)
tools/perf/Documentation/perf-record.txt +7 -1
index 2351f7b4f5fc..fcf1ea62bf1c 100644
@@ -173,7 +173,13 @@ OPTIONS
 
 	A BPF filter can access the sample data and make a decision based on the
 	data.  Users need to set an appropriate sample type to use the BPF
-	filter.  BPF filters need root privilege.
+	filter.  BPF filters need root privilege (or CAP_BPF, or a pinned BPF
+	filter for non-tracepoint events).  On tracepoint events, BPF filters
+	support context-independent terms ('uid', 'gid', 'tid', 'pid', 'cpu',
+	'time', 'cgroup') by attaching a 'BPF_PROG_TYPE_TRACEPOINT' program to
+	the tracepoint's shared 'trace_event_call->prog_array', which filters
+	the tracepoint before 'perf_tp_event()' runs across concurrent
+	perf_event listeners on that tracepoint.
 
 	The sample data field can be specified in lower case letter.  Multiple
 	filters can be separated with comma.  For example,
tools/perf/util/bpf-filter.c +125 -19

236 lines not on this page · raw message

tools/perf/util/bpf_skel/sample_filter.bpf.c +95 -0

105 lines not on this page · raw message

tools/perf/util/parse-events.c +35 -3
index 2f3317ce17f0..d6bab89ade5d 100644
@@ -3,8 +3,10 @@
 #include <linux/err.h>
 #include <linux/list_sort.h>
 #include <linux/zalloc.h>
+#include <ctype.h>
 #include <dirent.h>
 #include <errno.h>
+#include <string.h>
 #include <sys/ioctl.h>
 #include <sys/param.h>
 #include "cpumap.h"
@@ -2593,10 +2595,40 @@ foreach_evsel_in_last_glob(struct evlist *evlist,
 	return 0;
 }
 
+static bool is_filter_word_char(char c)
+{
+	return isalnum((unsigned char)c) || c == '_' || c == '/' || c == '.';
+}
+
+static bool has_filter_word(const char *str, const char *word)
+{
+	size_t len = strlen(word);
+	const char *p = str;
+
+	while ((p = strstr(p, word)) != NULL) {
+		bool start_ok = (p == str) || !is_filter_word_char(p[-1]);
+		bool end_ok = !is_filter_word_char(p[len]);
+
+		if (start_ok && end_ok)
+			return true;
+		p += len;
+	}
+	return false;
+}
+
 /* Will a tracepoint filter work for str or should a BPF filter be used? */
-static bool is_possible_tp_filter(const char *str)
+static bool is_possible_tp_filter(struct evsel *evsel, const char *str)
 {
-	return strstr(str, "uid") == NULL;
+	static const char *const bpf_tp_terms[] = {
+		"uid", "gid", "tid", "pid", "cpu", "time", "cgroup",
+	};
+
+	for (size_t i = 0; i < ARRAY_SIZE(bpf_tp_terms); i++) {
+		if (has_filter_word(str, bpf_tp_terms[i]) &&
+		    !evsel__field(evsel, bpf_tp_terms[i]))
+			return false;
+	}
+	return true;
 }
 
 static int set_filter(struct evsel *evsel, const void *arg)
@@ -2611,7 +2643,7 @@ static int set_filter(struct evsel *evsel, const void *arg)
 		return -1;
 	}
 
-	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT && is_possible_tp_filter(str)) {
+	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT && is_possible_tp_filter(evsel, str)) {
 		if (evsel__append_tp_filter(evsel, str) < 0) {
 			fprintf(stderr,
 				"not enough memory to hold filter string\n");
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#83 lore raw

Re: [PATCH v6 02/11] perf bpf-filter: Support BPF sample filters on tracepoint events

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] perf parse-events: is_possible_tp_filter() misroutes generic cpu tp filters - [Medium] perf…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] perf parse-events: is_possible_tp_filter() misroutes generic cpu tp filters
- [Medium] perf parse-events: misrouted tracepoint filters in is_possible_tp_filter() --

commit dbe9f68d8a043d94d321ad8e9a98e3b1d3114baf
Author: Ian Rogers <[email protected]>

perf bpf-filter: Support BPF sample filters on tracepoint events

This commit adds a BPF_PROG_TYPE_TRACEPOINT sample filter program to evaluate context-independent filter terms (uid, gid, tid, pid, cpu, time, cgroup) on tracepoint events, and updates set_filter() and perf_bpf_filter__prepare() to route and attach those filters.

Quoted 4 lines
tools/perf/util/parse-events.c +0 -0
index 2f3317ce17f08..d6bab89ade5de 100644

[ ... ]

Quoted 23 lines
tools/perf/util/parse-events.c +19 -0
@@ -2593,10 +2595,40 @@ foreach_evsel_in_last_glob(struct evlist *evlist,
 	return 0;
 }
 
+static bool is_filter_word_char(char c)
+{
+	return isalnum((unsigned char)c) || c == '_' || c == '/' || c == '.';
+}
+
+static bool has_filter_word(const char *str, const char *word)
+{
+	size_t len = strlen(word);
+	const char *p = str;
+
+	while ((p = strstr(p, word)) != NULL) {
+		bool start_ok = (p == str) || !is_filter_word_char(p[-1]);
+		bool end_ok = !is_filter_word_char(p[len]);
+
+		if (start_ok && end_ok)
+			return true;
+		p += len;
+	}
+	return false;

tools/perf/util/parse-events.c foreach_evsel_in_last_glob(struct evlist *evlist, · line 2624

Quoted 10 lines
tools/perf/util/parse-events.c +6 -2
+}
+
 /* Will a tracepoint filter work for str or should a BPF filter be used? */
-static bool is_possible_tp_filter(const char *str)
+static bool is_possible_tp_filter(struct evsel *evsel, const char *str)
 {
-	return strstr(str, "uid") == NULL;
+	static const char *const bpf_tp_terms[] = {
+		"uid", "gid", "tid", "pid", "cpu", "time", "cgroup",
+	};

[Severity: Medium]
In tools/perf/util/parse-events.c, is_possible_tp_filter() includes "cpu" in bpf_tp_terms[] and returns false whenever evsel__field(evsel, "cpu") is NULL.

In kernel/trace/trace_events.c, trace_define_generic_fields() registers "cpu" in ftrace_generic_fields for all tracepoint events:

kernel/trace/trace_events.c:trace_define_generic_fields() {
	int ret;

	__generic_field(int, CPU, FILTER_CPU);
	__generic_field(int, cpu, FILTER_CPU);
	__generic_field(int, common_cpu, FILTER_CPU);

While trace_find_event_field() resolves ftrace_generic_fields when applying a tracepoint filter via PERF_EVENT_IOC_SET_FILTER, f_next() and f_show() only emit ftrace_common_fields and event-specific fields in the tracefs format file parsed by evsel__field().

For any tracepoint that does not define its own event-specific "cpu" field (such as sched:sched_switch or kmem:mm_page_alloc), evsel__field(evsel, "cpu") returns NULL, so parse_filter() -> set_filter() -> is_possible_tp_filter() returns false.

Will this cause valid ftrace tracepoint predicate filters referencing the generic "cpu" field (such as compound filters combining "cpu" with event-specific fields, "&&", parentheses, or "CPUS{...}" masks) to be misrouted to perf_bpf_filter__parse() and fail to parse, while forcing standalone "cpu" tracepoint filters onto the shared trace_event_call->prog_array BPF filter requiring CAP_BPF?

tools/perf/util/parse-events.c foreach_evsel_in_last_glob(struct evlist *evlist, · line 2632

Quoted 8 lines
tools/perf/util/parse-events.c +7 -0
+
+	for (size_t i = 0; i < ARRAY_SIZE(bpf_tp_terms); i++) {
+		if (has_filter_word(str, bpf_tp_terms[i]) &&
+		    !evsel__field(evsel, bpf_tp_terms[i]))
+			return false;
+	}
+	return true;
 }

[Severity: Medium]
Can parse_filter() -> foreach_evsel_in_last_glob() -> set_filter() -> is_possible_tp_filter() in tools/perf/util/parse-events.c also misroute tracepoint filters in the following cases?

First, when perf is built without HAVE_LIBTRACEEVENT (NO_LIBTRACEEVENT=1), PERF_TYPE_TRACEPOINT events and kernel ftrace filters (applied via PERF_EVENT_IOC_SET_FILTER in perf_evsel__apply_filter()) are still supported via tp_pmu__id(), but the stub in tools/perf/util/evsel.h unconditionally returns NULL:

tools/perf/util/evsel.h:
static inline struct tep_format_field *
evsel__field(struct evsel *evsel __maybe_unused, const char *name __maybe_unused)

{
	return NULL;
}

When evsel__field() returns NULL, any tracepoint filter referencing a format field whose name appears in bpf_tp_terms[] (such as "pid" on sched:sched_wakeup, sched:sched_process_fork, or signal:signal_generate) causes is_possible_tp_filter() to return false. A filter like --filter "pid == 1234" on sched:sched_wakeup will then be routed to perf_tp_sample_filter and match current's TGID (bpf_get_current_pid_tgid() >>
32) instead of the tracepoint's target "pid" field, while compound filters like --filter "pid == 1234 && success == 1" will fail to parse in perf_bpf_filter__parse().

Second, even with HAVE_LIBTRACEEVENT enabled, has_filter_word() scans the raw filter string with strstr() without skipping quoted string literals, and is_filter_word_char() treats quotes, hyphens, and glob characters as word boundaries. On an event without a field of that name (for example, sched:sched_switch), a valid tracepoint string filter such as prev_comm == "cpu" or next_comm == "systemd-time" matches inside the quoted literal, causing is_possible_tp_filter() to return false and perf_bpf_filter__parse() to reject the filter.

Third, if a filter on an event like sched:sched_wakeup combines a tracepoint field whose name is in bpf_tp_terms[] with a BPF-only term (such as "pid == 1234, uid == 0"), is_possible_tp_filter() returns false for the entire string, causing "pid" to be evaluated as current's TGID in BPF rather than the tracepoint's "pid" field.

Quoted 11 lines
tools/perf/util/parse-events.c +1 -1
 static int set_filter(struct evsel *evsel, const void *arg)
@@ -2611,7 +2643,7 @@ static int set_filter(struct evsel *evsel, const void *arg)
 		return -1;
 	}
 
-	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT && is_possible_tp_filter(str)) {
+	if (evsel->core.attr.type == PERF_TYPE_TRACEPOINT && is_possible_tp_filter(evsel, str)) {
 		if (evsel__append_tp_filter(evsel, str) < 0) {
 			fprintf(stderr,
 				"not enough memory to hold filter string\n");
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author reviewer
#84 lore raw

PATCH v6 3/11 perf lock contention: Share common BPF and lock type definitions in lock_data.h

In reply to Ian Rogers

Move lock_type_table, LCB_F_* flags, and the common BPF lock helpers (get_lock_owner, get_current_mmap_lock, get_current_siglock, get_lock_addr, check_lock_type, do_collect_zone_lock, do_collect_lock_syms, do_slab_cache_iter) and shared CO-RE structs into tools/perf/util/bpf_skel/lock_data.h and tools/perf/util/lock-contention.[ch] so they can be reused by BPF sample filtering.

---
 tools/perf/builtin-lock.c                     |  27 --
 .../perf/util/bpf_skel/lock_contention.bpf.c  | 235 +-------------
 tools/perf/util/bpf_skel/lock_data.h          | 303 ++++++++++++++++++
 tools/perf/util/lock-contention.c             |  19 ++
 tools/perf/util/lock-contention.h             |  13 +
 5 files changed, 338 insertions(+), 259 deletions(-)
tools/perf/builtin-lock.c +0 -27
index d5c0d55cb82d..feaf1cfd08cf 100644
@@ -1477,33 +1477,6 @@ static void sort_result(void)
 	}
 }
 
-static const struct {
-	unsigned int flags;
-	/*
-	 * Name of the lock flags (access), with delimeter ':'.
-	 * For example, rwsem:R of rwsem:W.
-	 */
-	const char *flags_name;
-	/* Name of the lock (type), for example, rwlock or rwsem. */
-	const char *lock_name;
-} lock_type_table[] = {
-	{ 0,				"semaphore",	"semaphore" },
-	{ LCB_F_SPIN,			"spinlock",	"spinlock" },
-	{ LCB_F_SPIN | LCB_F_READ,	"rwlock:R",	"rwlock" },
-	{ LCB_F_SPIN | LCB_F_WRITE,	"rwlock:W",	"rwlock" },
-	{ LCB_F_READ,			"rwsem:R",	"rwsem" },
-	{ LCB_F_WRITE,			"rwsem:W",	"rwsem" },
-	{ LCB_F_RT,			"rt-mutex",	"rt-mutex" },
-	{ LCB_F_RT | LCB_F_READ,	"rwlock-rt:R",	"rwlock-rt" },
-	{ LCB_F_RT | LCB_F_WRITE,	"rwlock-rt:W",	"rwlock-rt" },
-	{ LCB_F_PERCPU | LCB_F_READ,	"pcpu-sem:R",	"percpu-rwsem" },
-	{ LCB_F_PERCPU | LCB_F_WRITE,	"pcpu-sem:W",	"percpu-rwsem" },
-	{ LCB_F_MUTEX,			"mutex",	"mutex" },
-	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex",	"mutex" },
-	/* alias for optimistic spinning only */
-	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex:spin",	"mutex-spin" },
-};
-
 static const char *get_type_flags_name(unsigned int flags)
 {
 	flags &= LCB_F_TYPE_MASK;
tools/perf/util/bpf_skel/lock_contention.bpf.c +3 -232

291 lines not on this page · raw message

tools/perf/util/bpf_skel/lock_data.h +303 -0

313 lines not on this page · raw message

tools/perf/util/lock-contention.c +19 -0
index 119a7206f3cd..f6e68d740860 100644
@@ -6,6 +6,7 @@
 #include "symbol.h"
 
 #include <limits.h>
+#include <stdlib.h>
 #include <string.h>
 
 #include <linux/hash.h>
@@ -22,6 +23,24 @@ struct callstack_filter {
 static LIST_HEAD(callstack_filters);
 struct hlist_head *lockhash_table;
 
+const struct perf_lock_type lock_type_table[] = {
+	{ 0,				"semaphore",	"semaphore" },
+	{ LCB_F_SPIN,			"spinlock",	"spinlock" },
+	{ LCB_F_SPIN | LCB_F_READ,	"rwlock:R",	"rwlock" },
+	{ LCB_F_SPIN | LCB_F_WRITE,	"rwlock:W",	"rwlock" },
+	{ LCB_F_READ,			"rwsem:R",	"rwsem" },
+	{ LCB_F_WRITE,			"rwsem:W",	"rwsem" },
+	{ LCB_F_RT,			"rt-mutex",	"rt-mutex" },
+	{ LCB_F_RT | LCB_F_READ,	"rwlock-rt:R",	"rwlock-rt" },
+	{ LCB_F_RT | LCB_F_WRITE,	"rwlock-rt:W",	"rwlock-rt" },
+	{ LCB_F_PERCPU | LCB_F_READ,	"pcpu-sem:R",	"percpu-rwsem" },
+	{ LCB_F_PERCPU | LCB_F_WRITE,	"pcpu-sem:W",	"percpu-rwsem" },
+	{ LCB_F_MUTEX,			"mutex",	"mutex" },
+	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex",	"mutex" },
+	/* alias for optimistic spinning only */
+	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex:spin",	"mutex-spin" },
+};
+
 int parse_call_stack(const struct option *opt __maybe_unused, const char *str,
 		     int unset __maybe_unused)
 {
tools/perf/util/lock-contention.h +13 -0
index 59c94190b092..68e9bd77e8a9 100644
@@ -129,6 +129,19 @@ struct thread_stat {
 #define LCB_F_PERCPU	(1U << 4)
 #define LCB_F_MUTEX	(1U << 5)
 
+struct perf_lock_type {
+	unsigned int flags;
+	/*
+	 * Name of the lock flags (access), with delimiter ':'.
+	 * For example, rwsem:R or rwsem:W.
+	 */
+	const char *flags_name;
+	/* Name of the lock (type), for example, rwlock or rwsem. */
+	const char *lock_name;
+};
+
+extern const struct perf_lock_type lock_type_table[14];
+
 struct evlist;
 struct machine;
 struct target;
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#85 lore raw

Re: [PATCH v6 03/11] perf lock contention: Share common BPF and lock type definitions in lock_data.h

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

Move lock_type_table, LCB_F_* flags, and the common BPF lock helpers (get_lock_owner, get_current_mmap_lock, get_current_siglock, get_lock_addr, check_lock_type, do_collect_zone_lock, do_collect_lock_syms, do_slab_cache_iter) and shared CO-RE structs into tools/perf/util/bpf_skel/lock_data.h and tools/perf/util/lock-contention.[ch] so they can be reused by BPF sample filtering.

Sashiko has reviewed this patch and found no issues.

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

PATCH v6 4/11 perf lock contention: Extend get_lock_owner() for rt_mutex and mutex handoff

In reply to Ian Rogers

Extend get_lock_owner() in tools/perf/util/bpf_skel/lock_data.h to:
- Support rt_mutex locks (LCB_F_RT) and CONFIG_PREEMPT_RT mutexes via struct rt_mutex_base and struct rt_mutex___old, masking out the low waiter bit (0x1UL).
- Return NULL when a mutex has MUTEX_FLAG_HANDOFF (0x4UL) set on owner.counter and is in the middle of being handed off rather than actively held.

Also add rw_semaphore.count and struct rt_mutex_base to the fallback tools/perf/util/bpf_skel/vmlinux/vmlinux.h.

---
 tools/perf/util/bpf_skel/lock_data.h       | 62 ++++++++++++++++++----
 tools/perf/util/bpf_skel/vmlinux/vmlinux.h |  5 ++
 2 files changed, 58 insertions(+), 9 deletions(-)
tools/perf/util/bpf_skel/lock_data.h +53 -9
index 91d464ac18bd..43d8f5030bc1 100644
@@ -104,11 +104,24 @@ extern struct rq runqueues __ksym __weak;
 # define __has_builtin(x) 0
 #endif
 
+struct mutex___non_rt {
+	atomic_long_t owner;
+} __attribute__((preserve_access_index));
+
+struct rt_mutex_base___new {
+	struct task_struct *owner;
+} __attribute__((preserve_access_index));
+
+struct rt_mutex___old {
+	struct task_struct *owner;
+} __attribute__((preserve_access_index));
+
 struct rw_semaphore___old {
 	struct task_struct *owner;
 } __attribute__((preserve_access_index));
 
 struct rw_semaphore___new {
+	atomic_long_t count;
 	atomic_long_t owner;
 } __attribute__((preserve_access_index));
 
@@ -146,9 +159,25 @@ static __always_inline struct task_struct *get_lock_owner(__u64 lock, __u32 flag
 	__u64 owner = 0;
 
 	if (flags & LCB_F_MUTEX) {
-		struct mutex *mutex = (void *)lock;
-
-		owner = BPF_CORE_READ(mutex, owner.counter);
+		struct mutex___non_rt *mutex = (void *)lock;
+
+		if (bpf_core_field_exists(mutex->owner.counter)) {
+			owner = BPF_CORE_READ(mutex, owner.counter);
+			if (owner & 0x4UL)
+				return NULL;
+		} else if (bpf_core_type_exists(struct rt_mutex_base___new)) {
+			struct rt_mutex_base___new *rtm = (void *)lock;
+
+			owner = (__u64)BPF_CORE_READ(rtm, owner);
+			return (void *)(owner & ~1UL);
+		} else {
+			struct rt_mutex___old *rtm = (void *)lock;
+
+			if (bpf_core_field_exists(rtm->owner)) {
+				owner = (__u64)BPF_CORE_READ(rtm, owner);
+				return (void *)(owner & ~1UL);
+			}
+		}
 	} else if (flags == LCB_F_READ || flags == LCB_F_WRITE) {
 	/*
 	 * Support for the BPF_TYPE_MATCHES argument to the
@@ -158,20 +187,35 @@ static __always_inline struct task_struct *get_lock_owner(__u64 lock, __u32 flag
 	 */
 #if __has_builtin(__builtin_preserve_type_info) && __clang_major__ >= 15
 		if (bpf_core_type_matches(struct rw_semaphore___old)) {
-			struct rw_semaphore___old *rwsem = (void *)lock;
+			struct rw_semaphore___old *old = (void *)lock;
 
-			owner = (unsigned long)BPF_CORE_READ(rwsem, owner);
+			owner = (unsigned long)BPF_CORE_READ(old, owner);
 		} else if (bpf_core_type_matches(struct rw_semaphore___new)) {
-			struct rw_semaphore___new *rwsem = (void *)lock;
+			struct rw_semaphore___new *new = (void *)lock;
 
-			owner = BPF_CORE_READ(rwsem, owner.counter);
+			owner = BPF_CORE_READ(new, owner.counter);
 		}
 #else
 		/* assume new struct */
-		struct rw_semaphore *rwsem = (void *)lock;
+		struct rw_semaphore___new *new = (void *)lock;
 
-		owner = BPF_CORE_READ(rwsem, owner.counter);
+		if (bpf_core_field_exists(new->owner.counter))
+			owner = BPF_CORE_READ(new, owner.counter);
 #endif
+	} else if (flags == LCB_F_RT) {
+		if (bpf_core_type_exists(struct rt_mutex_base___new)) {
+			struct rt_mutex_base___new *rtm = (void *)lock;
+
+			owner = (__u64)BPF_CORE_READ(rtm, owner);
+			return (void *)(owner & ~1UL);
+		} else {
+			struct rt_mutex___old *rtm = (void *)lock;
+
+			if (bpf_core_field_exists(rtm->owner)) {
+				owner = (__u64)BPF_CORE_READ(rtm, owner);
+				return (void *)(owner & ~1UL);
+			}
+		}
 	}
 
 	if (!owner)
tools/perf/util/bpf_skel/vmlinux/vmlinux.h +5 -0
index 94e42b022ab1..b75ddc6846bb 100644
@@ -76,6 +76,7 @@ struct signal_struct {
 } __attribute__((preserve_access_index));
 
 struct rw_semaphore {
+	atomic_long_t count;
 	atomic_long_t owner;
 } __attribute__((preserve_access_index));
 
@@ -83,6 +84,10 @@ struct mutex {
 	atomic_long_t owner;
 } __attribute__((preserve_access_index));
 
+struct rt_mutex_base {
+	struct task_struct *owner;
+} __attribute__((preserve_access_index));
+
 struct kernfs_node {
 	u64 id;
 } __attribute__((preserve_access_index));
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#87 lore raw

Re: [PATCH v6 04/11] perf lock contention: Extend get_lock_owner() for rt_mutex and mutex handoff

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

Extend get_lock_owner() in tools/perf/util/bpf_skel/lock_data.h to:
- Support rt_mutex locks (LCB_F_RT) and CONFIG_PREEMPT_RT mutexes via struct rt_mutex_base and struct rt_mutex___old, masking out the low waiter bit (0x1UL).
- Return NULL when a mutex has MUTEX_FLAG_HANDOFF (0x4UL) set on owner.counter and is in the middle of being handed off rather than actively held.

Quoted 4 lines

Also add rw_semaphore.count and struct rt_mutex_base to the fallback tools/perf/util/bpf_skel/vmlinux/vmlinux.h.

Sashiko has reviewed this patch and found no issues.

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

PATCH v6 5/11 perf bpf-filter: Add lock_held() sample filter for global mutexes

In reply to Ian Rogers

Add BPF sample filter predicates lock_held(<lock>), lock_held_read(<lock>) / lock_held_shared(<lock>), and lock_held_write(<lock>) / lock_held_exclusive(<lock>) (as well as ':R' and ':W' suffixes on <lock>) to allow recording perf event samples only when a specified kernel lock is held (or not held with '!').

In this initial step, support global/static kernel mutex symbols (e.g. lock_held(cgroup_mutex)) resolved via /proc/kallsyms. On sample overflow, perf_sample_filter and perf_tp_sample_filter inspect the mutex's owner field directly in kernel memory via get_lock_owner() without attaching any BPF fentry/fexit hooks.

Subsequent commits extend lock_held() to other kernel lock types, per-process and semi-global locks, slab cache locks, and RCU/SRCU.

---
 tools/perf/Documentation/perf-record.txt     |  16 +-
 tools/perf/util/bpf-filter.c                 | 350 ++++++++++++++++++-
 tools/perf/util/bpf-filter.h                 |  13 +
 tools/perf/util/bpf-filter.l                 |  31 +-
 tools/perf/util/bpf-filter.y                 |  47 ++-
 tools/perf/util/bpf_skel/sample-filter.h     |  36 ++
 tools/perf/util/bpf_skel/sample_filter.bpf.c |  54 +++
 tools/perf/util/parse-events.c               |   2 +
 8 files changed, 530 insertions(+), 19 deletions(-)
tools/perf/Documentation/perf-record.txt +15 -1
index fcf1ea62bf1c..445cc98a6c33 100644
@@ -210,7 +210,21 @@ OPTIONS
 	  ip, id, tid, pid, cpu, time, addr, period, txn, weight, phys_addr,
 	  code_pgsz, data_pgsz, weight1, weight2, weight3, ins_lat, retire_lat,
 	  p_stage_cyc, mem_op, mem_lvl, mem_snoop, mem_remote, mem_lock,
-	  mem_dtlb, mem_blk, mem_hops, uid, gid
+	  mem_dtlb, mem_blk, mem_hops, uid, gid, cgroup, lock_held(<lock>),
+	  lock_held_read(<lock>), lock_held_shared(<lock>),
+	  lock_held_write(<lock>), lock_held_exclusive(<lock>)
+
+	The 'lock_held(<lock>)' predicate (or '!lock_held(<lock>)') filters
+	samples based on whether the specified kernel lock is currently held
+	by the kernel thread.  To differentiate between shared/read holding
+	and exclusive/write holding, use 'lock_held_read(<lock>)' (alias
+	'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)' (alias
+	'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to <lock>.
+	<lock> can be a kernel mutex symbol name (e.g.
+	'lock_held(cgroup_mutex)').  When filtering on a mutex symbol
+	('*_mutex'), 'perf_sample_filter' inspects the lock's 'owner' field
+	directly in kernel memory on each sample without attaching any BPF
+	fentry/fexit hooks.
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +336 -14

456 lines not on this page · raw message

tools/perf/util/bpf-filter.h +13 -0
index 818c554b91b2..fda95ff226b3 100644
@@ -14,6 +14,13 @@ struct perf_bpf_filter_expr {
 	int part;
 	enum perf_bpf_filter_term term;
 	unsigned long val;
+	/*
+	 * Raw lock descriptor string for PBF_TERM_LOCK_HELD expressions
+	 * (e.g. "&cgroup_mutex", "mmap_lock", "&dentry", "rwsem:R").
+	 * Resolved into `entry.part` and `entry.target` during
+	 * perf_bpf_filter__prepare().
+	 */
+	char *lock_name;
 };
 
 struct evsel;
@@ -27,6 +34,12 @@ struct perf_bpf_filter_expr *perf_bpf_filter_expr__new(enum perf_bpf_filter_term
 						       int part,
 						       enum perf_bpf_filter_op op,
 						       unsigned long val);
+struct perf_bpf_filter_expr *perf_bpf_filter_expr__new_lock(const char *lock_name,
+							    int mode,
+							    enum perf_bpf_filter_op op,
+							    unsigned long val);
+void perf_bpf_filter_expr__delete(struct perf_bpf_filter_expr *expr);
+int __perf_bpf_filter__parse(struct list_head *expr_head, const char *str);
 int perf_bpf_filter__parse(struct list_head *expr_head, const char *str);
 int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target);
 int perf_bpf_filter__destroy(struct evsel *evsel);
tools/perf/util/bpf-filter.l +29 -2
index 1be9df6550fc..b4022110f1e5 100644
@@ -1,9 +1,12 @@
 %option prefix="perf_bpf_filter_"
 %option noyywrap
 
+%x LOCK_ARG
+
 %{
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 #include <linux/perf_event.h>
 
 #include "bpf-filter.h"
@@ -76,7 +79,7 @@ static int path_or_error(void)
 num_dec		[0-9]+
 num_hex		0[Xx][0-9a-fA-F]+
 space		[ \t]+
-path		[^ \t\n,]+
+path		[^ \t\n,()!=>&|<]+
 ident		[_a-zA-Z][_a-zA-Z0-9]+
 
 %%
@@ -116,7 +119,31 @@ mem_hops	{ return sample_part(PBF_TERM_DATA_SRC, 8); }
 uid		{ return sample(PBF_TERM_UID); }
 gid		{ return sample(PBF_TERM_GID); }
 cgroup		{ return sample_path(PBF_TERM_CGROUP); }
-
+lock_held[ \t]*"("	{
+				BEGIN(LOCK_ARG);
+				perf_bpf_filter_lval.num = PBF_LOCK_MODE_ANY;
+				return BFT_LOCK_HELD;
+			}
+(lock_held_read|lock_held_shared)[ \t]*"("	{
+				BEGIN(LOCK_ARG);
+				perf_bpf_filter_lval.num = PBF_LOCK_MODE_READ;
+				return BFT_LOCK_HELD;
+			}
+(lock_held_write|lock_held_exclusive)[ \t]*"("	{
+				BEGIN(LOCK_ARG);
+				perf_bpf_filter_lval.num = PBF_LOCK_MODE_WRITE;
+				return BFT_LOCK_HELD;
+			}
+
+<LOCK_ARG>{space}	{ }
+<LOCK_ARG>[^ \t\n()]+	{
+				perf_bpf_filter_lval.lock_name = strdup(perf_bpf_filter_text);
+				return BFT_LOCK_NAME;
+			}
+<LOCK_ARG>")"		{ BEGIN(INITIAL); return ')'; }
+<LOCK_ARG>.|\n		{ BEGIN(INITIAL); return BFT_ERROR; }
+
+"!"		{ return '!'; }
 "=="		{ return operator(PBF_OP_EQ); }
 "!="		{ return operator(PBF_OP_NEQ); }
 ">"		{ return operator(PBF_OP_GT); }
tools/perf/util/bpf-filter.y +45 -2

77 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +36 -0
index 683fec85e71e..ca1cf586ed6e 100644
@@ -53,8 +53,44 @@ enum perf_bpf_filter_term {
 	/* Terms computed from BPF helpers. */
 	PBF_TERM_UID,
 	PBF_TERM_GID,
+	/*
+	 * Kernel lock held predicate (`lock_held(...)`). Evaluates whether the
+	 * specified kernel lock is currently held by the running task/CPU.
+	 * The lock specification kind is stored in `entry.part`
+	 * (`enum perf_bpf_lock_target_kind`), `entry.op` is normalized to
+	 * `PBF_OP_EQ` (match when held) or `PBF_OP_NEQ` (match when not held),
+	 * and the resolved target address is stored in `entry.value`.
+	 */
+	PBF_TERM_LOCK_HELD,
 };
 
+/*
+ * Lock target categories for PBF_TERM_LOCK_HELD filters.
+ * Stored in `perf_bpf_filter_entry.part`.
+ */
+enum perf_bpf_lock_target_kind {
+	PBF_LOCK_NONE = 0,
+	/*
+	 * Specific global or static lock address resolved from kallsyms.
+	 * `entry.value` holds the kernel address.
+	 */
+	PBF_LOCK_ADDR,
+};
+
+/*
+ * `perf_bpf_filter_entry.part` layout for PBF_TERM_LOCK_HELD:
+ *   Bits 0..3: `enum perf_bpf_lock_target_kind`
+ *   Bit  4:    PBF_LOCK_MODE_READ      (match read/shared lock holding)
+ *   Bit  5:    PBF_LOCK_MODE_WRITE     (match write/exclusive lock holding)
+ *   Bit  6:    PBF_LOCK_DIRECT_MUTEX   (inspect struct mutex owner)
+ */
+#define PBF_LOCK_KIND_MASK	0x0fU
+#define PBF_LOCK_MODE_READ	(1U << 4)
+#define PBF_LOCK_MODE_WRITE	(1U << 5)
+#define PBF_LOCK_MODE_ANY	(PBF_LOCK_MODE_READ | PBF_LOCK_MODE_WRITE)
+#define PBF_LOCK_MODE_MASK	PBF_LOCK_MODE_ANY
+#define PBF_LOCK_DIRECT_MUTEX	(1U << 6)
+
 /* BPF map entry for filtering */
 struct perf_bpf_filter_entry {
 	enum perf_bpf_filter_op op;
tools/perf/util/bpf_skel/sample_filter.bpf.c +54 -0

80 lines not on this page · raw message

tools/perf/util/parse-events.c +2 -0
index d6bab89ade5d..da687e9d1a67 100644
@@ -2621,6 +2621,8 @@ static bool is_possible_tp_filter(struct evsel *evsel, const char *str)
 {
 	static const char *const bpf_tp_terms[] = {
 		"uid", "gid", "tid", "pid", "cpu", "time", "cgroup",
+		"lock_held", "lock_held_read", "lock_held_shared",
+		"lock_held_write", "lock_held_exclusive",
 	};
 
 	for (size_t i = 0; i < ARRAY_SIZE(bpf_tp_terms); i++) {
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#89 lore raw

Re: [PATCH v6 05/11] perf bpf-filter: Add lock_held() sample filter for global mutexes

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] perf bpf-filter: fix module symbol matching and _edata bound in find_lock_sym_cb() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] perf bpf-filter: fix module symbol matching and _edata bound in find_lock_sym_cb() --

commit 50246e2587ada8982167d48e27c24df7afceb9ec
Author: Ian Rogers <[email protected]>

perf bpf-filter: Add lock_held() sample filter for global mutexes

This commit adds BPF sample filter predicates such as lock_held(<lock>) to record perf event samples only when a specified kernel lock is held or not held. In this initial step, global and static kernel mutex symbols are resolved via /proc/kallsyms and inspected in kernel memory via get_lock_owner().

Quoted 4 lines
tools/perf/util/bpf-filter.c +0 -0
index 0d3c700d3dcd5..639db6c031379 100644

[ ... ]

Quoted 1 line
tools/perf/util/bpf-filter.c +0 -0
@@ -169,9 +178,263 @@ static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr *

[ ... ]

Quoted 38 lines
tools/perf/util/bpf-filter.c +38 -0
+struct lock_sym_cb_args {
+	const char *name;
+	u64 addr;
+	bool in_text;
+	bool in_data;
+	bool found;
+};
+
+static int find_lock_sym_cb(void *arg, const char *name, char type, u64 start)
+{
+	struct lock_sym_cb_args *args = arg;
+
+	if (!strcmp(name, "_text") || !strcmp(name, "_stext") ||
+	    !strcmp(name, "_sinittext")) {
+		args->in_text = true;
+		return 0;
+	}
+	if (!strcmp(name, "_etext") || !strcmp(name, "_einittext")) {
+		args->in_text = false;
+		return 0;
+	}
+	if (!strcmp(name, "_sdata") || !strcmp(name, "__bss_start")) {
+		args->in_text = false;
+		args->in_data = true;
+		return 0;
+	}
+	if (!strcmp(name, "__bss_stop")) {
+		args->in_data = false;
+		return 0;
+	}
+
+	/*
+	 * Ignore kernel text functions, module text functions, and
+	 * absolute/undefined symbols. On CONFIG_LTO_CLANG kernels, vmlinux
+	 * .data symbols between _sdata and _edata may have kallsyms type
+	 * 'T'/'t', so allow 'T'/'t' within vmlinux data/bss (args->in_data).
+	 */
+	if (args->in_text || type == 'A' || type == 'a' ||

tools/perf/util/bpf-filter.c static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr * · line 274

Quoted 10 lines
tools/perf/util/bpf-filter.c +10 -0
+	    type == 'U' || type == 'u' ||
+	    (!args->in_data && kallsyms__is_function(type)))
+		return 0;
+
+	if (!strcmp(name, args->name)) {
+		args->found = true;
+		args->addr = start;
+		if (start != 0)
+			return 1;
+	}

[Severity: Medium]
When resolving a lock symbol through the call chain:

perf_bpf_filter__prepare()

    -> get_filter_entries()
      -> resolve_lock_expr()
        -> find_kernel_lock_sym()
          -> kallsyms__parse(..., find_lock_sym_cb)

there appear to be two symbol resolution issues in find_lock_sym_cb() in tools/perf/util/bpf-filter.c:

First, in tools/lib/symbol/kallsyms.c, kallsyms__parse() reads each symbol name up to the newline character:

	for (i = 0; i < KSYM_NAME_LEN; i++) {
		ch = io__get_char(&io);
		if (ch < 0 || ch == '\n')
			break;
		symbol_name[i]  = ch;
	}
	symbol_name[i]  = '\0';

In /proc/kallsyms, module symbols are formatted with a trailing module name suffix ("\t[<module>]"). Because find_lock_sym_cb() compares names using !strcmp(name, args->name), will lock symbols residing in loaded kernel modules always fail to match? Other kallsyms callbacks such as kern_sym_name_match() in tools/perf/util/auxtrace.c handle this by allowing a tab delimiter after the symbol name:

static bool kern_sym_name_match(const char *kname, const char *name)

{
	size_t n = strlen(name);

	return !strcmp(kname, name) ||
	       (!strncmp(kname, name, n) && kname[n] == '\t');
}

Second, find_lock_sym_cb() sets args->in_data = true at both _sdata and __bss_start, and the comment notes that .data symbols between _sdata and _edata may have type 'T' or 't'. However, only __bss_stop resets args->in_data to false. Should _edata also reset args->in_data = false so that sections between _edata and __bss_start (such as .exit.text outside _sinittext.._einittext) are not treated as vmlinux data/bss?

Quoted 2 lines
tools/perf/util/bpf-filter.c +2 -0
+	return 0;
+}

[ ... ]

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

Re: [PATCH v6 05/11] perf bpf-filter: Add lock_held() sample filter for global mutexes

In reply to Ian Rogers
Quoted 327 lines · Ian Rogers

Add BPF sample filter predicates lock_held(<lock>), lock_held_read(<lock>) / lock_held_shared(<lock>), and lock_held_write(<lock>) / lock_held_exclusive(<lock>) (as well as ':R' and ':W' suffixes on <lock>) to allow recording perf event samples only when a specified kernel lock is held (or not held with '!').

In this initial step, support global/static kernel mutex symbols (e.g. lock_held(cgroup_mutex)) resolved via /proc/kallsyms. On sample overflow, perf_sample_filter and perf_tp_sample_filter inspect the mutex's owner field directly in kernel memory via get_lock_owner() without attaching any BPF fentry/fexit hooks.

Subsequent commits extend lock_held() to other kernel lock types, per-process and semi-global locks, slab cache locks, and RCU/SRCU.

---
 tools/perf/Documentation/perf-record.txt     |  16 +-
 tools/perf/util/bpf-filter.c                 | 350 ++++++++++++++++++-
 tools/perf/util/bpf-filter.h                 |  13 +
 tools/perf/util/bpf-filter.l                 |  31 +-
 tools/perf/util/bpf-filter.y                 |  47 ++-
 tools/perf/util/bpf_skel/sample-filter.h     |  36 ++
 tools/perf/util/bpf_skel/sample_filter.bpf.c |  54 +++
 tools/perf/util/parse-events.c               |   2 +
 8 files changed, 530 insertions(+), 19 deletions(-)
tools/perf/Documentation/perf-record.txt +15 -1
index fcf1ea62bf1c..445cc98a6c33 100644
@@ -210,7 +210,21 @@ OPTIONS
 	  ip, id, tid, pid, cpu, time, addr, period, txn, weight, phys_addr,
 	  code_pgsz, data_pgsz, weight1, weight2, weight3, ins_lat, retire_lat,
 	  p_stage_cyc, mem_op, mem_lvl, mem_snoop, mem_remote, mem_lock,
-	  mem_dtlb, mem_blk, mem_hops, uid, gid
+	  mem_dtlb, mem_blk, mem_hops, uid, gid, cgroup, lock_held(<lock>),
+	  lock_held_read(<lock>), lock_held_shared(<lock>),
+	  lock_held_write(<lock>), lock_held_exclusive(<lock>)
+
+	The 'lock_held(<lock>)' predicate (or '!lock_held(<lock>)') filters
+	samples based on whether the specified kernel lock is currently held
+	by the kernel thread.  To differentiate between shared/read holding
+	and exclusive/write holding, use 'lock_held_read(<lock>)' (alias
+	'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)' (alias
+	'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to <lock>.
+	<lock> can be a kernel mutex symbol name (e.g.
+	'lock_held(cgroup_mutex)').  When filtering on a mutex symbol
+	('*_mutex'), 'perf_sample_filter' inspects the lock's 'owner' field
+	directly in kernel memory on each sample without attaching any BPF
+	fentry/fexit hooks.
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +235 -1
index 0d3c700d3dcd..639db6c03137 100644
@@ -43,6 +43,9 @@
 #include <errno.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <string.h>
 #include <fcntl.h>
 #include <unistd.h>
 #include <sys/ioctl.h>
@@ -50,14 +53,19 @@
 
 #include <bpf/bpf.h>
 #include <linux/err.h>
+#include <linux/kernel.h>
 #include <linux/list.h>
+#include <linux/string.h>
+#include <linux/zalloc.h>
 #include <api/fs/fs.h>
 #include <internal/xyarray.h>
 #include <perf/threadmap.h>
+#include <symbol/kallsyms.h>
 
 #include "util/cap.h"
 #include "util/debug.h"
 #include "util/evsel.h"
+#include "util/symbol_conf.h"
 #include "util/target.h"
 #include "util/thread_map.h"
 #include "util/bpf-utils.h"
@@ -126,7 +134,8 @@ static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr *
 {
 	const struct perf_sample_info *info;
 
-	if (expr->term == PBF_TERM_UID || expr->term == PBF_TERM_GID) {
+	if (expr->term == PBF_TERM_UID || expr->term == PBF_TERM_GID ||
+	    expr->term == PBF_TERM_LOCK_HELD) {
 		/* Not dependent on the sample_type as computed from a BPF helper. */
 		return 0;
 	}
@@ -169,9 +178,263 @@ static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr *
 	return -1;
 }
 
+static int split_lock_name_mode(const char *name, int expr_part,
+				char *base_buf, size_t buf_sz,
+				bool *has_amp, unsigned int *mode_out)
+{
+	const char *bare;
+	size_t len;
+	unsigned int expr_mode = expr_part & PBF_LOCK_MODE_MASK;
+	unsigned int suffix_mode = 0;
+
+	if (!name || !*name)
+		return -EINVAL;
+
+	*has_amp = (name[0] == '&');
+	bare = *has_amp ? name + 1 : name;
+	len = strlen(bare);
+	if (len == 0)
+		return -EINVAL;
+
+	if (len > 2 && !strcmp(bare + len - 2, ":R")) {
+		suffix_mode = PBF_LOCK_MODE_READ;
+		len -= 2;
+	} else if (len > 2 && !strcmp(bare + len - 2, ":W")) {
+		suffix_mode = PBF_LOCK_MODE_WRITE;
+		len -= 2;
+	}
+
+	if (len == 0 || len >= buf_sz)
+		return -EINVAL;
+
+	if (expr_mode && expr_mode != PBF_LOCK_MODE_ANY &&
+	    suffix_mode && expr_mode != suffix_mode)
+		return -EINVAL;
+
+	memcpy(base_buf, bare, len);
+	base_buf[len] = '\0';
+
+	if (suffix_mode)
+		*mode_out = suffix_mode;
+	else if (expr_mode)
+		*mode_out = expr_mode;
+	else
+		*mode_out = PBF_LOCK_MODE_ANY;
+
+	return 0;
+}
+
+struct lock_sym_cb_args {
+	const char *name;
+	u64 addr;
+	bool in_text;
+	bool in_data;
+	bool found;
+};
+
+static int find_lock_sym_cb(void *arg, const char *name, char type, u64 start)
+{
+	struct lock_sym_cb_args *args = arg;
+
+	if (!strcmp(name, "_text") || !strcmp(name, "_stext") ||
+	    !strcmp(name, "_sinittext")) {
+		args->in_text = true;
+		return 0;
+	}
+	if (!strcmp(name, "_etext") || !strcmp(name, "_einittext")) {
+		args->in_text = false;
+		return 0;
+	}
+	if (!strcmp(name, "_sdata") || !strcmp(name, "__bss_start")) {
+		args->in_text = false;
+		args->in_data = true;
+		return 0;
+	}
+	if (!strcmp(name, "__bss_stop")) {
+		args->in_data = false;
+		return 0;
+	}
+
+	/*
+	 * Ignore kernel text functions, module text functions, and
+	 * absolute/undefined symbols. On CONFIG_LTO_CLANG kernels, vmlinux
+	 * .data symbols between _sdata and _edata may have kallsyms type
+	 * 'T'/'t', so allow 'T'/'t' within vmlinux data/bss (args->in_data).
+	 */
+	if (args->in_text || type == 'A' || type == 'a' ||
+	    type == 'U' || type == 'u' ||
+	    (!args->in_data && kallsyms__is_function(type)))
+		return 0;
+
+	if (!strcmp(name, args->name)) {
+		args->found = true;
+		args->addr = start;
+		if (start != 0)
+			return 1;
+	}
+	return 0;
+}
+
+static int find_kernel_lock_sym(const char *name, u64 *addr)
+{
+	struct lock_sym_cb_args args = {
+		.name = name,
+	};
+	const char *kallsyms_filename = "/proc/kallsyms";
+
+	if (symbol_conf.kallsyms_name != NULL)
+		kallsyms_filename = symbol_conf.kallsyms_name;
+
+	if (kallsyms__parse(kallsyms_filename, &args, find_lock_sym_cb) < 0)
+		return -ENOENT;
+
+	if (!args.found)
+		return -ENOENT;
+
+	if (args.addr == 0) {
+		pr_err("Error: Kernel symbol '%s' address is 0 (check permissions / kptr_restrict)\n",
+		       name);
+		return -EACCES;
+	}
+
+	*addr = args.addr;
+	return 0;
+}
+
+static void prescan_one_lock_expr(struct perf_bpf_filter_expr *expr,
+				  bool *has_lock_filter)
+{
+	if (expr->term != PBF_TERM_LOCK_HELD || !expr->lock_name)
+		return;
+
+	*has_lock_filter = true;
+}
+
+static void prescan_lock_filters(struct evsel *evsel, bool *has_lock_filter)
+{
+	struct perf_bpf_filter_expr *expr, *group;
+
+	*has_lock_filter = false;
+
+	list_for_each_entry(expr, &evsel->bpf_filters, list) {
+		prescan_one_lock_expr(expr, has_lock_filter);
+		if (expr->op == PBF_OP_GROUP_BEGIN) {
+			list_for_each_entry(group, &expr->groups, list)
+				prescan_one_lock_expr(group, has_lock_filter);
+		}
+	}
+}
+
+static int normalize_lock_expr_op(const struct perf_bpf_filter_expr *expr,
+				  enum perf_bpf_filter_op *op_out)
+{
+	switch (expr->op) {
+	case PBF_OP_EQ:
+		if (expr->val == 1) {
+			*op_out = PBF_OP_EQ;
+			return 0;
+		}
+		if (expr->val == 0) {
+			*op_out = PBF_OP_NEQ;
+			return 0;
+		}
+		break;
+	case PBF_OP_NEQ:
+		if (expr->val == 0) {
+			*op_out = PBF_OP_EQ;
+			return 0;
+		}
+		if (expr->val == 1) {
+			*op_out = PBF_OP_NEQ;
+			return 0;
+		}
+		break;
+	case PBF_OP_GT:
+		if (expr->val == 0) {
+			*op_out = PBF_OP_EQ;
+			return 0;
+		}
+		break;
+	case PBF_OP_GE:
+		if (expr->val == 1) {
+			*op_out = PBF_OP_EQ;
+			return 0;
+		}
+		break;
+	case PBF_OP_LT:
+		if (expr->val == 1) {
+			*op_out = PBF_OP_NEQ;
+			return 0;
+		}
+		break;
+	case PBF_OP_LE:
+		if (expr->val == 0) {
+			*op_out = PBF_OP_NEQ;
+			return 0;
+		}
+		break;
+	case PBF_OP_AND:
+		if (expr->val & 1) {
+			*op_out = PBF_OP_EQ;
+			return 0;
+		}
+		break;
+	case PBF_OP_GROUP_BEGIN:
+	case PBF_OP_GROUP_END:
+	case PBF_OP_DONE:
+	default:
+		break;
+	}
+	pr_err("Error: Invalid comparison for boolean lock_held(%s) predicate\n",
+	       expr->lock_name ?: "");
+	return -EINVAL;
+}
+
+static int resolve_lock_expr(struct perf_bpf_filter_expr *expr,
+			     struct perf_bpf_filter_entry *entry)
+{
+	const char *name = expr->lock_name;
+	char base[128];
+	bool has_amp;
+	unsigned int mode;
+	u64 addr = 0;
+	int ret;
+
+	ret = normalize_lock_expr_op(expr, &entry->op);
+	if (ret < 0)
+		return ret;

tools/perf/util/bpf-filter.c static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr * · line 415

Quoted 10 lines
tools/perf/util/bpf-filter.c +10 -0
+
+	if (split_lock_name_mode(name, expr->part, base, sizeof(base),
+				 &has_amp, &mode) < 0 || has_amp) {
+		pr_err("Error: Invalid kernel lock filter '%s'\n", name ?: "");
+		return -EINVAL;
+	}
+
+	if (str_ends_with(base, "mutex") &&
+	    !str_ends_with(base, "rt_mutex") &&
+	    !str_ends_with(base, "rtmutex")) {

Is it just checking the symbol name ends with "mutex" or so? It seems risky and limited, can we check BTF to verify if it's really a mutex?

Thanks,
Namhyung

Quoted 519 lines
tools/perf/util/bpf-filter.c +91 -13
+		ret = find_kernel_lock_sym(base, &addr);
+		if (ret == 0) {
+			if (!(mode & PBF_LOCK_MODE_WRITE)) {
+				pr_err("Error: Lock '%s' is exclusive and does not support read/shared mode\n",
+				       name);
+				return -EINVAL;
+			}
+			entry->part = PBF_LOCK_ADDR | mode | PBF_LOCK_DIRECT_MUTEX;
+			entry->value = addr;
+			return 0;
+		}
+		if (ret == -EACCES)
+			return ret;
+	}
+
+	pr_err("Error: Cannot resolve kernel lock '%s'\n", name);
+	return -EINVAL;
+}
+
 static int get_filter_entries(struct evsel *evsel, struct perf_bpf_filter_entry *entry)
 {
-	int i = 0;
+	int i = 0, ret;
 	struct perf_bpf_filter_expr *expr;
 
 	list_for_each_entry(expr, &evsel->bpf_filters, list) {
@@ -185,6 +448,11 @@ static int get_filter_entries(struct evsel *evsel, struct perf_bpf_filter_entry
 		entry[i].part = expr->part;
 		entry[i].term = expr->term;
 		entry[i].value = expr->val;
+		if (expr->term == PBF_TERM_LOCK_HELD) {
+			ret = resolve_lock_expr(expr, &entry[i]);
+			if (ret < 0)
+				return ret;
+		}
 		i++;
 
 		if (expr->op == PBF_OP_GROUP_BEGIN) {
@@ -198,6 +466,11 @@ static int get_filter_entries(struct evsel *evsel, struct perf_bpf_filter_entry
 				entry[i].part = group->part;
 				entry[i].term = group->term;
 				entry[i].value = group->val;
+				if (group->term == PBF_TERM_LOCK_HELD) {
+					ret = resolve_lock_expr(group, &entry[i]);
+					if (ret < 0)
+						return ret;
+				}
 				i++;
 			}
 
@@ -440,20 +713,24 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 	struct perf_bpf_filter_entry *entry;
 	bool needs_idx_hash = !target__has_cpu(target);
 	bool is_tracepoint = (evsel->core.attr.type == PERF_TYPE_TRACEPOINT);
+	bool has_lock_filter = false;
 
 	entry = calloc(MAX_FILTERS, sizeof(*entry));
 	if (entry == NULL)
 		return -1;
 
-	ret = get_filter_entries(evsel, entry);
-	if (ret < 0) {
-		pr_err("Failed to process filter entries\n");
+	prescan_lock_filters(evsel, &has_lock_filter);
+
+	if ((has_lock_filter || is_tracepoint) && geteuid() != 0 &&
+	    !perf_cap__capable(CAP_BPF)) {
+		pr_err("Error: BPF filter requires CAP_BPF capability\n");
+		ret = -EPERM;
 		goto err;
 	}
 
-	if (is_tracepoint && geteuid() != 0 && !perf_cap__capable(CAP_BPF)) {
-		pr_err("Error: Tracepoint BPF filter requires CAP_BPF capability\n");
-		ret = -EPERM;
+	ret = get_filter_entries(evsel, entry);
+	if (ret < 0) {
+		pr_err("Failed to process filter entries\n");
 		goto err;
 	}
 
@@ -513,6 +790,9 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		goto err;
 	}
 
+	if (has_lock_filter)
+		skel->bss->lock_enabled = 1;
+
 	i = 0;
 	fd = bpf_map__fd(skel->maps.filters);
 
@@ -571,6 +851,21 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 	return ret;
 }
 
+void perf_bpf_filter_expr__delete(struct perf_bpf_filter_expr *expr)
+{
+	struct perf_bpf_filter_expr *group, *tmp;
+
+	if (!expr)
+		return;
+
+	list_for_each_entry_safe(group, tmp, &expr->groups, list) {
+		list_del(&group->list);
+		perf_bpf_filter_expr__delete(group);
+	}
+	zfree(&expr->lock_name);
+	free(expr);
+}
+
 int perf_bpf_filter__destroy(struct evsel *evsel)
 {
 	struct perf_bpf_filter_expr *expr, *tmp;
@@ -578,7 +873,7 @@ int perf_bpf_filter__destroy(struct evsel *evsel)
 
 	list_for_each_entry_safe(expr, tmp, &evsel->bpf_filters, list) {
 		list_del(&expr->list);
-		free(expr);
+		perf_bpf_filter_expr__delete(expr);
 	}
 	sample_filter_bpf__destroy(evsel->bpf_skel);
 
@@ -630,7 +925,7 @@ struct perf_bpf_filter_expr *perf_bpf_filter_expr__new(enum perf_bpf_filter_term
 {
 	struct perf_bpf_filter_expr *expr;
 
-	expr = malloc(sizeof(*expr));
+	expr = zalloc(sizeof(*expr));
 	if (expr != NULL) {
 		expr->term = term;
 		expr->part = part;
@@ -641,6 +936,28 @@ struct perf_bpf_filter_expr *perf_bpf_filter_expr__new(enum perf_bpf_filter_term
 	return expr;
 }
 
+struct perf_bpf_filter_expr *perf_bpf_filter_expr__new_lock(const char *lock_name,
+							    int mode,
+							    enum perf_bpf_filter_op op,
+							    unsigned long val)
+{
+	struct perf_bpf_filter_expr *expr;
+
+	if (!lock_name || !*lock_name)
+		return NULL;
+
+	expr = perf_bpf_filter_expr__new(PBF_TERM_LOCK_HELD, mode, op, val);
+	if (!expr)
+		return NULL;
+
+	expr->lock_name = strdup(lock_name);
+	if (!expr->lock_name) {
+		free(expr);
+		return NULL;
+	}
+	return expr;
+}
+
 static bool check_bpf_filter_capable(void)
 {
 	int fd;
@@ -661,14 +978,11 @@ static bool check_bpf_filter_capable(void)
 	return false;
 }
 
-int perf_bpf_filter__parse(struct list_head *expr_head, const char *str)
+int __perf_bpf_filter__parse(struct list_head *expr_head, const char *str)
 {
 	YY_BUFFER_STATE buffer;
 	int ret;
 
-	if (!check_bpf_filter_capable())
-		return -EPERM;
-
 	buffer = perf_bpf_filter__scan_string(str);
 
 	ret = perf_bpf_filter_parse(expr_head);
@@ -680,6 +994,14 @@ int perf_bpf_filter__parse(struct list_head *expr_head, const char *str)
 	return ret;
 }
 
+int perf_bpf_filter__parse(struct list_head *expr_head, const char *str)
+{
+	if (!check_bpf_filter_capable())
+		return -EPERM;
+
+	return __perf_bpf_filter__parse(expr_head, str);
+}
+
 /*
  * perf_bpf_filter__pin() and perf_bpf_filter__unpin() only load
  * perf_sample_filter and disable autoload on other programs in the skeleton
tools/perf/util/bpf-filter.h +13 -0
index 818c554b91b2..fda95ff226b3 100644
@@ -14,6 +14,13 @@ struct perf_bpf_filter_expr {
 	int part;
 	enum perf_bpf_filter_term term;
 	unsigned long val;
+	/*
+	 * Raw lock descriptor string for PBF_TERM_LOCK_HELD expressions
+	 * (e.g. "&cgroup_mutex", "mmap_lock", "&dentry", "rwsem:R").
+	 * Resolved into `entry.part` and `entry.target` during
+	 * perf_bpf_filter__prepare().
+	 */
+	char *lock_name;
 };
 
 struct evsel;
@@ -27,6 +34,12 @@ struct perf_bpf_filter_expr *perf_bpf_filter_expr__new(enum perf_bpf_filter_term
 						       int part,
 						       enum perf_bpf_filter_op op,
 						       unsigned long val);
+struct perf_bpf_filter_expr *perf_bpf_filter_expr__new_lock(const char *lock_name,
+							    int mode,
+							    enum perf_bpf_filter_op op,
+							    unsigned long val);
+void perf_bpf_filter_expr__delete(struct perf_bpf_filter_expr *expr);
+int __perf_bpf_filter__parse(struct list_head *expr_head, const char *str);
 int perf_bpf_filter__parse(struct list_head *expr_head, const char *str);
 int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target);
 int perf_bpf_filter__destroy(struct evsel *evsel);
tools/perf/util/bpf-filter.l +29 -2
index 1be9df6550fc..b4022110f1e5 100644
@@ -1,9 +1,12 @@
 %option prefix="perf_bpf_filter_"
 %option noyywrap
 
+%x LOCK_ARG
+
 %{
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 #include <linux/perf_event.h>
 
 #include "bpf-filter.h"
@@ -76,7 +79,7 @@ static int path_or_error(void)
 num_dec		[0-9]+
 num_hex		0[Xx][0-9a-fA-F]+
 space		[ \t]+
-path		[^ \t\n,]+
+path		[^ \t\n,()!=>&|<]+
 ident		[_a-zA-Z][_a-zA-Z0-9]+
 
 %%
@@ -116,7 +119,31 @@ mem_hops	{ return sample_part(PBF_TERM_DATA_SRC, 8); }
 uid		{ return sample(PBF_TERM_UID); }
 gid		{ return sample(PBF_TERM_GID); }
 cgroup		{ return sample_path(PBF_TERM_CGROUP); }
-
+lock_held[ \t]*"("	{
+				BEGIN(LOCK_ARG);
+				perf_bpf_filter_lval.num = PBF_LOCK_MODE_ANY;
+				return BFT_LOCK_HELD;
+			}
+(lock_held_read|lock_held_shared)[ \t]*"("	{
+				BEGIN(LOCK_ARG);
+				perf_bpf_filter_lval.num = PBF_LOCK_MODE_READ;
+				return BFT_LOCK_HELD;
+			}
+(lock_held_write|lock_held_exclusive)[ \t]*"("	{
+				BEGIN(LOCK_ARG);
+				perf_bpf_filter_lval.num = PBF_LOCK_MODE_WRITE;
+				return BFT_LOCK_HELD;
+			}
+
+<LOCK_ARG>{space}	{ }
+<LOCK_ARG>[^ \t\n()]+	{
+				perf_bpf_filter_lval.lock_name = strdup(perf_bpf_filter_text);
+				return BFT_LOCK_NAME;
+			}
+<LOCK_ARG>")"		{ BEGIN(INITIAL); return ')'; }
+<LOCK_ARG>.|\n		{ BEGIN(INITIAL); return BFT_ERROR; }
+
+"!"		{ return '!'; }
 "=="		{ return operator(PBF_OP_EQ); }
 "!="		{ return operator(PBF_OP_NEQ); }
 ">"		{ return operator(PBF_OP_GT); }
tools/perf/util/bpf-filter.y +45 -2
index 5a79a8e7a45b..5ae05d4608c6 100644
@@ -8,9 +8,11 @@
 #endif
 
 #include <stdio.h>
+#include <stdlib.h>
 #include <string.h>
 #include <linux/compiler.h>
 #include <linux/list.h>
+#include <linux/zalloc.h>
 #include "bpf-filter.h"
 #include "cgroup.h"
 
@@ -31,6 +33,11 @@ static void perf_bpf_filter_error(struct list_head *expr __maybe_unused,
 {
 	unsigned long num;
 	char *path;
+	char *lock_name;
+	struct {
+		char *name;
+		int mode;
+	} lock;
 	struct {
 		enum perf_bpf_filter_term term;
 		int part;
@@ -40,12 +47,17 @@ static void perf_bpf_filter_error(struct list_head *expr __maybe_unused,
 }
 
 %token BFT_SAMPLE BFT_SAMPLE_PATH BFT_OP BFT_ERROR BFT_NUM BFT_LOGICAL_OR BFT_PATH
+%token BFT_LOCK_HELD BFT_LOCK_NAME
 %type <expr> filter_term filter_expr
-%destructor { free ($$); } <expr>
+%destructor { perf_bpf_filter_expr__delete($$); } <expr>
+%destructor { free($$); } <lock_name>
+%destructor { free($$.name); } <lock>
 %type <sample> BFT_SAMPLE BFT_SAMPLE_PATH
 %type <op> BFT_OP
-%type <num> BFT_NUM
+%type <num> BFT_NUM BFT_LOCK_HELD
 %type <path> BFT_PATH
+%type <lock_name> BFT_LOCK_NAME
+%type <lock> lock_term
 
 %%
 
@@ -105,5 +117,36 @@ BFT_SAMPLE_PATH BFT_OP BFT_PATH
 	$$ = perf_bpf_filter_expr__new($1.term, $1.part, $2, cgroup_id);
 	cgroup__put(cgrp);
 }
+|
+lock_term
+{
+	$$ = perf_bpf_filter_expr__new_lock($1.name, $1.mode, PBF_OP_EQ, 1);
+	zfree(&$1.name);
+	if (!$$)
+		YYERROR;
+}
+|
+'!' lock_term
+{
+	$$ = perf_bpf_filter_expr__new_lock($2.name, $2.mode, PBF_OP_EQ, 0);
+	zfree(&$2.name);
+	if (!$$)
+		YYERROR;
+}
+|
+lock_term BFT_OP BFT_NUM
+{
+	$$ = perf_bpf_filter_expr__new_lock($1.name, $1.mode, $2, $3);
+	zfree(&$1.name);
+	if (!$$)
+		YYERROR;
+}
+
+lock_term:
+BFT_LOCK_HELD BFT_LOCK_NAME ')'
+{
+	$$.name = $2;
+	$$.mode = $1;
+}
 
 %%
tools/perf/util/bpf_skel/sample-filter.h +36 -0
index 683fec85e71e..ca1cf586ed6e 100644
@@ -53,8 +53,44 @@ enum perf_bpf_filter_term {
 	/* Terms computed from BPF helpers. */
 	PBF_TERM_UID,
 	PBF_TERM_GID,
+	/*
+	 * Kernel lock held predicate (`lock_held(...)`). Evaluates whether the
+	 * specified kernel lock is currently held by the running task/CPU.
+	 * The lock specification kind is stored in `entry.part`
+	 * (`enum perf_bpf_lock_target_kind`), `entry.op` is normalized to
+	 * `PBF_OP_EQ` (match when held) or `PBF_OP_NEQ` (match when not held),
+	 * and the resolved target address is stored in `entry.value`.
+	 */
+	PBF_TERM_LOCK_HELD,
 };
 
+/*
+ * Lock target categories for PBF_TERM_LOCK_HELD filters.
+ * Stored in `perf_bpf_filter_entry.part`.
+ */
+enum perf_bpf_lock_target_kind {
+	PBF_LOCK_NONE = 0,
+	/*
+	 * Specific global or static lock address resolved from kallsyms.
+	 * `entry.value` holds the kernel address.
+	 */
+	PBF_LOCK_ADDR,
+};
+
+/*
+ * `perf_bpf_filter_entry.part` layout for PBF_TERM_LOCK_HELD:
+ *   Bits 0..3: `enum perf_bpf_lock_target_kind`
+ *   Bit  4:    PBF_LOCK_MODE_READ      (match read/shared lock holding)
+ *   Bit  5:    PBF_LOCK_MODE_WRITE     (match write/exclusive lock holding)
+ *   Bit  6:    PBF_LOCK_DIRECT_MUTEX   (inspect struct mutex owner)
+ */
+#define PBF_LOCK_KIND_MASK	0x0fU
+#define PBF_LOCK_MODE_READ	(1U << 4)
+#define PBF_LOCK_MODE_WRITE	(1U << 5)
+#define PBF_LOCK_MODE_ANY	(PBF_LOCK_MODE_READ | PBF_LOCK_MODE_WRITE)
+#define PBF_LOCK_MODE_MASK	PBF_LOCK_MODE_ANY
+#define PBF_LOCK_DIRECT_MUTEX	(1U << 6)
+
 /* BPF map entry for filtering */
 struct perf_bpf_filter_entry {
 	enum perf_bpf_filter_op op;
tools/perf/util/bpf_skel/sample_filter.bpf.c +54 -0
index a190374ed87a..42556ab0e2d5 100644
@@ -5,6 +5,7 @@
 #include <bpf/bpf_tracing.h>
 #include <bpf/bpf_core_read.h>
 
+#include "lock_data.h"
 #include "sample-filter.h"
 
 /* BPF map that will be filled by user space */
@@ -45,8 +46,57 @@ struct lost_count {
 
 volatile const int use_idx_hash;
 
+/* Control flag set by userspace when lock_held(...) filters are active. */
+int lock_enabled;
+
 void *bpf_cast_to_kern_ctx(void *) __ksym;
 
+static __always_inline bool is_direct_lock_owner(__u64 lock_addr, __u64 curr, __u32 part)
+{
+	if (!curr)
+		return false;
+
+	if ((part & PBF_LOCK_DIRECT_MUTEX) &&
+	    (__u64)get_lock_owner(lock_addr, LCB_F_MUTEX) == curr)
+		return true;
+	return false;
+}
+
+static __always_inline bool is_lock_held(struct perf_bpf_filter_entry *entry)
+{
+	__u64 curr = bpf_get_current_task();
+	__u32 kind = entry->part & PBF_LOCK_KIND_MASK;
+	__u32 mode = entry->part & PBF_LOCK_MODE_MASK;
+
+	if (!mode)
+		mode = PBF_LOCK_MODE_ANY;
+
+	switch (kind) {
+	case PBF_LOCK_ADDR:
+		if ((mode & PBF_LOCK_MODE_WRITE) &&
+		    is_direct_lock_owner(entry->value, curr, entry->part))
+			return true;
+		return false;
+
+	default:
+		return false;
+	}
+}
+
+static __always_inline __u64 check_lock_held(struct perf_bpf_filter_entry *entry)
+{
+	/*
+	 * Pinned filters (use_idx_hash != 0) share a world-writable filters
+	 * map and do not support lock_held(). Reject evaluation when pinned
+	 * or when lock_enabled is not set so unprivileged users cannot probe
+	 * arbitrary kernel addresses via entry->value.
+	 */
+	if (use_idx_hash || !lock_enabled)
+		return entry->op == PBF_OP_EQ ? ~entry->value : entry->value;
+
+	return is_lock_held(entry) ? entry->value : ~entry->value;
+}
+
 /* new kernel perf_sample_data definition */
 struct perf_sample_data___new {
 	__u64 sample_flags;
@@ -175,6 +225,8 @@ static inline __u64 perf_get_sample(struct bpf_perf_event_data_kern *kctx,
 		return bpf_get_current_uid_gid() & 0xFFFFFFFF;
 	case PBF_TERM_GID:
 		return bpf_get_current_uid_gid() >> 32;
+	case PBF_TERM_LOCK_HELD:
+		return check_lock_held(entry);
 	case PBF_TERM_NONE:
 	case __PBF_UNUSED_TERM4:
 	case __PBF_UNUSED_TERM5:
@@ -209,6 +261,8 @@ static __always_inline __u64 perf_get_common_sample(struct perf_bpf_filter_entry
 		return bpf_get_current_uid_gid() & 0xFFFFFFFF;
 	case PBF_TERM_GID:
 		return bpf_get_current_uid_gid() >> 32;
+	case PBF_TERM_LOCK_HELD:
+		return check_lock_held(entry);
 	default:
 		return 0;
 	}
tools/perf/util/parse-events.c +2 -0
index d6bab89ade5d..da687e9d1a67 100644
@@ -2621,6 +2621,8 @@ static bool is_possible_tp_filter(struct evsel *evsel, const char *str)
 {
 	static const char *const bpf_tp_terms[] = {
 		"uid", "gid", "tid", "pid", "cpu", "time", "cgroup",
+		"lock_held", "lock_held_read", "lock_held_shared",
+		"lock_held_write", "lock_held_exclusive",
 	};
 
 	for (size_t i = 0; i < ARRAY_SIZE(bpf_tp_terms); i++) {
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
author reviewer
#91 lore raw

Re: [PATCH v6 05/11] perf bpf-filter: Add lock_held() sample filter for global mutexes

Quoted 2 lines · Namhyung Kim

On Thu, Oct 22, 2026 at 01:29:57PM -0700, Ian Rogers wrote:

[snip]

Quoted 18 lines
Quoted 18 lines
tools/perf/util/bpf-filter.c +18 -0
+static int resolve_lock_expr(struct perf_bpf_filter_expr *expr,
+                          struct perf_bpf_filter_entry *entry)
+{
+     const char *name = expr->lock_name;
+     char base[128];
+     bool has_amp;
+     unsigned int mode;
+     u64 addr = 0;
+     int ret;
+
+     ret = normalize_lock_expr_op(expr, &entry->op);
+     if (ret < 0)
+             return ret;
+
+     if (split_lock_name_mode(name, expr->part, base, sizeof(base),
+                              &has_amp, &mode) < 0 || has_amp) {
+             pr_err("Error: Invalid kernel lock filter '%s'\n", name ?: "");
+             return -EINVAL;
Quoted 8 lines

tools/perf/util/bpf-filter.c static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr * · line 415

Quoted 5 lines
tools/perf/util/bpf-filter.c +5 -0
+     }
+
+     if (str_ends_with(base, "mutex") &&
+         !str_ends_with(base, "rt_mutex") &&
+         !str_ends_with(base, "rtmutex")) {

Is it just checking the symbol name ends with "mutex" or so? It seems risky and limited, can we check BTF to verify if it's really a mutex?

Agreed, a suffix check is only a heuristic. The catch is that kallsyms gives an address for a global or static variable but not its type. And vmlinux BTF normally only has BTF_KIND_VAR entries for per-CPU
variables: scripts/Makefile.btf passes "--btf_features=...,var,..." but not "global_var". So on most kernels there's no BTF type for something like cgroup_mutex to check.

Patch 6 in this series adds classify_lock_sym(), which uses BTF where it can and falls back to the name suffix otherwise. It checks:
1. for a __percpu_rwsem_rc_<name> BTF var. DEFINE_PERCPU_RWSEM() always emits one, and as a per-CPU variable it's always in BTF;
2. the symbol's BTF_KIND_VAR type (struct mutex, rt_mutex, rw_semaphore, semaphore, ...), when the kernel was built with global variables in BTF;
3. otherwise, the name suffix.

In any case a wrong guess is harmless. The direct owner check only reads lock->owner with bpf_probe_read_kernel(), and only at an address already confirmed to be in kernel .data/.bss (function symbols are rejected via kallsyms and BTF). The worst case is that the filter doesn't match.

Patch 5 adding a suffix check that patch 6 then replaces isn't intuitive, so in the next version I'll move classify_lock_sym() into patch 5 and use it from the start.

Thanks,
Ian

Quoted 2 lines

Thanks,
Namhyung

author reviewer
#92 lore raw

PATCH v6 6/11 perf bpf-filter: Extend lock_held() to other kernel lock types

In reply to Ian Rogers

Extend the lock_held() BPF sample filter beyond global mutexes to support:
- Other global/static kernel lock symbols (rwsem, spinlock, rwlock, rt-mutex, percpu-rwsem, semaphore) and hexadecimal kernel lock addresses.
- Lock types and flags: mutex, spinlock, rwsem, rwsem:R, rwsem:W, rwlock, rwlock:R, rwlock:W, rt-mutex, percpu-rwsem, pcpu-sem:W, semaphore.

For rt-mutexes and write-locked rwsems, perf_sample_filter inspects the lock's owner field directly in kernel memory. For locks and modes without an authoritative per-task owner pointer (spinlocks, rwlocks, semaphores, reader-locked rwsems, percpu-rwsems, and lock type filters), attach BPF fentry/fexit hooks on kernel lock acquire and release functions to track held locks in the held_locks BPF LRU hash map.

Note that counting semaphores (down*() / up()) do not enforce same-task ownership in the kernel: when a semaphore is used as a cross-task completion/signaling mechanism, fexit/down and fentry/up will not pair on the same task ID. Semaphore hooks are therefore only enabled when 'semaphore' or a '*_sem' symbol (such as console_sem) is explicitly specified, and held_locks uses BPF_MAP_TYPE_LRU_HASH so any unpaired cross-task entries are automatically evicted.

---
 tools/perf/Documentation/perf-record.txt     |  53 +-
 tools/perf/util/bpf-filter.c                 | 596 ++++++++++++-
 tools/perf/util/bpf_skel/sample-filter.h     |  17 +-
 tools/perf/util/bpf_skel/sample_filter.bpf.c | 851 ++++++++++++++++++-
 4 files changed, 1465 insertions(+), 52 deletions(-)
tools/perf/Documentation/perf-record.txt +44 -9
index 445cc98a6c33..9fb5d15de135 100644
@@ -216,15 +216,50 @@ OPTIONS
 
 	The 'lock_held(<lock>)' predicate (or '!lock_held(<lock>)') filters
 	samples based on whether the specified kernel lock is currently held
-	by the kernel thread.  To differentiate between shared/read holding
-	and exclusive/write holding, use 'lock_held_read(<lock>)' (alias
-	'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)' (alias
-	'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to <lock>.
-	<lock> can be a kernel mutex symbol name (e.g.
-	'lock_held(cgroup_mutex)').  When filtering on a mutex symbol
-	('*_mutex'), 'perf_sample_filter' inspects the lock's 'owner' field
-	directly in kernel memory on each sample without attaching any BPF
-	fentry/fexit hooks.
+	by the kernel thread or CPU.  To differentiate between shared/read
+	holding and exclusive/write holding, use 'lock_held_read(<lock>)'
+	(alias 'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)'
+	(alias 'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to
+	<lock> (e.g. 'lock_held(rwsem:R)' or 'lock_held(rwsem:W)').
+	<lock> can be a kernel lock symbol name (e.g.
+	'lock_held(cgroup_mutex)'), a hexadecimal lock address, or a lock type
+	('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
+	'rwlock:R', 'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W',
+	'semaphore').  Both read/shared and write/exclusive tracking are
+	supported for 'rwsem' and 'rwlock'; 'mutex', 'spinlock', 'rt-mutex',
+	'semaphore', and 'percpu-rwsem' ('percpu_down_write()') support
+	write/exclusive tracking only.  Note that 'semaphore' tracking
+	('down*()' / 'up()') assumes binary mutex-like usage where the
+	acquiring task also releases the semaphore (such as 'console_sem'),
+	rather than cross-task completion signaling.
+
+	For example, 'lock_held()' can be combined with memory allocation or
+	reclaim events to detect allocations or direct memory reclaim occurring
+	while a kernel lock is held (which can stall lock waiters for extended
+	periods):
+
+	  # perf record -a -g -e vmscan:mm_vmscan_direct_reclaim_begin \
+	      --filter 'lock_held(mutex) || lock_held(rwsem)'
+	  # perf record -a -g -e kmem:mm_page_alloc \
+	      --filter 'gfp_flags & 0x400' \
+	      --filter 'lock_held(mutex) || lock_held(rwsem)'
+	  # perf record -a -g -e major-faults \
+	      --filter 'lock_held(mutex) || lock_held(rwsem)'
+
+	When filtering on a specific mutex symbol ('*_mutex') or rt-mutex
+	symbol ('*_rt_mutex'), 'perf_sample_filter' inspects the lock's
+	'owner' field directly in kernel memory on each sample without attaching
+	any BPF fentry/fexit hooks.  For locks that do not maintain an
+	authoritative per-task owner pointer (such as spinlocks, rwlocks,
+	semaphores, reader-locked rwsems, and lock type filters), it attaches
+	BPF fentry/fexit programs to kernel lock acquire and release functions
+	to track held locks in a BPF map.  These BPF hooks run on every kernel
+	lock acquisition and release for the attached lock family, even when no
+	perf sample is being taken.  To minimize this overhead, only the hooks
+	for the relevant lock family and mode are attached when known, whereas
+	raw hex addresses or symbols without a recognizable lock-type suffix
+	attach hooks across all lock families (including high-frequency
+	spinlocks).
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +559 -37

745 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +14 -3
index ca1cf586ed6e..c240eee782f8 100644
@@ -59,7 +59,8 @@ enum perf_bpf_filter_term {
 	 * The lock specification kind is stored in `entry.part`
 	 * (`enum perf_bpf_lock_target_kind`), `entry.op` is normalized to
 	 * `PBF_OP_EQ` (match when held) or `PBF_OP_NEQ` (match when not held),
-	 * and the resolved target address is stored in `entry.value`.
+	 * and the resolved target address or type flag encoding is stored in
+	 * `entry.value`.
 	 */
 	PBF_TERM_LOCK_HELD,
 };
@@ -71,10 +72,16 @@ enum perf_bpf_filter_term {
 enum perf_bpf_lock_target_kind {
 	PBF_LOCK_NONE = 0,
 	/*
-	 * Specific global or static lock address resolved from kallsyms.
-	 * `entry.value` holds the kernel address.
+	 * Specific global or static lock address (resolved from kallsyms or
+	 * given as a hex address). `entry.value` holds the kernel address.
 	 */
 	PBF_LOCK_ADDR,
+	/*
+	 * Lock type filter (`mutex`, `spinlock`, `rwsem`, `rwsem:R`, etc.).
+	 * `entry.value` packs up to two `LCB_F_*` flag combinations in the
+	 * low two bytes: `flag1 | (flag2 << 8)` (with 0xff indicating unused).
+	 */
+	PBF_LOCK_TYPE,
 };
 
 /*
@@ -83,6 +90,8 @@ enum perf_bpf_lock_target_kind {
  *   Bit  4:    PBF_LOCK_MODE_READ      (match read/shared lock holding)
  *   Bit  5:    PBF_LOCK_MODE_WRITE     (match write/exclusive lock holding)
  *   Bit  6:    PBF_LOCK_DIRECT_MUTEX   (inspect struct mutex owner)
+ *   Bit  7:    PBF_LOCK_DIRECT_RWSEM   (inspect struct rw_semaphore writer owner)
+ *   Bit  8:    PBF_LOCK_DIRECT_RTMUTEX (inspect struct rt_mutex_base / rt_mutex owner)
  */
 #define PBF_LOCK_KIND_MASK	0x0fU
 #define PBF_LOCK_MODE_READ	(1U << 4)
@@ -90,6 +99,8 @@ enum perf_bpf_lock_target_kind {
 #define PBF_LOCK_MODE_ANY	(PBF_LOCK_MODE_READ | PBF_LOCK_MODE_WRITE)
 #define PBF_LOCK_MODE_MASK	PBF_LOCK_MODE_ANY
 #define PBF_LOCK_DIRECT_MUTEX	(1U << 6)
+#define PBF_LOCK_DIRECT_RWSEM	(1U << 7)
+#define PBF_LOCK_DIRECT_RTMUTEX	(1U << 8)
 
 /* BPF map entry for filtering */
 struct perf_bpf_filter_entry {
tools/perf/util/bpf_skel/sample_filter.bpf.c +848 -3

895 lines not on this page · raw message

Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#93 lore raw

Re: [PATCH v6 06/11] perf bpf-filter: Extend lock_held() to other kernel lock types

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] perf bpf-filter: prescan_one_lock_expr() misses percpu_rw_semaphore symbols - [Medium] perf…

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] perf bpf-filter: prescan_one_lock_expr() misses percpu_rw_semaphore symbols
- [Medium] perf bpf-filter: '*_sem' rw_semaphore and percpu_rw_semaphore symbols misclassified as counting semaphores --

commit 088eb8ec579be2bc3ffee09560153843b89f7a25
Author: Ian Rogers <[email protected]>

perf bpf-filter: Extend lock_held() to other kernel lock types

This commit extends the lock_held() BPF sample filter to support additional kernel lock types, lock type flags, and hexadecimal lock addresses. It uses direct owner inspection where possible and attaches fentry/fexit BPF hooks to track lock acquisitions and releases in an LRU hash map otherwise.

Quoted 4 lines
tools/perf/util/bpf-filter.c +0 -0
index 639db6c031379..8797f67698f7d 100644

[ ... ]

Quoted 1 line
tools/perf/util/bpf-filter.c +0 -0
@@ -301,26 +517,225 @@ static int find_kernel_lock_sym(const char *name, u64 *addr)

[ ... ]

Quoted 54 lines

static void prescan_one_lock_expr(struct perf_bpf_filter_expr *expr,

tools/perf/util/bpf-filter.c +47 -1
-				  bool *has_lock_filter)
+				  bool *has_lock_filter,
+				  unsigned int *prog_groups,
+				  unsigned int *required_groups)
 {
+	char base[128];
+	bool has_amp;
+	unsigned int mode, groups = 0;
+	u64 dummy;
+
 	if (expr->term != PBF_TERM_LOCK_HELD || !expr->lock_name)
 		return;
 
 	*has_lock_filter = true;
+	if (split_lock_name_mode(expr->lock_name, expr->part, base,
+				 sizeof(base), &has_amp, &mode) < 0 || has_amp)
+		return;
+
+	if (parse_lock_type_name(base, mode, NULL, NULL, &groups)) {
+		*prog_groups |= groups;
+		*required_groups |= groups;
+		return;
+	}
+
+	if (parse_lock_hex_addr(base, &dummy)) {
+		*prog_groups |= LOCK_PROG_ALL;
+		return;
+	}
+
+	if (str_ends_with(base, "rt_mutex") || str_ends_with(base, "rtmutex") ||
+	    str_ends_with(base, "mutex")) {
+		/* Inspected directly via lock->owner; no tracing hooks needed. */
+		return;
+	} else if (str_ends_with(base, "percpu_rwsem") ||
+		   str_ends_with(base, "pcpu_rwsem")) {
+		*prog_groups |= LOCK_PROG_PERCPU_RWSEM;
+		*required_groups |= LOCK_PROG_PERCPU_RWSEM;
+	} else if (str_ends_with(base, "rwsem")) {
+		if (mode & PBF_LOCK_MODE_READ) {
+			*prog_groups |= LOCK_PROG_RWSEM_READ;
+			*required_groups |= LOCK_PROG_RWSEM_READ;
+		}
+		if (mode & PBF_LOCK_MODE_WRITE) {
+			*prog_groups |= LOCK_PROG_RWSEM_WRITE | LOCK_PROG_PERCPU_RWSEM;
+			*required_groups |= LOCK_PROG_RWSEM_WRITE;
+		}
+	} else if (str_ends_with(base, "spinlock")) {
+		*prog_groups |= LOCK_PROG_SPIN;
+		*required_groups |= LOCK_PROG_SPIN;
+	} else if (str_ends_with(base, "sem")) {
+		*prog_groups |= LOCK_PROG_SEM;
+		*required_groups |= LOCK_PROG_SEM;
+	} else if (str_ends_with(base, "rwlock")) {

tools/perf/util/bpf-filter.c static int find_kernel_lock_sym(const char *name, u64 *addr) · line 719

Quoted 10 lines
tools/perf/util/bpf-filter.c +9 -0
+		if (mode & PBF_LOCK_MODE_READ)
+			groups |= LOCK_PROG_RWLOCK_READ;
+		if (mode & PBF_LOCK_MODE_WRITE)
+			groups |= LOCK_PROG_RWLOCK_WRITE;
+		*prog_groups |= groups;
+		*required_groups |= groups;
+	} else {
+		*prog_groups |= LOCK_PROG_ALL;
+	}
 }

[Severity: Medium]
In perf_bpf_filter__prepare(), prescan_lock_filters() calls prescan_one_lock_expr() before btf__load_vmlinux_btf() is called:

perf_bpf_filter__prepare()
prescan_lock_filters()
prescan_one_lock_expr()
...
btf = btf__load_vmlinux_btf(); configure_lock_progs(skel, btf, prog_groups, required_groups, ...); sample_filter_bpf__load(skel);
get_filter_entries(evsel, skel, btf, entry)

    resolve_lock_expr(skel, btf, ...)
      is_percpu_rwsem_sym(btf, base)

Because prescan_one_lock_expr() only checks whether base ends with "percpu_rwsem" or "pcpu_rwsem" without calling is_percpu_rwsem_sym(), won't percpu_rw_semaphore symbols with other suffixes be misclassified during prescan?

For example, when filtering on dup_mmap_sem or bp_cpuinfo_sem, prescan_one_lock_expr() matches str_ends_with(base, "sem") and only sets LOCK_PROG_SEM. Then configure_lock_progs() disables autoload for fexit_percpu_down_write and fentry_percpu_up_write before the skeleton is loaded. When resolve_lock_expr() later runs and identifies the symbol via is_percpu_rwsem_sym(btf, base), the LOCK_PROG_PERCPU_RWSEM programs were never loaded or attached.

Similarly, for percpu_rw_semaphore symbols ending in "_rwsem" (such as cgroup_threadgroup_rwsem) or "_lock" (such as cpu_hotplug_lock and mem_hotplug_lock), wouldn't prescan_one_lock_expr() enable unnecessary LOCK_PROG_RWSEM or LOCK_PROG_ALL hooks across other lock families?

Quoted 19 lines
tools/perf/util/bpf-filter.c +14 -1
@@ -390,14 +805,42 @@ static int normalize_lock_expr_op(const struct perf_bpf_filter_expr *expr,
 	return -EINVAL;
 }
 
-static int resolve_lock_expr(struct perf_bpf_filter_expr *expr,
+static bool is_percpu_rwsem_sym(struct btf *btf, const char *name)
+{
+	char rc_name[160];
+
+	if (str_ends_with(name, "percpu_rwsem") ||
+	    str_ends_with(name, "pcpu_rwsem"))
+		return true;
+
+	if (!btf)
+		return false;
+
+	snprintf(rc_name, sizeof(rc_name), "__percpu_rwsem_rc_%s", name);
+	return btf__find_by_name_kind(btf, rc_name, BTF_KIND_VAR) > 0;
+}

[ ... ]

Quoted 1 line
tools/perf/util/bpf-filter.c +0 -0
@@ -410,29 +853,79 @@ static int resolve_lock_expr(struct perf_bpf_filter_expr *expr,

[ ... ]

Quoted 13 lines
tools/perf/util/bpf-filter.c +13 -0
+	ret = find_kernel_lock_sym(base, &addr);
+	if (ret == 0) {
+		unsigned int direct_flag = 0;
+		bool is_pcpu_rwsem = is_percpu_rwsem_sym(btf, base);
+
+		if (str_ends_with(base, "rt_mutex") || str_ends_with(base, "rtmutex"))
+			direct_flag = PBF_LOCK_DIRECT_RTMUTEX;
+		else if (str_ends_with(base, "mutex"))
+			direct_flag = PBF_LOCK_DIRECT_MUTEX;
+		else if (str_ends_with(base, "rwsem") && !is_pcpu_rwsem)
+			direct_flag = PBF_LOCK_DIRECT_RWSEM;
+
+		if ((direct_flag == PBF_LOCK_DIRECT_MUTEX ||

tools/perf/util/bpf-filter.c static int resolve_lock_expr(struct perf_bpf_filter_expr *expr, · line 907

Quoted 10 lines
tools/perf/util/bpf-filter.c +10 -0
+		     direct_flag == PBF_LOCK_DIRECT_RTMUTEX ||
+		     is_pcpu_rwsem ||
+		     str_ends_with(base, "spinlock") ||
+		     (str_ends_with(base, "sem") &&
+		      !str_ends_with(base, "rwsem"))) &&
+		    !(mode & PBF_LOCK_MODE_WRITE)) {
+			pr_err("Error: Lock '%s' is exclusive and does not support read/shared mode\n",
+			       name);
+			return -EINVAL;
+		}

[Severity: Medium]
How are global or static rw_semaphore locks whose names end in "_sem" (such as namespace_sem, uts_sem, pci_bus_sem, or dev_addr_sem, defined with DECLARE_RWSEM) handled here and in prescan_one_lock_expr()?

Because both functions classify any symbol ending in "sem" (and not "rwsem") as a counting semaphore:

1. In resolve_lock_expr(), read-mode filters such as lock_held_read(namespace_sem) or lock_held(uts_sem:R) hit the str_ends_with(base, "sem") && !str_ends_with(base, "rwsem") check when !(mode & PBF_LOCK_MODE_WRITE) and are rejected with -EINVAL.

2. For write-mode or any-mode filters such as lock_held(namespace_sem) or lock_held_write(uts_sem), prescan_one_lock_expr() only enables LOCK_PROG_SEM (down/up) and resolve_lock_expr() leaves direct_flag as 0, so neither PBF_LOCK_DIRECT_RWSEM nor the down_read/down_write hooks are used.

Could BTF type inspection on the symbol (or checking whether the BTF var type is struct rw_semaphore vs struct semaphore) be used to distinguish rw_semaphore symbols ending in "_sem" from counting semaphores?

Quoted 3 lines
tools/perf/util/bpf-filter.c +3 -0
+
+		entry->part = PBF_LOCK_ADDR | mode | direct_flag;
+		entry->value = addr;

[ ... ]

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

Re: [PATCH v6 06/11] perf bpf-filter: Extend lock_held() to other kernel lock types

In reply to Ian Rogers
Quoted 183 lines · Ian Rogers

Extend the lock_held() BPF sample filter beyond global mutexes to support:
- Other global/static kernel lock symbols (rwsem, spinlock, rwlock, rt-mutex, percpu-rwsem, semaphore) and hexadecimal kernel lock addresses.
- Lock types and flags: mutex, spinlock, rwsem, rwsem:R, rwsem:W, rwlock, rwlock:R, rwlock:W, rt-mutex, percpu-rwsem, pcpu-sem:W, semaphore.

For rt-mutexes and write-locked rwsems, perf_sample_filter inspects the lock's owner field directly in kernel memory. For locks and modes without an authoritative per-task owner pointer (spinlocks, rwlocks, semaphores, reader-locked rwsems, percpu-rwsems, and lock type filters), attach BPF fentry/fexit hooks on kernel lock acquire and release functions to track held locks in the held_locks BPF LRU hash map.

Note that counting semaphores (down*() / up()) do not enforce same-task ownership in the kernel: when a semaphore is used as a cross-task completion/signaling mechanism, fexit/down and fentry/up will not pair on the same task ID. Semaphore hooks are therefore only enabled when 'semaphore' or a '*_sem' symbol (such as console_sem) is explicitly specified, and held_locks uses BPF_MAP_TYPE_LRU_HASH so any unpaired cross-task entries are automatically evicted.

---
 tools/perf/Documentation/perf-record.txt     |  53 +-
 tools/perf/util/bpf-filter.c                 | 596 ++++++++++++-
 tools/perf/util/bpf_skel/sample-filter.h     |  17 +-
 tools/perf/util/bpf_skel/sample_filter.bpf.c | 851 ++++++++++++++++++-
 4 files changed, 1465 insertions(+), 52 deletions(-)
tools/perf/Documentation/perf-record.txt +44 -9
index 445cc98a6c33..9fb5d15de135 100644
@@ -216,15 +216,50 @@ OPTIONS
 
 	The 'lock_held(<lock>)' predicate (or '!lock_held(<lock>)') filters
 	samples based on whether the specified kernel lock is currently held
-	by the kernel thread.  To differentiate between shared/read holding
-	and exclusive/write holding, use 'lock_held_read(<lock>)' (alias
-	'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)' (alias
-	'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to <lock>.
-	<lock> can be a kernel mutex symbol name (e.g.
-	'lock_held(cgroup_mutex)').  When filtering on a mutex symbol
-	('*_mutex'), 'perf_sample_filter' inspects the lock's 'owner' field
-	directly in kernel memory on each sample without attaching any BPF
-	fentry/fexit hooks.
+	by the kernel thread or CPU.  To differentiate between shared/read
+	holding and exclusive/write holding, use 'lock_held_read(<lock>)'
+	(alias 'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)'
+	(alias 'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to
+	<lock> (e.g. 'lock_held(rwsem:R)' or 'lock_held(rwsem:W)').
+	<lock> can be a kernel lock symbol name (e.g.
+	'lock_held(cgroup_mutex)'), a hexadecimal lock address, or a lock type
+	('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
+	'rwlock:R', 'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W',
+	'semaphore').  Both read/shared and write/exclusive tracking are
+	supported for 'rwsem' and 'rwlock'; 'mutex', 'spinlock', 'rt-mutex',
+	'semaphore', and 'percpu-rwsem' ('percpu_down_write()') support
+	write/exclusive tracking only.  Note that 'semaphore' tracking
+	('down*()' / 'up()') assumes binary mutex-like usage where the
+	acquiring task also releases the semaphore (such as 'console_sem'),
+	rather than cross-task completion signaling.
+
+	For example, 'lock_held()' can be combined with memory allocation or
+	reclaim events to detect allocations or direct memory reclaim occurring
+	while a kernel lock is held (which can stall lock waiters for extended
+	periods):
+
+	  # perf record -a -g -e vmscan:mm_vmscan_direct_reclaim_begin \
+	      --filter 'lock_held(mutex) || lock_held(rwsem)'
+	  # perf record -a -g -e kmem:mm_page_alloc \
+	      --filter 'gfp_flags & 0x400' \
+	      --filter 'lock_held(mutex) || lock_held(rwsem)'
+	  # perf record -a -g -e major-faults \
+	      --filter 'lock_held(mutex) || lock_held(rwsem)'
+
+	When filtering on a specific mutex symbol ('*_mutex') or rt-mutex
+	symbol ('*_rt_mutex'), 'perf_sample_filter' inspects the lock's
+	'owner' field directly in kernel memory on each sample without attaching
+	any BPF fentry/fexit hooks.  For locks that do not maintain an
+	authoritative per-task owner pointer (such as spinlocks, rwlocks,
+	semaphores, reader-locked rwsems, and lock type filters), it attaches
+	BPF fentry/fexit programs to kernel lock acquire and release functions
+	to track held locks in a BPF map.  These BPF hooks run on every kernel
+	lock acquisition and release for the attached lock family, even when no
+	perf sample is being taken.  To minimize this overhead, only the hooks
+	for the relevant lock family and mode are attached when known, whereas
+	raw hex addresses or symbols without a recognizable lock-type suffix
+	attach hooks across all lock families (including high-frequency
+	spinlocks).
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +58 -0
index 639db6c03137..8797f67698f7 100644
@@ -52,6 +52,7 @@
 #include <sys/stat.h>
 
 #include <bpf/bpf.h>
+#include <bpf/btf.h>
 #include <linux/err.h>
 #include <linux/kernel.h>
 #include <linux/list.h>
@@ -65,6 +66,7 @@
 #include "util/cap.h"
 #include "util/debug.h"
 #include "util/evsel.h"
+#include "util/lock-contention.h"
 #include "util/symbol_conf.h"
 #include "util/target.h"
 #include "util/thread_map.h"
@@ -74,6 +76,7 @@
 #include <util/bpf-filter-flex.h>
 #include <util/bpf-filter-bison.h>
 
+#include "bpf_skel/lock_data.h"
 #include "bpf_skel/sample-filter.h"
 #include "bpf_skel/sample_filter.skel.h"
 
@@ -178,6 +181,153 @@ static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr *
 	return -1;
 }
 
+/*
+ * Program groups for `lock_held(...)` BPF tracing hooks.
+ *
+ * When a `lock_held(...)` filter is specified, only the BPF tracing program
+ * groups required for the requested lock(s) are autoloaded and attached.
+ * If no `lock_held(...)` filter is present, none of these programs are loaded.
+ */
+enum lock_prog_group {
+	LOCK_PROG_MUTEX         = 1U << 0,
+	LOCK_PROG_RWSEM_READ    = 1U << 1,
+	LOCK_PROG_RWSEM_WRITE   = 1U << 2,
+	LOCK_PROG_RWSEM         = LOCK_PROG_RWSEM_READ | LOCK_PROG_RWSEM_WRITE,
+	LOCK_PROG_SPIN          = 1U << 3,
+	LOCK_PROG_RWLOCK_READ   = 1U << 4,
+	LOCK_PROG_RWLOCK_WRITE  = 1U << 5,
+	LOCK_PROG_RWLOCK        = LOCK_PROG_RWLOCK_READ | LOCK_PROG_RWLOCK_WRITE,
+	LOCK_PROG_RTMUTEX       = 1U << 6,
+	LOCK_PROG_SEM           = 1U << 7,
+	LOCK_PROG_PERCPU_RWSEM  = 1U << 8,
+	LOCK_PROG_ALL           = 0x1ffU & ~LOCK_PROG_SEM,
+};
+
+static unsigned int lock_flags_to_prog_group(unsigned int flags)
+{
+	if (flags & LCB_F_MUTEX)
+		return LOCK_PROG_MUTEX;
+	if (flags & LCB_F_RT)
+		return LOCK_PROG_RTMUTEX;
+	if (flags & LCB_F_PERCPU)
+		return LOCK_PROG_PERCPU_RWSEM;
+	if (flags == LCB_F_SPIN)
+		return LOCK_PROG_SPIN;
+	if (flags & LCB_F_SPIN)
+		return (flags & LCB_F_READ) ? LOCK_PROG_RWLOCK_READ : LOCK_PROG_RWLOCK_WRITE;
+	if (flags & LCB_F_READ)
+		return LOCK_PROG_RWSEM_READ;
+	if (flags & LCB_F_WRITE)
+		return LOCK_PROG_RWSEM_WRITE;
+	return LOCK_PROG_SEM;
+}
+
+struct lock_prog_desc {
+	size_t prog_offset;
+	const char *btf_func;
+	unsigned int group;
+};
+
+#define LOCK_FPROG(field, func, grp) \
+	{ offsetof(struct sample_filter_bpf, progs.field), func, grp }
+
+static const struct lock_prog_desc lock_progs[] = {
+	/* Mutex */
+	LOCK_FPROG(fexit_mutex_lock, "mutex_lock", LOCK_PROG_MUTEX),
+	LOCK_FPROG(fexit_mutex_lock_nested, "mutex_lock_nested", LOCK_PROG_MUTEX),
+	LOCK_FPROG(fexit__mutex_lock_nest_lock, "_mutex_lock_nest_lock", LOCK_PROG_MUTEX),

tools/perf/util/bpf-filter.c static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr * · line 248

Quoted 10 lines
tools/perf/util/bpf-filter.c +10 -0
+	LOCK_FPROG(fexit_mutex_lock_io, "mutex_lock_io", LOCK_PROG_MUTEX),
+	LOCK_FPROG(fexit_mutex_lock_io_nested, "mutex_lock_io_nested", LOCK_PROG_MUTEX),
+	LOCK_FPROG(fexit_mutex_lock_interruptible, "mutex_lock_interruptible", LOCK_PROG_MUTEX),
+	LOCK_FPROG(fexit_mutex_lock_interruptible_nested, "mutex_lock_interruptible_nested",
+		   LOCK_PROG_MUTEX),
+	LOCK_FPROG(fexit_mutex_lock_killable, "mutex_lock_killable", LOCK_PROG_MUTEX),
+	LOCK_FPROG(fexit__mutex_lock_killable, "_mutex_lock_killable", LOCK_PROG_MUTEX),
+	LOCK_FPROG(fexit_mutex_trylock, "mutex_trylock", LOCK_PROG_MUTEX),
+	LOCK_FPROG(fexit__mutex_trylock_nest_lock, "_mutex_trylock_nest_lock", LOCK_PROG_MUTEX),
+	LOCK_FPROG(fentry_mutex_unlock, "mutex_unlock", LOCK_PROG_MUTEX),

I'm not sure if these are still needed.. it can handle mutexes specially, right?

Thanks,
Namhyung

Quoted 81 lines
tools/perf/util/bpf-filter.c +81 -0
+	/* RW semaphore */
+	LOCK_FPROG(fexit_down_read, "down_read", LOCK_PROG_RWSEM_READ),
+	LOCK_FPROG(fexit_down_read_nested, "down_read_nested", LOCK_PROG_RWSEM_READ),
+	LOCK_FPROG(fexit_down_read_interruptible, "down_read_interruptible", LOCK_PROG_RWSEM_READ),
+	LOCK_FPROG(fexit_down_read_killable, "down_read_killable", LOCK_PROG_RWSEM_READ),
+	LOCK_FPROG(fexit_down_read_killable_nested, "down_read_killable_nested",
+		   LOCK_PROG_RWSEM_READ),
+	LOCK_FPROG(fexit_down_read_trylock, "down_read_trylock", LOCK_PROG_RWSEM_READ),
+	LOCK_FPROG(fexit_down_write, "down_write", LOCK_PROG_RWSEM_WRITE),
+	LOCK_FPROG(fexit_down_write_nested, "down_write_nested", LOCK_PROG_RWSEM_WRITE),
+	LOCK_FPROG(fexit__down_write_nest_lock, "_down_write_nest_lock", LOCK_PROG_RWSEM_WRITE),
+	LOCK_FPROG(fexit_down_write_killable, "down_write_killable", LOCK_PROG_RWSEM_WRITE),
+	LOCK_FPROG(fexit_down_write_killable_nested, "down_write_killable_nested",
+		   LOCK_PROG_RWSEM_WRITE),
+	LOCK_FPROG(fexit_down_write_trylock, "down_write_trylock", LOCK_PROG_RWSEM_WRITE),
+	LOCK_FPROG(fexit_downgrade_write, "downgrade_write", LOCK_PROG_RWSEM),
+	LOCK_FPROG(fentry_up_read, "up_read", LOCK_PROG_RWSEM_READ),
+	LOCK_FPROG(fentry_up_write, "up_write", LOCK_PROG_RWSEM_WRITE),
+	/* Spinlock */
+	LOCK_FPROG(fexit_raw_spin_lock, "_raw_spin_lock", LOCK_PROG_SPIN),
+	LOCK_FPROG(fexit_raw_spin_lock_nested, "_raw_spin_lock_nested", LOCK_PROG_SPIN),
+	LOCK_FPROG(fexit_raw_spin_lock_nest_lock, "_raw_spin_lock_nest_lock", LOCK_PROG_SPIN),
+	LOCK_FPROG(fexit_raw_spin_lock_irq, "_raw_spin_lock_irq", LOCK_PROG_SPIN),
+	LOCK_FPROG(fexit_raw_spin_lock_irq_disable, "_raw_spin_lock_irq_disable", LOCK_PROG_SPIN),
+	LOCK_FPROG(fexit_raw_spin_lock_irqsave, "_raw_spin_lock_irqsave", LOCK_PROG_SPIN),
+	LOCK_FPROG(fexit_raw_spin_lock_irqsave_nested, "_raw_spin_lock_irqsave_nested",
+		   LOCK_PROG_SPIN),
+	LOCK_FPROG(fexit_raw_spin_lock_bh, "_raw_spin_lock_bh", LOCK_PROG_SPIN),
+	LOCK_FPROG(fexit_raw_spin_trylock, "_raw_spin_trylock", LOCK_PROG_SPIN),
+	LOCK_FPROG(fexit_raw_spin_trylock_bh, "_raw_spin_trylock_bh", LOCK_PROG_SPIN),
+	LOCK_FPROG(fentry_raw_spin_unlock, "_raw_spin_unlock", LOCK_PROG_SPIN),
+	LOCK_FPROG(fentry_raw_spin_unlock_irq, "_raw_spin_unlock_irq", LOCK_PROG_SPIN),
+	LOCK_FPROG(fentry_raw_spin_unlock_irq_enable, "_raw_spin_unlock_irq_enable",
+		   LOCK_PROG_SPIN),
+	LOCK_FPROG(fentry_raw_spin_unlock_irqrestore, "_raw_spin_unlock_irqrestore",
+		   LOCK_PROG_SPIN),
+	LOCK_FPROG(fentry_raw_spin_unlock_bh, "_raw_spin_unlock_bh", LOCK_PROG_SPIN),
+	/* RWlock */
+	LOCK_FPROG(fexit_raw_read_lock, "_raw_read_lock", LOCK_PROG_RWLOCK_READ),
+	LOCK_FPROG(fexit_raw_read_lock_irq, "_raw_read_lock_irq", LOCK_PROG_RWLOCK_READ),
+	LOCK_FPROG(fexit_raw_read_lock_irqsave, "_raw_read_lock_irqsave", LOCK_PROG_RWLOCK_READ),
+	LOCK_FPROG(fexit_raw_read_lock_bh, "_raw_read_lock_bh", LOCK_PROG_RWLOCK_READ),
+	LOCK_FPROG(fexit_raw_read_trylock, "_raw_read_trylock", LOCK_PROG_RWLOCK_READ),
+	LOCK_FPROG(fentry_raw_read_unlock, "_raw_read_unlock", LOCK_PROG_RWLOCK_READ),
+	LOCK_FPROG(fentry_raw_read_unlock_irq, "_raw_read_unlock_irq", LOCK_PROG_RWLOCK_READ),
+	LOCK_FPROG(fentry_raw_read_unlock_irqrestore, "_raw_read_unlock_irqrestore",
+		   LOCK_PROG_RWLOCK_READ),
+	LOCK_FPROG(fentry_raw_read_unlock_bh, "_raw_read_unlock_bh", LOCK_PROG_RWLOCK_READ),
+	LOCK_FPROG(fexit_raw_write_lock, "_raw_write_lock", LOCK_PROG_RWLOCK_WRITE),
+	LOCK_FPROG(fexit_raw_write_lock_nested, "_raw_write_lock_nested", LOCK_PROG_RWLOCK_WRITE),
+	LOCK_FPROG(fexit_raw_write_lock_irq, "_raw_write_lock_irq", LOCK_PROG_RWLOCK_WRITE),
+	LOCK_FPROG(fexit_raw_write_lock_irqsave, "_raw_write_lock_irqsave", LOCK_PROG_RWLOCK_WRITE),
+	LOCK_FPROG(fexit_raw_write_lock_bh, "_raw_write_lock_bh", LOCK_PROG_RWLOCK_WRITE),
+	LOCK_FPROG(fexit_raw_write_trylock, "_raw_write_trylock", LOCK_PROG_RWLOCK_WRITE),
+	LOCK_FPROG(fentry_raw_write_unlock, "_raw_write_unlock", LOCK_PROG_RWLOCK_WRITE),
+	LOCK_FPROG(fentry_raw_write_unlock_irq, "_raw_write_unlock_irq", LOCK_PROG_RWLOCK_WRITE),
+	LOCK_FPROG(fentry_raw_write_unlock_irqrestore, "_raw_write_unlock_irqrestore",
+		   LOCK_PROG_RWLOCK_WRITE),
+	LOCK_FPROG(fentry_raw_write_unlock_bh, "_raw_write_unlock_bh", LOCK_PROG_RWLOCK_WRITE),
+	/* RT-Mutex */
+	LOCK_FPROG(fexit_rt_mutex_lock, "rt_mutex_lock", LOCK_PROG_RTMUTEX),
+	LOCK_FPROG(fexit_rt_mutex_lock_nested, "rt_mutex_lock_nested", LOCK_PROG_RTMUTEX),
+	LOCK_FPROG(fexit__rt_mutex_lock_nest_lock, "_rt_mutex_lock_nest_lock", LOCK_PROG_RTMUTEX),
+	LOCK_FPROG(fexit_rt_mutex_lock_interruptible, "rt_mutex_lock_interruptible",
+		   LOCK_PROG_RTMUTEX),
+	LOCK_FPROG(fexit_rt_mutex_lock_killable, "rt_mutex_lock_killable", LOCK_PROG_RTMUTEX),
+	LOCK_FPROG(fexit_rt_mutex_trylock, "rt_mutex_trylock", LOCK_PROG_RTMUTEX),
+	LOCK_FPROG(fentry_rt_mutex_unlock, "rt_mutex_unlock", LOCK_PROG_RTMUTEX),
+	/* Semaphore */
+	LOCK_FPROG(fexit_down, "down", LOCK_PROG_SEM),
+	LOCK_FPROG(fexit_down_interruptible, "down_interruptible", LOCK_PROG_SEM),
+	LOCK_FPROG(fexit_down_killable, "down_killable", LOCK_PROG_SEM),
+	LOCK_FPROG(fexit_down_timeout, "down_timeout", LOCK_PROG_SEM),
+	LOCK_FPROG(fexit_down_trylock, "down_trylock", LOCK_PROG_SEM),
+	LOCK_FPROG(fentry_up, "up", LOCK_PROG_SEM),
+	/* Percpu-RWsem */
+	LOCK_FPROG(fexit_percpu_down_write, "percpu_down_write", LOCK_PROG_PERCPU_RWSEM),
+	LOCK_FPROG(fentry_percpu_up_write, "percpu_up_write", LOCK_PROG_PERCPU_RWSEM),
+};
+
+#undef LOCK_FPROG
author reviewer
#95 lore raw

Re: [PATCH v6 06/11] perf bpf-filter: Extend lock_held() to other kernel lock types

Quoted 2 lines · Namhyung Kim

On Thu, Oct 22, 2026 at 01:29:58PM -0700, Ian Rogers wrote:

[snip]

Quoted 16 lines
Quoted 5 lines
tools/perf/util/bpf-filter.c +5 -0
+static const struct lock_prog_desc lock_progs[] = {
+     /* Mutex */
+     LOCK_FPROG(fexit_mutex_lock, "mutex_lock", LOCK_PROG_MUTEX),
+     LOCK_FPROG(fexit_mutex_lock_nested, "mutex_lock_nested", LOCK_PROG_MUTEX),
+     LOCK_FPROG(fexit__mutex_lock_nest_lock, "_mutex_lock_nest_lock", LOCK_PROG_MUTEX),

tools/perf/util/bpf-filter.c static int check_sample_flags(struct evsel *evsel, struct perf_bpf_filter_expr * · line 248

Quoted 10 lines
tools/perf/util/bpf-filter.c +10 -0
+     LOCK_FPROG(fexit_mutex_lock_io, "mutex_lock_io", LOCK_PROG_MUTEX),
+     LOCK_FPROG(fexit_mutex_lock_io_nested, "mutex_lock_io_nested", LOCK_PROG_MUTEX),
+     LOCK_FPROG(fexit_mutex_lock_interruptible, "mutex_lock_interruptible", LOCK_PROG_MUTEX),
+     LOCK_FPROG(fexit_mutex_lock_interruptible_nested, "mutex_lock_interruptible_nested",
+                LOCK_PROG_MUTEX),
+     LOCK_FPROG(fexit_mutex_lock_killable, "mutex_lock_killable", LOCK_PROG_MUTEX),
+     LOCK_FPROG(fexit__mutex_lock_killable, "_mutex_lock_killable", LOCK_PROG_MUTEX),
+     LOCK_FPROG(fexit_mutex_trylock, "mutex_trylock", LOCK_PROG_MUTEX),
+     LOCK_FPROG(fexit__mutex_trylock_nest_lock, "_mutex_trylock_nest_lock", LOCK_PROG_MUTEX),
+     LOCK_FPROG(fentry_mutex_unlock, "mutex_unlock", LOCK_PROG_MUTEX),
Quoted 2 lines

I'm not sure if these are still needed.. it can handle mutexes specially, right?

The direct lock->owner check only works when we already know the mutex's address, i.e. lock_held(<global mutex symbol>). In that case prescan_one_lock_expr() adds no LOCK_PROG_MUTEX group, and configure_lock_progs() turns autoload off for all of these programs, so none of them are loaded.

They're still needed when the address isn't known up front, or the target matches many mutexes:
- lock type filters, e.g. lock_held(mutex) or "lock_held(mutex) ||
lock_held(rwsem)" for the direct reclaim use case. There we need to know whether the current task holds any mutex, which means tracking acquire/release in held_locks;
- slab cache filters (lock_held(&<cache>)), where the lock is
embedded in a dynamically allocated object and we match on the kmem_cache of the address recorded at acquire time;
- hex addresses and symbols whose type can't be determined, where we
hook every lock family.

So they're only loaded when the filter actually needs them. I'll add a comment above lock_progs[] in the next version explaining this.

Thanks,
Ian

Quoted 2 lines

Thanks,
Namhyung

author reviewer
#96 lore raw

PATCH v6 7/11 perf bpf-filter: Support per-process and semi-global locks in lock_held()

In reply to Ian Rogers

Extend the lock_held() BPF sample filter to support well-known per-process and semi-global kernel locks:
- mmap_lock (or mmap_sem): current->mm->mmap_lock, supporting both read/shared (lock_held_read(mmap_lock) / lock_held(mmap_lock:R)) and write/exclusive (lock_held_write(mmap_lock) / lock_held(mmap_lock:W)) modes. Write ownership is inspected directly via is_rwsem_writer_owner() without attaching fentry/fexit hooks.
- siglock: current->sighand->siglock.
- rq_lock: per-CPU scheduler runqueue locks.
- zone_lock: memory management NUMA zone locks.

For rq_lock and zone_lock, reuse do_collect_lock_syms() from lock_data.h via a raw_tp/bpf_test_finish program run at filter setup time to populate the lock_syms map with each CPU's rq_lock and each NUMA node's zone_lock addresses.

Example usage:

  # perf record -a -g -e cycles --filter 'lock_held(mmap_lock)' \
      -- perf bench mem mmap -t 2 -l 100
  # perf record -a -g -e cycles --filter 'lock_held_read(mmap_lock)' ...
  # perf record -a -g -e cycles --filter 'lock_held_write(mmap_lock)' ...
  # perf record -a -g -e cycles --filter 'lock_held(mmap_lock:W)' ...
---
 tools/perf/Documentation/perf-record.txt     |  24 +--
 tools/perf/util/bpf-filter.c                 | 169 +++++++++++++++++--
 tools/perf/util/bpf_skel/sample-filter.h     |  18 +-
 tools/perf/util/bpf_skel/sample_filter.bpf.c |  67 ++++++++
 4 files changed, 252 insertions(+), 26 deletions(-)
tools/perf/Documentation/perf-record.txt +14 -10
index 9fb5d15de135..2b2aaaead76b 100644
@@ -220,13 +220,15 @@ OPTIONS
 	holding and exclusive/write holding, use 'lock_held_read(<lock>)'
 	(alias 'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)'
 	(alias 'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to
-	<lock> (e.g. 'lock_held(rwsem:R)' or 'lock_held(rwsem:W)').
+	<lock> (e.g. 'lock_held(mmap_lock:R)' or 'lock_held(mmap_lock:W)').
 	<lock> can be a kernel lock symbol name (e.g.
-	'lock_held(cgroup_mutex)'), a hexadecimal lock address, or a lock type
-	('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
+	'lock_held(cgroup_mutex)'), a hexadecimal lock address, a well-known
+	lock name ('mmap_lock', 'siglock', 'rq_lock', 'zone_lock'), or a lock
+	type ('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
 	'rwlock:R', 'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W',
 	'semaphore').  Both read/shared and write/exclusive tracking are
-	supported for 'rwsem' and 'rwlock'; 'mutex', 'spinlock', 'rt-mutex',
+	supported for 'rwsem' (including 'mmap_lock') and 'rwlock'; 'mutex',
+	'spinlock' (including 'siglock', 'rq_lock', 'zone_lock'), 'rt-mutex',
 	'semaphore', and 'percpu-rwsem' ('percpu_down_write()') support
 	write/exclusive tracking only.  Note that 'semaphore' tracking
 	('down*()' / 'up()') assumes binary mutex-like usage where the
@@ -246,8 +248,9 @@ OPTIONS
 	  # perf record -a -g -e major-faults \
 	      --filter 'lock_held(mutex) || lock_held(rwsem)'
 
-	When filtering on a specific mutex symbol ('*_mutex') or rt-mutex
-	symbol ('*_rt_mutex'), 'perf_sample_filter' inspects the lock's
+	When filtering on a specific mutex symbol ('*_mutex'), rt-mutex symbol
+	('*_rt_mutex'), or write-locked 'mmap_lock' ('lock_held_write(mmap_lock)'
+	or 'lock_held(mmap_lock:W)'), 'perf_sample_filter' inspects the lock's
 	'owner' field directly in kernel memory on each sample without attaching
 	any BPF fentry/fexit hooks.  For locks that do not maintain an
 	authoritative per-task owner pointer (such as spinlocks, rwlocks,
@@ -256,10 +259,11 @@ OPTIONS
 	to track held locks in a BPF map.  These BPF hooks run on every kernel
 	lock acquisition and release for the attached lock family, even when no
 	perf sample is being taken.  To minimize this overhead, only the hooks
-	for the relevant lock family and mode are attached when known, whereas
-	raw hex addresses or symbols without a recognizable lock-type suffix
-	attach hooks across all lock families (including high-frequency
-	spinlocks).
+	for the relevant lock family and mode are attached when known (for
+	example, 'lock_held_read(mmap_lock)' only hooks rwsem read functions
+	and 'rq_lock' only hooks spinlock functions), whereas raw hex addresses
+	or symbols without a recognizable lock-type suffix attach hooks across
+	all lock families (including high-frequency spinlocks).
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +155 -14

272 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +16 -2
index c240eee782f8..836b398dc62b 100644
@@ -59,8 +59,8 @@ enum perf_bpf_filter_term {
 	 * The lock specification kind is stored in `entry.part`
 	 * (`enum perf_bpf_lock_target_kind`), `entry.op` is normalized to
 	 * `PBF_OP_EQ` (match when held) or `PBF_OP_NEQ` (match when not held),
-	 * and the resolved target address or type flag encoding is stored in
-	 * `entry.value`.
+	 * and the resolved target address, class ID, or type flag encoding is
+	 * stored in `entry.value`.
 	 */
 	PBF_TERM_LOCK_HELD,
 };
@@ -76,6 +76,20 @@ enum perf_bpf_lock_target_kind {
 	 * given as a hex address). `entry.value` holds the kernel address.
 	 */
 	PBF_LOCK_ADDR,
+	/*
+	 * Per-process `current->mm->mmap_lock` (or `mmap_sem`).
+	 */
+	PBF_LOCK_MMAP,
+	/*
+	 * Per-process `current->sighand->siglock`.
+	 */
+	PBF_LOCK_SIGHAND,
+	/*
+	 * Semi-global lock class (`rq_lock` or `zone_lock`).
+	 * `entry.value` holds `enum lock_class_sym` (LOCK_CLASS_RQLOCK or
+	 * LOCK_CLASS_ZONE_LOCK).
+	 */
+	PBF_LOCK_CLASS,
 	/*
 	 * Lock type filter (`mutex`, `spinlock`, `rwsem`, `rwsem:R`, etc.).
 	 * `entry.value` packs up to two `LCB_F_*` flag combinations in the
tools/perf/util/bpf_skel/sample_filter.bpf.c +67 -0

113 lines not on this page · raw message

Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#97 lore raw

Re: [PATCH v6 07/11] perf bpf-filter: Support per-process and semi-global locks in lock_held()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] perf bpf-filter: unhandled zone_lock resolution errors in init_numa_data() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] perf bpf-filter: unhandled zone_lock resolution errors in init_numa_data() --

commit f38f272294852331e8bd18c104c37ae24d5b109c
Author: Ian Rogers <[email protected]>

perf bpf-filter: Support per-process and semi-global locks in lock_held()

This commit extends the lock_held() BPF sample filter to support the per-process locks mmap_lock and siglock as well as the semi-global locks rq_lock and zone_lock. For rq_lock and zone_lock, it populates the lock_syms BPF map at filter setup time via a raw_tp/bpf_test_finish program.

Quoted 57 lines
tools/perf/util/bpf-filter.c +48 -0
index 8797f67698f7d..f542920f914fc 100644
@@ -534,6 +534,54 @@ static bool parse_lock_hex_addr(const char *str, u64 *addr)
 	return true;
 }
 
+static void init_numa_data(struct sample_filter_bpf *skel, struct btf *btf)
+{
+	u64 addr = 0;
+	char *buf = NULL, *p;
+	size_t len;
+	long last = -1;
+	int ret;
+
+	if (!btf)
+		return;
+
+	ret = btf__find_by_name_kind(btf, "zone", BTF_KIND_STRUCT);
+	if (ret < 0)
+		return;
+
+	ret = btf__resolve_size(btf, ret);
+	if (ret < 0)
+		return;
+
+	skel->rodata->sizeof_zone = ret;
+
+	if (find_kernel_lock_sym("contig_page_data", &addr) == 0) {
+		skel->rodata->contig_page_data_addr = addr;
+		return;
+	}
+
+	if (find_kernel_lock_sym("node_data", &addr) != 0)
+		return;
+
+	skel->rodata->node_data_addr = addr;
+
+	if (sysfs__read_str("devices/system/node/online", &buf, &len) >= 0) {
+		p = buf;
+		while (p && *p) {
+			char *end;
+
+			last = strtol(p, &end, 0);
+			if (end == p)
+				break;
+			p = end;
+			if (*p == ',' || *p == '-' || *p == '\n')
+				p++;
+		}
+		skel->rodata->nr_nodes = last + 1;
+		free(buf);
+	}
+}
+
 static bool btf_has_func(struct btf *btf, const char *name)

[ ... ]

Quoted 37 lines
tools/perf/util/bpf-filter.c +25 -1
@@ -657,7 +707,8 @@ static int configure_lock_progs(struct sample_filter_bpf *skel, struct btf *btf,
 static void prescan_one_lock_expr(struct perf_bpf_filter_expr *expr,
 				  bool *has_lock_filter,
 				  unsigned int *prog_groups,
-				  unsigned int *required_groups)
+				  unsigned int *required_groups,
+				  bool *needs_lock_syms)
 {
 	char base[128];
 	bool has_amp;
@@ -672,6 +723,29 @@ static void prescan_one_lock_expr(struct perf_bpf_filter_expr *expr,
 				 sizeof(base), &has_amp, &mode) < 0 || has_amp)
 		return;
 
+	if (!strcmp(base, "mmap_lock") || !strcmp(base, "mmap_sem")) {
+		/*
+		 * Write ownership of mm->mmap_lock is inspected directly via
+		 * is_rwsem_writer_owner() without tracing hooks; only reader
+		 * tracking requires LOCK_PROG_RWSEM_READ.
+		 */
+		if (mode & PBF_LOCK_MODE_READ) {
+			*prog_groups |= LOCK_PROG_RWSEM_READ;
+			*required_groups |= LOCK_PROG_RWSEM_READ;
+		}
+		return;
+	}
+	if (!strcmp(base, "siglock")) {
+		*prog_groups |= LOCK_PROG_SPIN;
+		*required_groups |= LOCK_PROG_SPIN;
+		return;
+	}
+	if (!strcmp(base, "rq_lock") || !strcmp(base, "zone_lock")) {
+		*prog_groups |= LOCK_PROG_SPIN;
+		*required_groups |= LOCK_PROG_SPIN;
+		*needs_lock_syms = true;
+		return;
+	}

[ ... ]

Quoted 1 line
tools/perf/util/bpf-filter.c +0 -0
@@ -853,6 +932,53 @@ static int resolve_lock_expr(struct sample_filter_bpf *skel, struct btf *btf,

[ ... ]

Quoted 12 lines
tools/perf/util/bpf-filter.c +12 -0
+	if (!strcmp(base, "zone_lock")) {
+		if (!(mode & PBF_LOCK_MODE_WRITE)) {
+			pr_err("Error: Lock '%s' is exclusive and does not support read/shared mode\n",
+			       name);
+			return -EINVAL;
+		}
+		entry->part = PBF_LOCK_CLASS | mode;
+		entry->value = LOCK_CLASS_ZONE_LOCK;
+		if (skel)
+			skel->bss->has_lock_class = 1;
+		return 0;
+	}

[ ... ]

tools/perf/util/bpf-filter.c int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target) · line 1412

Quoted 8 lines
tools/perf/util/bpf-filter.c +4 -0
@@ -1280,12 +1406,16 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		btf = btf__load_vmlinux_btf();
 		bpf_map__set_max_entries(skel->maps.held_locks, MAX_ENTRIES);
 		bpf_map__set_max_entries(skel->maps.lock_addr_filter, MAX_FILTERS);
+		if (needs_lock_syms) {
+			bpf_map__set_max_entries(skel->maps.lock_syms, MAX_ENTRIES);
+			init_numa_data(skel, btf);
+		}

[Severity: Medium]
In perf_bpf_filter__prepare() -> prescan_lock_filters() -> prescan_one_lock_expr(), both rq_lock and zone_lock set *needs_lock_syms = true, and perf_bpf_filter__prepare() unconditionally calls init_numa_data(skel, btf) whenever needs_lock_syms is set.

When a user only specifies lock_held(rq_lock), which resolves runqueues via BPF BTF ksym and does not use kallsyms or NUMA zone data, init_numa_data() still queries kallsyms for contig_page_data and node_data. If /proc/kallsyms addresses are restricted (for instance under kptr_restrict=2 or when running with CAP_BPF without CAP_SYSLOG), find_kernel_lock_sym() prints spurious permission error messages for NUMA symbols that rq_lock does not use. Also, on a UMA kernel where contig_page_data exists in /proc/kallsyms with address 0, find_kernel_lock_sym("contig_page_data", &addr) prints an error and returns -EACCES, and init_numa_data() then falls through to query node_data as well.

Conversely, when a user specifies lock_held(zone_lock), init_numa_data() returns void and silently ignores failures if BTF lookup or size resolution for struct zone fails, if both find_kernel_lock_sym("contig_page_data", &addr) and find_kernel_lock_sym("node_data", &addr) fail, or if sysfs__read_str("devices/system/node/online", ...) fails (leaving skel->rodata->nr_nodes as 0).

In resolve_lock_expr(), the zone_lock branch then succeeds without checking whether skel->rodata->contig_page_data_addr or skel->rodata->node_data_addr (with skel->rodata->nr_nodes > 0) was populated. As a result, collect_lock_syms() runs do_collect_zone_lock() with zeroed addresses, populates zero LOCK_CLASS_ZONE_LOCK entries in lock_syms, and attaches kernel-wide spinlock fentry/fexit programs for a filter that can never match any zone_lock.

Should init_numa_data() only be invoked when zone_lock is used, and should failures to resolve the NUMA zone parameters be propagated so that perf_bpf_filter__prepare() aborts instead of attaching a non-functional zone_lock filter?

[ ... ]

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

PATCH v6 8/11 perf bpf-filter: Support slab cache locks (&<name>) in lock_held()

In reply to Ian Rogers

Extend the lock_held() BPF sample filter to support dynamically allocated kernel locks inside slab caches prefixed with '&' (e.g. lock_held(&dentry), lock_held_read(&dentry), lock_held_write(&dentry)).

Reuse do_slab_cache_iter() from lock_data.h via a SEC("iter/kmem_cache") program to resolve the requested slab cache name to its kernel struct kmem_cache * address, and use the bpf_get_kmem_cache() kfunc in record_lock_acquired_owner() and record_lock_released_addr() to match held locks allocated from that slab cache.

---
 tools/perf/Documentation/perf-record.txt     |  25 ++--
 tools/perf/util/bpf-filter.c                 | 125 ++++++++++++++++---
 tools/perf/util/bpf_skel/sample-filter.h     |   5 +
 tools/perf/util/bpf_skel/sample_filter.bpf.c |  48 +++++++
 4 files changed, 175 insertions(+), 28 deletions(-)
tools/perf/Documentation/perf-record.txt +14 -11
index 2b2aaaead76b..8fc3196ed93d 100644
@@ -222,13 +222,15 @@ OPTIONS
 	(alias 'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to
 	<lock> (e.g. 'lock_held(mmap_lock:R)' or 'lock_held(mmap_lock:W)').
 	<lock> can be a kernel lock symbol name (e.g.
-	'lock_held(cgroup_mutex)'), a hexadecimal lock address, a well-known
-	lock name ('mmap_lock', 'siglock', 'rq_lock', 'zone_lock'), or a lock
-	type ('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
-	'rwlock:R', 'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W',
-	'semaphore').  Both read/shared and write/exclusive tracking are
-	supported for 'rwsem' (including 'mmap_lock') and 'rwlock'; 'mutex',
-	'spinlock' (including 'siglock', 'rq_lock', 'zone_lock'), 'rt-mutex',
+	'lock_held(cgroup_mutex)'), a hexadecimal lock address, a slab cache
+	name prefixed with '&' (e.g. 'lock_held(&dentry)',
+	'lock_held_read(&dentry)'), a well-known lock name ('mmap_lock',
+	'siglock', 'rq_lock', 'zone_lock'), or a lock type ('mutex',
+	'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock', 'rwlock:R',
+	'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W', 'semaphore').
+	Both read/shared and write/exclusive tracking are supported for
+	'rwsem' (including 'mmap_lock') and 'rwlock'; 'mutex', 'spinlock'
+	(including 'siglock', 'rq_lock', 'zone_lock'), 'rt-mutex',
 	'semaphore', and 'percpu-rwsem' ('percpu_down_write()') support
 	write/exclusive tracking only.  Note that 'semaphore' tracking
 	('down*()' / 'up()') assumes binary mutex-like usage where the
@@ -254,16 +256,17 @@ OPTIONS
 	'owner' field directly in kernel memory on each sample without attaching
 	any BPF fentry/fexit hooks.  For locks that do not maintain an
 	authoritative per-task owner pointer (such as spinlocks, rwlocks,
-	semaphores, reader-locked rwsems, and lock type filters), it attaches
+	semaphores, reader-locked rwsems, and slab/type filters), it attaches
 	BPF fentry/fexit programs to kernel lock acquire and release functions
 	to track held locks in a BPF map.  These BPF hooks run on every kernel
 	lock acquisition and release for the attached lock family, even when no
 	perf sample is being taken.  To minimize this overhead, only the hooks
 	for the relevant lock family and mode are attached when known (for
 	example, 'lock_held_read(mmap_lock)' only hooks rwsem read functions
-	and 'rq_lock' only hooks spinlock functions), whereas raw hex addresses
-	or symbols without a recognizable lock-type suffix attach hooks across
-	all lock families (including high-frequency spinlocks).
+	and 'rq_lock' only hooks spinlock functions), whereas slab filters
+	('&<slab>'), raw hex addresses, or symbols without a recognizable
+	lock-type suffix attach hooks across all lock families (including
+	high-frequency spinlocks).
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +108 -17

246 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +5 -0
index 836b398dc62b..a65ee780d64d 100644
@@ -76,6 +76,11 @@ enum perf_bpf_lock_target_kind {
 	 * given as a hex address). `entry.value` holds the kernel address.
 	 */
 	PBF_LOCK_ADDR,
+	/*
+	 * Dynamic lock allocated inside a slab cache (`&slab_name`).
+	 * `entry.value` holds the kernel `struct kmem_cache *` address.
+	 */
+	PBF_LOCK_SLAB,
 	/*
 	 * Per-process `current->mm->mmap_lock` (or `mmap_sem`).
 	 */
tools/perf/util/bpf_skel/sample_filter.bpf.c +48 -0

97 lines not on this page · raw message

Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#99 lore raw

Re: [PATCH v6 08/11] perf bpf-filter: Support slab cache locks (&<name>) in lock_held()

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

Extend the lock_held() BPF sample filter to support dynamically allocated kernel locks inside slab caches prefixed with '&' (e.g. lock_held(&dentry), lock_held_read(&dentry), lock_held_write(&dentry)).

Reuse do_slab_cache_iter() from lock_data.h via a SEC("iter/kmem_cache") program to resolve the requested slab cache name to its kernel struct kmem_cache * address, and use the bpf_get_kmem_cache() kfunc in record_lock_acquired_owner() and record_lock_released_addr() to match held locks allocated from that slab cache.

Sashiko has reviewed this patch and found no issues.

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

PATCH v6 9/11 perf test: Add tests for lock_held() BPF sample filter

In reply to Ian Rogers

Add unit tests in parse-events.c for parsing lock_held(), lock_held_read(), and lock_held_exclusive() BPF filter expressions (standalone predicates, negated predicates, and compound group expressions) and extend record_bpf_filter.sh with lock_held(), lock_held_read()/lock_held_write(), and ':R'/':W' recording tests.

Example output:

  # perf test -v 'Parsing of BPF sample filters'
    5: Parse event definition strings               :
    5.7: Parsing of BPF sample filters              : Ok
  # perf test -v 'perf record sample filtering (by BPF) tests'
  112: perf record sample filtering (by BPF) tests  :
  Checking BPF-filter privilege
  Basic bpf-filter test
  Basic bpf-filter test [Success]
  Failing bpf-filter test
  Failing bpf-filter test [Success]
  Group bpf-filter test
  Group bpf-filter test [Success]
  Multiple bpf-filter test
  Multiple bpf-filter test [Success]
  Cgroup bpf-filter test
  Cgroup bpf-filter test [Success]
  Lock-held bpf-filter test
  Lock-held bpf-filter test [Success]
  112: perf record sample filtering (by BPF) tests  : Ok
---
 tools/perf/tests/parse-events.c             | 108 +++++++++++++++++
 tools/perf/tests/shell/record_bpf_filter.sh | 122 ++++++++++++++++++++
 2 files changed, 230 insertions(+)
tools/perf/tests/parse-events.c +108 -0
index 5f6f95c8a5b4..4cf9192762f2 100644
@@ -8,9 +8,11 @@
 #include "debug.h"
 #include "pmu.h"
 #include "pmus.h"
+#include "bpf-filter.h"
 #include "strbuf.h"
 #include <dirent.h>
 #include <errno.h>
+#include <string.h>
 #include "fncache.h"
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -2938,6 +2940,111 @@ static int test__pmu_events_alias2(struct test_suite *test __maybe_unused,
 	return ret;
 }
 
+#ifdef HAVE_BPF_SKEL
+static void clear_bpf_filter_exprs(struct list_head *expr_head)
+{
+	struct perf_bpf_filter_expr *expr, *tmp;
+
+	list_for_each_entry_safe(expr, tmp, expr_head, list) {
+		list_del(&expr->list);
+		perf_bpf_filter_expr__delete(expr);
+	}
+}
+
+static int do_test_bpf_filters(struct list_head *expr_head)
+{
+	struct perf_bpf_filter_expr *expr, *group;
+	const char *compound = "lock_held(rwsem:R) == 1 || lock_held(&dentry) != 0, period > 100";
+
+	/* Simple lock_held(&cgroup_mutex) */
+	TEST_ASSERT_VAL("parse lock_held(&cgroup_mutex)",
+			__perf_bpf_filter__parse(expr_head, "lock_held(&cgroup_mutex)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 1", expr->val == 1);
+	TEST_ASSERT_VAL("lock_name is &cgroup_mutex",
+			expr->lock_name && !strcmp(expr->lock_name, "&cgroup_mutex"));
+	clear_bpf_filter_exprs(expr_head);
+
+	/* Negated !lock_held(cgroup_mutex) */
+	TEST_ASSERT_VAL("parse !lock_held(cgroup_mutex)",
+			__perf_bpf_filter__parse(expr_head, "!lock_held(cgroup_mutex)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 0", expr->val == 0);
+	TEST_ASSERT_VAL("lock_name is cgroup_mutex",
+			expr->lock_name && !strcmp(expr->lock_name, "cgroup_mutex"));
+	clear_bpf_filter_exprs(expr_head);
+
+	/* Read/shared and write/exclusive predicates */
+	TEST_ASSERT_VAL("parse lock_held_read(&mmap_lock)",
+			__perf_bpf_filter__parse(expr_head, "lock_held_read(&mmap_lock)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("part is PBF_LOCK_MODE_READ", expr->part == PBF_LOCK_MODE_READ);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 1", expr->val == 1);
+	TEST_ASSERT_VAL("lock_name is &mmap_lock",
+			expr->lock_name && !strcmp(expr->lock_name, "&mmap_lock"));
+	clear_bpf_filter_exprs(expr_head);
+
+	TEST_ASSERT_VAL("parse !lock_held_exclusive(mmap_lock)",
+			__perf_bpf_filter__parse(expr_head,
+						 "!lock_held_exclusive(mmap_lock)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("part is PBF_LOCK_MODE_WRITE", expr->part == PBF_LOCK_MODE_WRITE);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 0", expr->val == 0);
+	TEST_ASSERT_VAL("lock_name is mmap_lock",
+			expr->lock_name && !strcmp(expr->lock_name, "mmap_lock"));
+	clear_bpf_filter_exprs(expr_head);
+
+	/*
+	 * Comparison and compound group:
+	 * lock_held(rwsem:R) == 1 || lock_held(&dentry) != 0, period > 100
+	 */
+	TEST_ASSERT_VAL("parse compound lock_held filter",
+			__perf_bpf_filter__parse(expr_head, compound) == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("group op", expr->op == PBF_OP_GROUP_BEGIN);
+	TEST_ASSERT_VAL("groups not empty", !list_empty(&expr->groups));
+	group = list_first_entry(&expr->groups, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("first group member lock_name",
+			group->lock_name && !strcmp(group->lock_name, "rwsem:R"));
+	TEST_ASSERT_VAL("first group member op", group->op == PBF_OP_EQ && group->val == 1);
+	group = list_last_entry(&expr->groups, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("second group member lock_name",
+			group->lock_name && !strcmp(group->lock_name, "&dentry"));
+	TEST_ASSERT_VAL("second group member op", group->op == PBF_OP_NEQ && group->val == 0);
+	expr = list_last_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("second term is period", expr->term == PBF_TERM_PERIOD && expr->val == 100);
+
+	return TEST_OK;
+}
+#endif
+
+static int test__bpf_filters(struct test_suite *test __maybe_unused,
+			     int subtest __maybe_unused)
+{
+#ifdef HAVE_BPF_SKEL
+	struct list_head expr_head = LIST_HEAD_INIT(expr_head);
+	int ret = do_test_bpf_filters(&expr_head);
+
+	clear_bpf_filter_exprs(&expr_head);
+	return ret;
+#else
+	return TEST_SKIP;
+#endif
+}
+
 static struct test_case tests__parse_events[] = {
 	TEST_CASE_REASON("Test event parsing",
 			 events2,
@@ -2952,6 +3059,7 @@ static struct test_case tests__parse_events[] = {
 			 "no aliases in sysfs"),
 	TEST_CASE("Parsing of aliased events", pmu_events_alias2),
 	TEST_CASE("Parsing of terms (event modifiers)", terms2),
+	TEST_CASE("Parsing of BPF sample filters", bpf_filters),
 	{	.name = NULL, }
 };
 
tools/perf/tests/shell/record_bpf_filter.sh +122 -0

133 lines not on this page · raw message

Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#101 lore raw

Re: [PATCH v6 09/11] perf test: Add tests for lock_held() BPF sample filter

Sashiko has reviewed this patch and found no issues.
Quoted 29 lines

Add unit tests in parse-events.c for parsing lock_held(), lock_held_read(), and lock_held_exclusive() BPF filter expressions (standalone predicates, negated predicates, and compound group expressions) and extend record_bpf_filter.sh with lock_held(), lock_held_read()/lock_held_write(), and ':R'/':W' recording tests.

Example output:

  # perf test -v 'Parsing of BPF sample filters'
    5: Parse event definition strings               :
    5.7: Parsing of BPF sample filters              : Ok
  # perf test -v 'perf record sample filtering (by BPF) tests'
  112: perf record sample filtering (by BPF) tests  :
  Checking BPF-filter privilege
  Basic bpf-filter test
  Basic bpf-filter test [Success]
  Failing bpf-filter test
  Failing bpf-filter test [Success]
  Group bpf-filter test
  Group bpf-filter test [Success]
  Multiple bpf-filter test
  Multiple bpf-filter test [Success]
  Cgroup bpf-filter test
  Cgroup bpf-filter test [Success]
  Lock-held bpf-filter test
  Lock-held bpf-filter test [Success]
  112: perf record sample filtering (by BPF) tests  : Ok
Quoted 1 line

Sashiko has reviewed this patch and found no issues.

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

PATCH v6 10/11 perf bpf-filter: Extend lock_held() to support RCU, Tasks Trace RCU, and SRCU

In reply to Ian Rogers

Extend the lock_held(<lock>) BPF sample filter to support RCU, Tasks Trace RCU, and SRCU locks:

- 'rcu' (supports both read/shared and write/exclusive modes):
- Read/shared ('lock_held_read(rcu)', 'lock_held(rcu:R)', 'lock_held(rcu_read_lock)'): directly inspects current->rcu_read_lock_nesting in perf_sample_filter via CO-RE (on CONFIG_PREEMPT_RCU kernels), accounting for the baseline rcu_read_lock() nesting acquired by the perf overflow handler itself (bpf_overflow_handler() and do_perf_sw_event()) with zero extra fentry/fexit tracing hooks.
- Write/exclusive ('lock_held_write(rcu)', 'lock_held(rcu:W)'):
attaches fentry/fexit hooks to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), and rcu_barrier() to track grace-period and barrier waits.
- 'srcu' and specific SRCU symbols (e.g. '&srcu_symbol', supports both read/shared and write/exclusive modes):
- Read/shared ('lock_held_read(srcu)', 'lock_held(srcu:R)'): attaches fexit/__srcu_read_lock and fentry/__srcu_read_unlock.
- Write/exclusive ('lock_held_write(srcu)', 'lock_held(srcu:W)'):
attaches fentry/fexit on synchronize_srcu(), synchronize_srcu_expedited(), and srcu_barrier().
- 'rcu-trace' / 'rcu_trace' / 'rcu_read_lock_trace' (supports read/shared mode only): directly inspects current->trc_reader_nesting > 0 on CONFIG_TASKS_TRACE_RCU kernels with zero extra tracing hooks.

Example usage:

  # perf record -a -g -e cycles --filter 'lock_held_read(rcu)' -- sleep 1
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 1.482 MB perf.data (412 samples) ]
  # perf report --stdio --no-children
  # Overhead  Command  Shared Object      Symbol
  # ........  .......  .................  ........................
  #
      14.32%  perf     [kernel.kallsyms]  [k] __d_lookup_rcu
              |
              ---__d_lookup_rcu
                 lookup_fast
                 walk_component
                 link_path_walk
                 path_lookupat
                 filename_lookup
                 vfs_statx
                 __do_sys_newstat
                 do_syscall_64
                 entry_SYSCALL_64_after_hwframe
  # perf record -a -g -e task-clock --filter 'lock_held(rcu:W)' -- sleep 1
  # perf record -a -g -e cycles --filter 'lock_held(srcu)' -- sleep 1
---
 tools/perf/Documentation/perf-record.txt     |  44 ++--
 tools/perf/tests/parse-events.c              |  13 +
 tools/perf/tests/shell/record_bpf_filter.sh  |  20 ++
 tools/perf/util/bpf-filter.c                 | 237 ++++++++++++++++++-
 tools/perf/util/bpf_skel/lock_data.h         |  47 +++-
 tools/perf/util/bpf_skel/sample-filter.h     |  14 ++
 tools/perf/util/bpf_skel/sample_filter.bpf.c | 136 ++++++++++-
 tools/perf/util/bpf_skel/vmlinux/vmlinux.h   |   2 +
 tools/perf/util/lock-contention.c            |   4 +
 tools/perf/util/lock-contention.h            |   4 +-
 10 files changed, 490 insertions(+), 31 deletions(-)
tools/perf/Documentation/perf-record.txt +26 -18
index 8fc3196ed93d..6869a465d8e3 100644
@@ -225,11 +225,17 @@ OPTIONS
 	'lock_held(cgroup_mutex)'), a hexadecimal lock address, a slab cache
 	name prefixed with '&' (e.g. 'lock_held(&dentry)',
 	'lock_held_read(&dentry)'), a well-known lock name ('mmap_lock',
-	'siglock', 'rq_lock', 'zone_lock'), or a lock type ('mutex',
-	'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock', 'rwlock:R',
-	'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W', 'semaphore').
-	Both read/shared and write/exclusive tracking are supported for
-	'rwsem' (including 'mmap_lock') and 'rwlock'; 'mutex', 'spinlock'
+	'siglock', 'rq_lock', 'zone_lock', 'rcu', 'rcu-trace'), or a lock
+	type ('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
+	'rwlock:R', 'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W',
+	'srcu', 'srcu:R', 'srcu:W', 'rcu:R', 'rcu:W', 'semaphore').  Both
+	read/shared and write/exclusive tracking are supported for 'rwsem'
+	(including 'mmap_lock'), 'rwlock', 'rcu', and 'srcu' (where
+	read/shared mode matches 'rcu_read_lock()' / 'srcu_read_lock()'
+	critical sections and write/exclusive mode matches grace-period
+	waits 'synchronize_rcu*()', 'synchronize_srcu*()', 'rcu_barrier()',
+	and 'srcu_barrier()'); 'rcu-trace' ('rcu_read_lock_trace()')
+	supports read/shared tracking only; and 'mutex', 'spinlock'
 	(including 'siglock', 'rq_lock', 'zone_lock'), 'rt-mutex',
 	'semaphore', and 'percpu-rwsem' ('percpu_down_write()') support
 	write/exclusive tracking only.  Note that 'semaphore' tracking
@@ -251,19 +257,21 @@ OPTIONS
 	      --filter 'lock_held(mutex) || lock_held(rwsem)'
 
 	When filtering on a specific mutex symbol ('*_mutex'), rt-mutex symbol
-	('*_rt_mutex'), or write-locked 'mmap_lock' ('lock_held_write(mmap_lock)'
-	or 'lock_held(mmap_lock:W)'), 'perf_sample_filter' inspects the lock's
-	'owner' field directly in kernel memory on each sample without attaching
-	any BPF fentry/fexit hooks.  For locks that do not maintain an
-	authoritative per-task owner pointer (such as spinlocks, rwlocks,
-	semaphores, reader-locked rwsems, and slab/type filters), it attaches
-	BPF fentry/fexit programs to kernel lock acquire and release functions
-	to track held locks in a BPF map.  These BPF hooks run on every kernel
-	lock acquisition and release for the attached lock family, even when no
-	perf sample is being taken.  To minimize this overhead, only the hooks
-	for the relevant lock family and mode are attached when known (for
-	example, 'lock_held_read(mmap_lock)' only hooks rwsem read functions
-	and 'rq_lock' only hooks spinlock functions), whereas slab filters
+	('*_rt_mutex'), write-locked 'mmap_lock' ('lock_held_write(mmap_lock)'
+	or 'lock_held(mmap_lock:W)'), or 'rcu:R' / 'rcu-trace' (which inspect
+	'current->rcu_read_lock_nesting' / 'current->trc_reader_nesting'),
+	'perf_sample_filter' inspects the kernel fields directly on each sample
+	without attaching any BPF fentry/fexit hooks.  For locks that do not
+	maintain an authoritative per-task owner pointer (such as spinlocks,
+	rwlocks, semaphores, reader-locked rwsems, SRCU locks, RCU synchronize
+	waits, and slab/type filters), it attaches BPF fentry/fexit programs to
+	kernel lock acquire and release functions to track held locks in a BPF
+	map.  These BPF hooks run on every kernel lock acquisition and release
+	for the attached lock family, even when no perf sample is being taken.
+	To minimize this overhead, only the hooks for the relevant lock family
+	and mode are attached when known (for example, 'lock_held_read(mmap_lock)'
+	only hooks rwsem read functions, 'srcu' only hooks SRCU functions, and
+	'rq_lock' only hooks spinlock functions), whereas slab filters
 	('&<slab>'), raw hex addresses, or symbols without a recognizable
 	lock-type suffix attach hooks across all lock families (including
 	high-frequency spinlocks).
tools/perf/tests/parse-events.c +13 -0
index 4cf9192762f2..730466b7ebf6 100644
@@ -2980,6 +2980,19 @@ static int do_test_bpf_filters(struct list_head *expr_head)
 			expr->lock_name && !strcmp(expr->lock_name, "cgroup_mutex"));
 	clear_bpf_filter_exprs(expr_head);
 
+	/* RCU and SRCU lock_held(rcu) || lock_held(srcu) */
+	TEST_ASSERT_VAL("parse lock_held(rcu)",
+			__perf_bpf_filter__parse(expr_head, "lock_held(rcu)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("part is PBF_LOCK_MODE_ANY", expr->part == PBF_LOCK_MODE_ANY);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 1", expr->val == 1);
+	TEST_ASSERT_VAL("lock_name is rcu",
+			expr->lock_name && !strcmp(expr->lock_name, "rcu"));
+	clear_bpf_filter_exprs(expr_head);
+
 	/* Read/shared and write/exclusive predicates */
 	TEST_ASSERT_VAL("parse lock_held_read(&mmap_lock)",
 			__perf_bpf_filter__parse(expr_head, "lock_held_read(&mmap_lock)") == 0);
tools/perf/tests/shell/record_bpf_filter.sh +20 -0
index ebaf8ee41622..47f697f53a85 100755
@@ -247,6 +247,26 @@ test_bpf_filter_lock_held() {
     return
   fi
 
+  if ! perf record -e task-clock --filter 'lock_held_write(rcu) || lock_held(srcu)' \
+       -o "${perfdata}" true 2> /dev/null
+  then
+    echo "Lock-held bpf-filter test [Failed rcu:W/srcu]"
+    err=1
+    return
+  fi
+
+  if ! perf record -e task-clock --filter 'lock_held_read(rcu)' \
+       -o "${perfdata}" true 2> /dev/null
+  then
+    if ! perf record -e task-clock --filter 'lock_held_read(rcu)' \
+         -o /dev/null true 2>&1 | grep -q CONFIG_PREEMPT_RCU
+    then
+      echo "Lock-held bpf-filter test [Failed lock_held_read(rcu)]"
+      err=1
+      return
+    fi
+  fi
+
   if ! perf record -e task-clock \
        --filter 'lock_held_read(mmap_lock) || lock_held_write(mmap_lock)' \
        -o "${perfdata}" true 2> /dev/null
tools/perf/util/bpf-filter.c +229 -8

311 lines not on this page · raw message

tools/perf/util/bpf_skel/lock_data.h +45 -2

72 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +14 -0
index a65ee780d64d..7abc530ed50d 100644
@@ -101,6 +101,20 @@ enum perf_bpf_lock_target_kind {
 	 * low two bytes: `flag1 | (flag2 << 8)` (with 0xff indicating unused).
 	 */
 	PBF_LOCK_TYPE,
+	/*
+	 * Preemptible RCU read-side lock (`rcu` / `rcu_read_lock`).
+	 * Inspected directly via `current->rcu_read_lock_nesting > entry.value`,
+	 * where `entry.value` is the baseline RCU nesting depth added by the
+	 * kernel perf overflow path.
+	 */
+	PBF_LOCK_RCU,
+	/*
+	 * Tasks Trace RCU read-side lock (`rcu-trace` / `rcu_read_lock_trace`).
+	 * Inspected directly via `current->trc_reader_nesting > entry.value`,
+	 * where `entry.value` is the baseline nesting depth added by the
+	 * kernel event tracing path.
+	 */
+	PBF_LOCK_RCU_TRACE,
 };
 
 /*
tools/perf/util/bpf_skel/sample_filter.bpf.c +134 -2

169 lines not on this page · raw message

tools/perf/util/bpf_skel/vmlinux/vmlinux.h +2 -0
index b75ddc6846bb..1fb91a829d54 100644
@@ -119,6 +119,8 @@ struct task_struct {
 	struct signal_struct  *signal;
 	struct sighand_struct *sighand;
 	struct css_set	      *cgroups;
+	int		      rcu_read_lock_nesting;
+	int		      trc_reader_nesting;
 } __attribute__((preserve_access_index));
 
 struct trace_entry {
tools/perf/util/lock-contention.c +4 -0
index f6e68d740860..37415f7b7f2c 100644
@@ -39,6 +39,10 @@ const struct perf_lock_type lock_type_table[] = {
 	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex",	"mutex" },
 	/* alias for optimistic spinning only */
 	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex:spin",	"mutex-spin" },
+	{ LCB_F_SRCU | LCB_F_READ,	"srcu:R",	"srcu" },
+	{ LCB_F_SRCU | LCB_F_WRITE,	"srcu:W",	"srcu" },
+	{ LCB_F_RCU | LCB_F_READ,	"rcu:R",	"rcu" },
+	{ LCB_F_RCU | LCB_F_WRITE,	"rcu:W",	"rcu" },
 };
 
 int parse_call_stack(const struct option *opt __maybe_unused, const char *str,
tools/perf/util/lock-contention.h +3 -1
index 68e9bd77e8a9..88b2c11244ad 100644
@@ -128,6 +128,8 @@ struct thread_stat {
 #define LCB_F_RT	(1U << 3)
 #define LCB_F_PERCPU	(1U << 4)
 #define LCB_F_MUTEX	(1U << 5)
+#define LCB_F_SRCU	(1U << 6)
+#define LCB_F_RCU	(1U << 7)
 
 struct perf_lock_type {
 	unsigned int flags;
@@ -140,7 +142,7 @@ struct perf_lock_type {
 	const char *lock_name;
 };
 
-extern const struct perf_lock_type lock_type_table[14];
+extern const struct perf_lock_type lock_type_table[18];
 
 struct evlist;
 struct machine;
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#103 lore raw

Re: [PATCH v6 10/11] perf bpf-filter: Extend lock_held() to support RCU, Tasks Trace RCU, and SRCU

Sashiko has reviewed this patch and found no issues.
Quoted 17 lines

Extend the lock_held(<lock>) BPF sample filter to support RCU, Tasks Trace RCU, and SRCU locks:

- 'rcu' (supports both read/shared and write/exclusive modes):
- Read/shared ('lock_held_read(rcu)', 'lock_held(rcu:R)', 'lock_held(rcu_read_lock)'): directly inspects current->rcu_read_lock_nesting in perf_sample_filter via CO-RE (on CONFIG_PREEMPT_RCU kernels), accounting for the baseline rcu_read_lock() nesting acquired by the perf overflow handler itself (bpf_overflow_handler() and do_perf_sw_event()) with zero extra fentry/fexit tracing hooks.
- Write/exclusive ('lock_held_write(rcu)', 'lock_held(rcu:W)'):
attaches fentry/fexit hooks to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), and rcu_barrier() to track grace-period and barrier waits.
[ ... ]

Quoted 4 lines
  # perf record -a -g -e task-clock --filter 'lock_held(rcu:W)' -- sleep 1
  # perf record -a -g -e cycles --filter 'lock_held(srcu)' -- sleep 1

Sashiko has reviewed this patch and found no issues.

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

PATCH v6 11/11 perf lock contention: Extend BPF lock contention to RCU and SRCU

In reply to Ian Rogers

Extend 'perf lock contention --use-bpf' to track RCU and SRCU grace-period and barrier waits:

- Attach fentry/fexit programs to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), rcu_barrier(), synchronize_srcu(), synchronize_srcu_expedited(), and srcu_barrier() when available in BTF.
- Support filtering by lock type ('-Y rcu', '-Y rcu:W', '-Y srcu', '-Y srcu:W') and by lock name ('-L rcu' or specific srcu_struct symbol names).

Example usage:

  # perf lock con -a -b -Y rcu,srcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait         type   caller
       35.12 ms      8.78 ms        rcu:W   cleanup_net+0x284
        7.84 ms      3.92 ms       srcu:W   __fsnotify_parent+0x114
  # perf lock con -a -b -l -L rcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait            address   symbol
       35.12 ms      8.78 ms   ffffffff83754dc0   rcu (rcu)
---
 tools/perf/Documentation/perf-lock.txt        |   7 +-
 tools/perf/tests/shell/lock_contention.sh     |  14 ++
 tools/perf/util/bpf_lock_contention.c         | 174 +++++++++++++-
 .../perf/util/bpf_skel/lock_contention.bpf.c  | 222 ++++++++++++++----
 tools/perf/util/machine.c                     |  11 +
 5 files changed, 366 insertions(+), 62 deletions(-)
tools/perf/Documentation/perf-lock.txt +5 -2
index c17b3e318169..bfeb98c976e3 100644
@@ -188,11 +188,14 @@ CONTENTION OPTIONS
 	Show lock contention only for given lock types (comma separated list).
 	Available values are:
 	  semaphore, spinlock, rwlock, rwlock:R, rwlock:W, rwsem, rwsem:R, rwsem:W,
-	  rtmutex, rwlock-rt, rwlock-rt:R, rwlock-rt:W, percpu-rwmem, pcpu-sem,
-	  pcpu-sem:R, pcpu-sem:W, mutex
+	  rtmutex, rwlock-rt, rwlock-rt:R, rwlock-rt:W, percpu-rwsem, pcpu-sem,
+	  pcpu-sem:R, pcpu-sem:W, mutex, srcu, srcu:W, rcu, rcu:W
 
 	Note that RW-variant of locks have :R and :W suffix.  Names without the
 	suffix are shortcuts for the both variants.  Ex) rwsem = rwsem:R + rwsem:W.
+	For RCU and SRCU with --use-bpf, contention tracks grace-period and
+	barrier waits (synchronize_rcu*(), synchronize_srcu*(), rcu_barrier(),
+	srcu_barrier()).
 
 -L::
 --lock-filter=<value>::
tools/perf/tests/shell/lock_contention.sh +14 -0
index 5df9a0cd48a3..999dcfd1ef26 100755
@@ -181,6 +181,13 @@ test_type_filter()
 		err=1
 		exit
 	fi
+
+	perf lock con -a -b -Y rcu -q -- true > /dev/null 2> ${result}
+	if [ "$(grep -c -v -w rcu "${result}")" != "0" ]; then
+		echo "[Fail] BPF result should not have non-rcu locks:" "$(cat "${result}")"
+		err=1
+		exit
+	fi
 }
 
 test_lock_filter()
@@ -224,6 +231,13 @@ test_lock_filter()
 		err=1
 		exit
 	fi
+
+	perf lock con -a -b -L rcu -q -- true > /dev/null 2> ${result}
+	if [ "$(grep -c -v -w rcu "${result}")" != "0" ]; then
+		echo "[Fail] BPF result should not have non-rcu locks:" "$(cat "${result}")"
+		err=1
+		exit
+	fi
 }
 
 test_stack_filter()
tools/perf/util/bpf_lock_contention.c +161 -13

239 lines not on this page · raw message

tools/perf/util/bpf_skel/lock_contention.bpf.c +175 -47

361 lines not on this page · raw message

tools/perf/util/machine.c +11 -0
index 1d9d3bf57720..0a0f223b3335 100644
@@ -3379,6 +3379,17 @@ bool machine__is_lock_function(struct machine *machine, u64 addr)
 			return true;
 	}
 
+	{
+		struct symbol *sym = machine__find_kernel_symbol(machine, addr, NULL);
+
+		if (sym && (!strncmp(sym->name, "synchronize_rcu", 15) ||
+			    !strncmp(sym->name, "synchronize_srcu", 16) ||
+			    !strcmp(sym->name, "__synchronize_srcu") ||
+			    !strcmp(sym->name, "rcu_barrier") ||
+			    !strcmp(sym->name, "srcu_barrier")))
+			return true;
+	}
+
 	return false;
 }
 
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#105 lore raw

Re: [PATCH v6 11/11] perf lock contention: Extend BPF lock contention to RCU and SRCU

Sashiko has reviewed this patch and found no issues.
Quoted 19 lines

Extend 'perf lock contention --use-bpf' to track RCU and SRCU grace-period and barrier waits:

- Attach fentry/fexit programs to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), rcu_barrier(), synchronize_srcu(), synchronize_srcu_expedited(), and srcu_barrier() when available in BTF.
- Support filtering by lock type ('-Y rcu', '-Y rcu:W', '-Y srcu', '-Y srcu:W') and by lock name ('-L rcu' or specific srcu_struct symbol names).

Example usage:

  # perf lock con -a -b -Y rcu,srcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait         type   caller
       35.12 ms      8.78 ms        rcu:W   cleanup_net+0x284
        7.84 ms      3.92 ms       srcu:W   __fsnotify_parent+0x114
Quoted 6 lines
  # perf lock con -a -b -l -L rcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait            address   symbol
       35.12 ms      8.78 ms   ffffffff83754dc0   rcu (rcu)

Sashiko has reviewed this patch and found no issues.

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

v7 cover perf bpf-filter / lock contention: Add lock_held() sample filter and RCU/SRCU support

In reply to Ian Rogers

This series adds a new BPF sample filter predicate, lock_held(<lock>) (along with lock_held_read(<lock>) / lock_held_shared(<lock>), lock_held_write(<lock>) / lock_held_exclusive(<lock>), and :R / :W mode suffixes), to perf record --filter, allowing perf event samples to be recorded only when a specified kernel lock is held (or not held with !) by the running kernel thread or CPU. It also fixes a bpf_link memory leak in perf_bpf_filter__prepare(), enables BPF sample filters on tracepoint events (PERF_TYPE_TRACEPOINT), and extends both lock_held() and perf lock contention --use-bpf to support RCU and SRCU.

For example:

  # perf record -a -g -e cycles --filter 'lock_held(cgroup_mutex)' -- ...
  # perf record -a -g -e cycles --filter 'lock_held_read(mmap_lock)' -- ...
  # perf record -a -g -e cycles --filter 'lock_held(mmap_lock:W)' -- ...
  # perf record -a -g -e cycles --filter 'lock_held_read(rcu)' -- ...
  # perf lock contention -a -b -Y rcu,srcu -- sleep 1

An important use-case is detecting memory allocations or direct memory reclaim occurring while kernel locks are held, which can stall lock waiters for extended periods under memory pressure:

# Direct memory reclaim triggered while holding any mutex or rwsem:

  # perf record -a -g -e vmscan:mm_vmscan_direct_reclaim_begin \
      --filter 'lock_held(mutex) || lock_held(rwsem)' -- ...

# Page allocations permitted to enter direct reclaim (__GFP_DIRECT_RECLAIM)

  # while holding a mutex or rwsem:
  # perf record -a -g -e kmem:mm_page_alloc \
      --filter 'gfp_flags & 0x400' \
      --filter 'lock_held(mutex) || lock_held(rwsem)' -- ...

# Major page faults occurring while holding a mutex or rwsem:

  # perf record -a -g -e major-faults \
      --filter 'lock_held(mutex) || lock_held(rwsem)' -- ...

Supported <lock> specifications match perf lock contention:
- Global/static kernel lock symbols (e.g. lock_held(cgroup_mutex))
- Hexadecimal kernel lock addresses
- Slab cache names prefixed with & (e.g. lock_held(&dentry), lock_held_read(&dentry))
- Well-known per-process, semi-global, and RCU locks: mmap_lock, siglock, rq_lock, zone_lock, rcu, rcu-trace
- Lock types and flags: mutex, spinlock, rwsem, rwsem:R, rwsem:W, rwlock, rwlock:R, rwlock:W, rt-mutex, percpu-rwsem, pcpu-sem:W, srcu, srcu:R, srcu:W, rcu:R, rcu:W, semaphore

Limitations and weaknesses in determining whether a lock is held:
- Inlined lock/unlock operations:
- When the kernel is configured to inline spinlock or rwlock operations (CONFIG_INLINE_SPIN_LOCK, CONFIG_INLINE_READ_LOCK, CONFIG_INLINE_WRITE_LOCK, !CONFIG_UNINLINE_SPIN_UNLOCK, CONFIG_INLINE_*_UNLOCK*, etc.), _raw_spin_lock* / _raw_spin_unlock* and _raw_read_lock* / _raw_write_lock* are inlined into callers and have no BTF function entry points for fentry/fexit to attach to. configure_lock_progs() verifies that both acquire and release entry points exist in BTF before enabling a lock family.
- Fast-path percpu_down_read() / percpu_up_read() and srcu_read_lock_fast() / srcu_read_unlock_fast() are inlined per-CPU counter increments without function calls, so only percpu_down_write() / percpu_up_write() and out-of-line __srcu_read_lock*() / __srcu_read_unlock*() can be hooked.
- On !CONFIG_PREEMPT_RCU kernels, rcu_read_lock() compiles to preempt_disable() and does not maintain current->rcu_read_lock_nesting in task_struct, so lock_held(rcu) read-side inspection requires CONFIG_PREEMPT_RCU.
- Lack of an inspectable owner field on non-exclusive / spinning locks:
- While struct mutex, struct rt_mutex, and write-locked struct rw_semaphore store the owning task_struct * in lock->owner (allowing perf_sample_filter to inspect kernel memory directly on sample overflow when filtering by lock address without attaching any fentry/fexit hooks for *_mutex, *_rt_mutex, and mmap_lock:W), spinlocks, rwlocks, semaphores, SRCU, and reader-locked rw_semaphores (where __up_read() does not clear sem->owner when !CONFIG_DEBUG_RWSEMS) do not maintain an authoritative per-task owner pointer.
- Tracking these locks (as well as slab-cache and lock-type filters) relies on fexit (acquire) and fentry (release) BPF hooks maintaining the held_locks BPF LRU hash map:
- Any such lock already held before perf record attaches its BPF programs will not be present in held_locks until it is released and re-acquired.
- The attached fentry/fexit hooks execute on every kernel lock acquire and release for the hooked lock family across the system, adding tracing overhead outside of perf sample handling.
- Cross-task semaphore signaling (down*() / up()):
- Counting struct semaphores do not enforce same-task ownership in the
kernel: when a semaphore is used as a completion/signaling mechanism (down() in one task woken by up() in another task or interrupt handler, which proposed kernel dependency trackers like CONFIG_DEPT model as wait/event dependencies bounded by execution context rather than lock ownership), fexit/down and fentry/up do not pair on the same task ID. Semaphore hooks are therefore only enabled when semaphore or a *_sem symbol (such as console_sem) is explicitly specified, and held_locks uses BPF_MAP_TYPE_LRU_HASH so any unpaired cross-task entries are automatically evicted.
- Shared trace_event_call->prog_array on PERF_TYPE_TRACEPOINT:
- In kernel/events/core.c, __perf_event_set_bpf_prog() requires BPF_PROG_TYPE_TRACEPOINT for PERF_TYPE_TRACEPOINT events and attaches the program to event->tp_event->prog_array on the shared trace_event_call. Because perf_trace_run_bpf_submit() executes trace_call_bpf() before perf_tp_event(), returning 0 from perf_tp_sample_filter filters that tracepoint invocation before perf_tp_event() iterates call->perf_events (affecting concurrent perf_event listeners on the same tracepoint while the privileged perf record session is active).

Patch overview (patches 1-2 are standalone fixes independent of the rest of the series):
1. "perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF":
Attaches perf_sample_filter directly via PERF_EVENT_IOC_SET_BPF in perf_bpf_filter__prepare(), matching the pinned filter path and avoiding leaking struct bpf_link_perf or double-closing FD(evsel, x, y).
2. "perf bpf-filter: Support BPF sample filters on tracepoint events":
Adds SEC("tracepoint") int perf_tp_sample_filter(void *ctx) so BPF sample filters can attach to PERF_TYPE_TRACEPOINT events (where __perf_event_set_bpf_prog() in kernel/events/core.c requires BPF_PROG_TYPE_TRACEPOINT rather than BPF_PROG_TYPE_PERF_EVENT).
3. "perf lock contention: Share common BPF and lock type definitions in lock_data.h": Pure refactoring moving lock_type_table to util/lock-contention.c and LCB_F_* flags, CO-RE structs, and common BPF lock helpers into tools/perf/util/bpf_skel/lock_data.h.
4. "perf lock contention: Extend get_lock_owner() for rt_mutex and mutex handoff": Extends get_lock_owner() in lock_data.h to support rt_mutex (LCB_F_RT), CONFIG_PREEMPT_RT mutexes, and MUTEX_FLAG_HANDOFF.
5. "perf bpf-filter: Add lock_held() sample filter for global mutexes":
Adds the lock_held(), lock_held_read()/lock_held_shared(), lock_held_write()/lock_held_exclusive(), and :R/:W filter syntax and evaluates global/static kernel mutexes via direct lock->owner inspection.
6. "perf bpf-filter: Extend lock_held() to other kernel lock types":
Extends lock_held() to spinlocks, rwsems, rwlocks, rt-mutexes, percpu-rwsems, and semaphores (as well as hex addresses and lock type filters) using a held_locks BPF LRU hash map updated by selectively attached fentry/fexit hooks.
7. "perf bpf-filter: Support per-process and semi-global locks in lock_held()": Adds support for mmap_lock, siglock, rq_lock, and zone_lock.
8. "perf bpf-filter: Support slab cache locks (&<name>) in lock_held()":
Adds support for slab cache locks prefixed with & (e.g. lock_held(&dentry)) using the kmem_cache BPF iterator and slab_caches map.
9. "perf test: Add tests for lock_held() BPF sample filter": Adds unit tests in tests/parse-events.c and shell tests in tests/shell/record_bpf_filter.sh.
10. "perf bpf-filter: Extend lock_held() to support RCU, Tasks Trace RCU,

    and SRCU": Supports `rcu` (`rcu:R` via direct
    `current->rcu_read_lock_nesting` inspection with zero tracing hooks;
    `rcu:W` via `synchronize_rcu*()` / `rcu_barrier()` hooks),
    `rcu-trace` (via `current->trc_reader_nesting`), and `srcu`
    (`srcu:R` via `__srcu_read_lock*` / `__srcu_read_unlock*`; `srcu:W`
    via `synchronize_srcu*()` / `srcu_barrier()`).

11. "perf lock contention: Extend BPF lock contention to RCU and SRCU":
Extends perf lock contention --use-bpf to track RCU and SRCU grace-period and barrier waits (-Y rcu, -Y srcu, -L rcu).

Changes in v7:
- Route tracepoint --filter strings to BPF filters only for BPF terms
that aren't fields of the tracepoint, checking fields with the tracefs
format file when built without libtraceevent, ignoring words inside
quoted string literals, keeping "cpu" as an ftrace filter (ftrace's
generic "cpu" field), and rejecting filters that mix BPF terms with
tracepoint fields of the same name, such as "pid" on
sched:sched_wakeup (patch 2).
- Match module lock symbols with a "\t[<module>]" kallsyms suffix and
stop treating symbols between _edata and __bss_start as data in find_lock_sym_cb() (patch 5).
- Classify lock symbols with a shared classify_lock_sym() in both prescan_one_lock_expr() and resolve_lock_expr(), using the __percpu_rwsem_rc_<name> BTF variable (so percpu-rwsems like
dup_mmap_sem, cpu_hotplug_lock and cgroup_threadgroup_rwsem only hook percpu_down_write()/percpu_up_write()), the variable's BTF type when
vmlinux BTF has global variables, and otherwise the name suffix.
'*_sem' symbols may be rw_semaphores (namespace_sem, uts_sem), so
hook both semaphore and rwsem entry points and allow read mode
(patches 5 and 6, Namhyung).
- Add a comment above lock_progs[] in patch 6 explaining why mutex
hooks are still needed (lock type filters, hex addresses, and symbols
of unknown type) even though specific global mutexes are checked via
their owner field (Namhyung).
- Only read NUMA zone data from kallsyms/sysfs for lock_held(zone_lock),
not rq_lock, and fail filter setup when it can't be determined rather
than attaching a filter that never matches (patch 7).
- Link to v6: https://lore.kernel.org/linux-perf-users/[email protected]/

Changes in v6:
- Drop "perf lock contention: Filter events before creating lock_stat"
as Arnaldo cherry-picked it.
- Add an inline comment above pin_filter_object() in util/bpf-filter.c
in patch 2 explaining why bpf_object__pin() / bpf_object__unpin()
cannot be used when programs in sample_filter.bpf.c have autoload
disabled (Namhyung).
- Split the lock_data.h refactoring into a pure code-movement commit
(patch 3) and a separate commit extending get_lock_owner() for
rt_mutex and MUTEX_FLAG_HANDOFF (patch 4), keep lock_syms in its
original location in lock_contention.bpf.c, and add a comment above
#ifdef __BPF__ in lock_data.h explaining that the header is shared
between userspace and BPF programs (Namhyung).
- Split the lock_held() implementation into 4 incremental commits
(patches 5-8): (5) core parser, expression evaluation, and global mutex
support; (6) other kernel lock types (spinlock, rwsem, rwlock,
rt-mutex, percpu-rwsem, semaphore), hex addresses, and lock type
filters; (7) per-process (mmap_lock, siglock) and semi-global
(rq_lock, zone_lock) locks; and (8) slab cache locks (&<name>)
(Namhyung).
- Update is_possible_tp_filter() in util/parse-events.c in patch 2
to check all tracepoint BPF sample filter terms enabled by that patch
(uid, gid, tid, pid, cpu, time, cgroup) using
word-boundary matching (has_filter_word()) and !evsel__field() so
they are routed to evsel->bpf_filters when not matching a tracepoint
format field, and extend bpf_tp_terms[] with lock_held* in patch 5.
- Replace strtailcmp(base, ...) with str_ends_with(base, ...) in prescan_one_lock_expr() and resolve_lock_expr() in
util/bpf-filter.c (patches 5, 6, and 10) so lock symbol names shorter
than a tested suffix (such as lock vs spinlock, or u_rwsem vs percpu_rwsem) are not misclassified.
- Use a CO-RE flavor struct struct rt_mutex_base___new in lock_data.h
(patch 4) and add explicit standard C header includes (<errno.h>,
<stdio.h>, <unistd.h>, <string.h>, <stddef.h>, <stdlib.h>) in
patches 1, 2, and 11 for musl libc compatibility.
- Reject kernel text functions, module text functions, and absolute or
undefined symbols when resolving lock addresses from /proc/kallsyms,
and check for __percpu_rwsem_rc_<name> in BTF so percpu_rw_semaphore
symbols ending in _rwsem (such as cgroup_threadgroup_rwsem or
file_rwsem) do not set PBF_LOCK_DIRECT_RWSEM or allow read-only mode.
- Link to v5: https://lore.kernel.org/linux-perf-users/[email protected]/

Changes in v5:
- Add patch 2 ("perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF") attaching BPF sample filters via ioctl(..., PERF_EVENT_IOC_SET_BPF, fd) instead of bpf_program__attach_perf_event_opts(), fixing the bpf_link memory leak without double-closing FD(evsel, x, y), and use the same attachment in patch 3 for tracepoint sample filters (Namhyung).
- Expand patch 3's commit message to detail why pin_filter_object() and unpin_filter_object() replace bpf_object__pin() and bpf_object__unpin() when autoload is disabled on perf_tp_sample_filter (Namhyung).
- Store the resolved lock target in perf_bpf_filter_entry.value (with op normalized to PBF_OP_EQ or PBF_OP_NEQ), keeping struct perf_bpf_filter_entry unchanged at 24 bytes for backwards compatibility with pinned filters maps.
- Add a CO-RE struct rt_mutex___old fallback in get_lock_owner() in lock_data.h for kernels prior to v5.15, and pass baseline nesting depth to is_rcu_trace_lock_held() for syscall tracepoints.

Changes in v4:
- Move the two bugfix commits (Filter events before creating lock_stat and Support BPF sample filters on tracepoint events) to patches 1 and 2 at the start of the series for easier cherry-picking.
- Reserve leading & strictly for slab cache locks (e.g. lock_held(&dentry)) so global/static lock symbols and well-known locks do not use & (e.g. lock_held(cgroup_mutex), lock_held_read(mmap_lock)), matching perf lock contention (Namhyung).
- Skip attaching fentry/fexit hooks when filtering on a specific mutex symbol (*_mutex), rt_mutex symbol (*_rt_mutex), or write-locked mmap_lock (mmap_lock:W / lock_held_write(mmap_lock)), evaluating them purely via direct owner inspection (Namhyung).
- Use a CO-RE flavor struct struct mutex___non_rt in get_lock_owner() in lock_data.h so GEN_VMLINUX_H=1 builds succeed on CONFIG_PREEMPT_RT=y kernels.
- Switch held_locks to BPF_MAP_TYPE_LRU_HASH, exclude LOCK_PROG_SEM from LOCK_PROG_ALL unless semaphore or a *_sem symbol is explicitly requested, and document cross-task semaphore signaling limitations (and comparison with CONFIG_DEPT).
- Skip LCB_F_MUTEX | LCB_F_SPIN in parse_lock_type_name(), reject read-only mode on exclusive-only lock symbol suffixes in resolve_lock_expr(), and check needed_groups & supported_groups before masking needed_groups in configure_lock_progs().
- Recursively traverse anonymous structs/unions in btf_has_task_field() so lock_held(rcu) and lock_held(rcu-trace) work on CONFIG_RANDSTRUCT kernels.

Changes in v3:
- Move the writer-only rw_semaphore check out of get_lock_owner() in lock_data.h into is_rwsem_writer_owner() in sample_filter.bpf.c so perf lock contention -b -o still reports reader owners when a writer contends on a reader-owned rw_semaphore, and scope is_direct_lock_owner() by lock type (PBF_LOCK_DIRECT_MUTEX, PBF_LOCK_DIRECT_RWSEM, PBF_LOCK_DIRECT_RTMUTEX).
- Add SEC("tracepoint") int perf_tp_sample_filter(void *ctx) so BPF sample filters (lock_held(), uid, gid, etc.) can attach to PERF_TYPE_TRACEPOINT events (such as kmem:mm_page_alloc and vmscan:mm_vmscan_direct_reclaim_begin), check libbpf_get_error() when attaching, and document memory allocation / direct reclaim filtering with lock_held().
- Return early in init_numa_data() in bpf-filter.c when node_data cannot be resolved and check node_data_addr != 0 in do_collect_zone_lock().
- Avoid double-counting _raw_read_lock_irq / _raw_read_lock_bh in sample_filter.bpf.c on CONFIG_GENERIC_LOCKBREAK=y && !CONFIG_DEBUG_LOCK_ALLOC kernels where they call _raw_read_lock_irqsave().
- Offset rcu_state_addr by 1 byte so it is distinct from &rcu_state.node[0].lock at offset 0 of rcu_state, and pass bool is_rcu to do_contention_end() in lock_contention.bpf.c so tp_btf/contention_end and RCU/SRCU fexit hooks never cross-match timestamp maps.

Changes in v2:
- Guard BPF_CORE_READ(mutex, owner.counter) with bpf_core_field_exists and fall back to struct rt_mutex_base in get_lock_owner() so CO-RE relocation succeeds on CONFIG_PREEMPT_RT=y kernels.
- Add CONFIG_DEBUG_LOCK_ALLOC=y lock entry points (_mutex_lock_nest_lock, _mutex_lock_killable, _mutex_trylock_nest_lock, _down_write_nest_lock, _raw_spin_lock_nest_lock, _rt_mutex_lock_nest_lock) to sample_filter.bpf.c and lock_progs[].
- Verify in supported_lock_prog_groups() that both acquire and all unlock BTF entry points exist for a lock family before enabling its tracing hooks, preventing acquire-only attachment when spinlock/rwlock unlock functions are inlined.
- Enable LOCK_PROG_PERCPU_RWSEM alongside LOCK_PROG_RWSEM_WRITE when a symbol name ends in rwsem (such as cgroup_threadgroup_rwsem).
- Gate record_lock_acquired(ctx, LCB_F_READ) in fexit_downgrade_write on track_rwsem_read and verify non-zero read/write counts in record_lock_released_addr() before decrementing aggregate slab/type counts.
- Adjust stack skip depth by 2 for fentry RCU/SRCU programs in lock_contention.bpf.c and recognize synchronize_rcu*, synchronize_srcu*, rcu_barrier, and srcu_barrier in machine__is_lock_function().
- Add patch fixing report_lock_contention_begin_event() to check type, address, and callstack filters before creating lock_stat entries.

Assisted-by Antigravity:gemini-3.1-pro

Ian Rogers (11):
perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF perf bpf-filter: Support BPF sample filters on tracepoint events perf lock contention: Share common BPF and lock type definitions in
lock_data.h
perf lock contention: Extend get_lock_owner() for rt_mutex and mutex
handoff
perf bpf-filter: Add lock_held() sample filter for global mutexes perf bpf-filter: Extend lock_held() to other kernel lock types perf bpf-filter: Support per-process and semi-global locks in

    lock_held()

perf bpf-filter: Support slab cache locks (&<name>) in lock_held() perf test: Add tests for lock_held() BPF sample filter perf bpf-filter: Extend lock_held() to support RCU, Tasks Trace RCU,
and SRCU
perf lock contention: Extend BPF lock contention to RCU and SRCU

 tools/perf/Documentation/perf-lock.txt        |    7 +-
 tools/perf/Documentation/perf-record.txt      |   79 +-
 tools/perf/builtin-lock.c                     |   27 -
 tools/perf/tests/parse-events.c               |  121 ++
 tools/perf/tests/shell/lock_contention.sh     |   14 +
 tools/perf/tests/shell/record_bpf_filter.sh   |  142 ++
 tools/perf/util/bpf-filter.c                  | 1677 ++++++++++++++++-
 tools/perf/util/bpf-filter.h                  |   13 +
 tools/perf/util/bpf-filter.l                  |   31 +-
 tools/perf/util/bpf-filter.y                  |   47 +-
 tools/perf/util/bpf_lock_contention.c         |  174 +-
 .../perf/util/bpf_skel/lock_contention.bpf.c  |  431 ++---
 tools/perf/util/bpf_skel/lock_data.h          |  394 +++-
 tools/perf/util/bpf_skel/sample-filter.h      |   80 +
 tools/perf/util/bpf_skel/sample_filter.bpf.c  | 1241 ++++++++++++
 tools/perf/util/bpf_skel/vmlinux/vmlinux.h    |    7 +
 tools/perf/util/lock-contention.c             |   23 +
 tools/perf/util/lock-contention.h             |   15 +
 tools/perf/util/machine.c                     |   11 +
 tools/perf/util/parse-events.c                |  111 +-
 tools/perf/util/tp_pmu.c                      |   54 +
 tools/perf/util/tp_pmu.h                      |    1 +
 22 files changed, 4340 insertions(+), 360 deletions(-)
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
author reviewer
#107 lore raw

PATCH v7 1/11 perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF

In perf_bpf_filter__prepare(), the unpinned filter path attaches skel->progs.perf_sample_filter to each FD(evsel, x, y) using bpf_program__attach_perf_event_opts() and ignores the returned struct bpf_link *, leaking the allocated struct bpf_link_perf and its BPF_PERF_EVENT link fd.

Furthermore, bpf_program__attach_perf_event_opts() is designed for callers that transfer ownership of the perf_event fd to the returned
bpf_link: when bpf_link__destroy() is called, bpf_link_perf_detach() unconditionally disables and closes perf_link->perf_event_fd. Because evsel->core.fd owns FD(evsel, x, y) and closes them in evlist__close(), destroying the returned bpf_link would double-close the perf_event file descriptors.

Fix this by attaching the program directly with ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd), matching the pinned filter path right above it in perf_bpf_filter__prepare(). In the kernel, PERF_EVENT_IOC_SET_BPF takes a reference on the BPF program and _free_event() -> perf_event_free_bpf_prog() automatically detaches and releases it when the perf_event fd is closed. This also avoids enabling the event prematurely, allowing pe_opts (.dont_enable = true) and the LIBBPF_CURRENT_VERSION_GEQ(1, 7) guard to be dropped.

Before (built with EXTRA_CFLAGS="-fsanitize=address"):

  # perf record -e cycles --filter 'period > 1000' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data ]

=================================================================
==51328==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 1568 byte(s) in 28 object(s) allocated from:

      #0 0x7ffbe76ef24f in calloc (/lib64/libasan.so.8+0xef24f)
      #1 0x625df7 in bpf_program__attach_perf_event_opts (tools/perf/perf+0x625df7)
      #2 0xbeddc0 in perf_bpf_filter__prepare util/bpf-filter.c:507
      #3 0x8f3def in evlist__apply_filters util/evlist.c:1421
      #4 0x44bbcf in record__open tools/perf/builtin-record.c:1469
      #5 0x453f9e in __cmd_record tools/perf/builtin-record.c:2594
      #6 0x45dadb in cmd_record tools/perf/builtin-record.c:4427
      #7 0x5df56b in run_builtin tools/perf/perf.c:383
      #8 0x5dfa0e in handle_internal_command tools/perf/perf.c:436
      #9 0x5dfddc in run_argv tools/perf/perf.c:480
      #10 0x5e0333 in main tools/perf/perf.c:581

SUMMARY: AddressSanitizer: 1568 byte(s) leaked in 28 allocation(s).

After (built with EXTRA_CFLAGS="-fsanitize=address"):

  # perf record -e cycles --filter 'period > 1000' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data ]
Fixes 56ec9457a4a2 ("perf bpf filter: Implement event sample filtering")
---
 tools/perf/util/bpf-filter.c | 18 +++++-------------
 1 file changed, 5 insertions(+), 13 deletions(-)
tools/perf/util/bpf-filter.c +5 -13
index 72e83ac1d6a4..506414e5c407 100644
@@ -40,6 +40,7 @@
  * The 'dropped' map is to keep how many samples it dropped by the filter and
  * it will be reported as lost samples.
  */
+#include <errno.h>
 #include <stdlib.h>
 #include <fcntl.h>
 #include <sys/ioctl.h>
@@ -423,16 +424,8 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 {
 	int i, x, y, fd, ret;
 	struct sample_filter_bpf *skel = NULL;
-	struct bpf_program *prog;
-	struct bpf_link *link;
 	struct perf_bpf_filter_entry *entry;
 	bool needs_idx_hash = !target__has_cpu(target);
-#if LIBBPF_CURRENT_VERSION_GEQ(1, 7)
-	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts,
-			    .dont_enable = true);
-#else
-	DECLARE_LIBBPF_OPTS(bpf_perf_event_opts, pe_opts);
-#endif
 
 	entry = calloc(MAX_FILTERS, sizeof(*entry));
 	if (entry == NULL)
@@ -501,14 +494,13 @@ int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target)
 		goto err;
 	}
 
-	prog = skel->progs.perf_sample_filter;
+	fd = bpf_program__fd(skel->progs.perf_sample_filter);
 	for (x = 0; x < xyarray__max_x(evsel->core.fd); x++) {
 		for (y = 0; y < xyarray__max_y(evsel->core.fd); y++) {
-			link = bpf_program__attach_perf_event_opts(prog, FD(evsel, x, y),
-								   &pe_opts);
-			if (IS_ERR(link)) {
+			ret = ioctl(FD(evsel, x, y), PERF_EVENT_IOC_SET_BPF, fd);
+			if (ret < 0) {
+				ret = -errno;
 				pr_err("Failed to attach perf sample-filter program\n");
-				ret = PTR_ERR(link);
 				goto err;
 			}
 		}
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#108 lore raw

Re: [PATCH v7 01/11] perf bpf-filter: Fix bpf_link leak by using PERF_EVENT_IOC_SET_BPF

Sashiko has reviewed this patch and found no issues.
Quoted 14 lines

In perf_bpf_filter__prepare(), the unpinned filter path attaches skel->progs.perf_sample_filter to each FD(evsel, x, y) using bpf_program__attach_perf_event_opts() and ignores the returned struct bpf_link *, leaking the allocated struct bpf_link_perf and its BPF_PERF_EVENT link fd.

Furthermore, bpf_program__attach_perf_event_opts() is designed for callers that transfer ownership of the perf_event fd to the returned
bpf_link: when bpf_link__destroy() is called, bpf_link_perf_detach() unconditionally disables and closes perf_link->perf_event_fd. Because evsel->core.fd owns FD(evsel, x, y) and closes them in evlist__close(), destroying the returned bpf_link would double-close the perf_event file descriptors.

Quoted 7 lines

Fix this by attaching the program directly with
[ ... ]

Fixes 56ec9457a4a2 ("perf bpf filter: Implement event sample filtering")

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 2/11 perf bpf-filter: Support BPF sample filters on tracepoint events

In reply to Ian Rogers

Commit 466db4275edd ("perf parse-events: Add parse_uid_filter helper") updated set_filter() to route non-tracepoint filter terms (such as uid and gid) on PERF_TYPE_TRACEPOINT events to evsel->bpf_filters instead of the ftrace tracepoint predicate filter.

However, in the kernel's __perf_event_set_bpf_prog() (kernel/events/core.c), attaching a BPF program to a perf_event fd branches on perf_event_is_tracing(event):
- Non-tracing events (hardware PMU, software events, breakpoints) call perf_event_set_bpf_handler(), which requires BPF_PROG_TYPE_PERF_EVENT (SEC("perf_event")).
- Tracepoint events (event->pmu == &perf_tracepoint) reject BPF_PROG_TYPE_PERF_EVENT with -EINVAL and instead require BPF_PROG_TYPE_TRACEPOINT (SEC("tracepoint")), which is attached to event->tp_event->prog_array and executed in perf_trace_run_bpf_submit() before perf_tp_event(), dropping the sample if the BPF program returns 0. Furthermore, the bpf_cast_to_kern_ctx() kfunc is only permitted in BPF_PROG_TYPE_PERF_EVENT programs.

Add SEC("tracepoint") int perf_tp_sample_filter(void *ctx) in sample_filter.bpf.c to evaluate context-independent filter terms (uid, gid, tid, cpu, time, cgroup) using BPF helpers without calling bpf_cast_to_kern_ctx(). When preparing a BPF filter on a PERF_TYPE_TRACEPOINT evsel, autoload perf_tp_sample_filter instead of perf_sample_filter and attach it once to the shared trace_event_call. Because returning 0 from a BPF_PROG_TYPE_TRACEPOINT program filters at the shared trace_event_call->prog_array prior to perf_tp_event(), tracepoint BPF filters are never pinned for unprivileged use and require CAP_BPF or root privileges.

Route a tracepoint --filter to the BPF filter only when it uses one of these terms that isn't a field of the tracepoint, looking up fields with evsel__field() or, without libtraceevent, the tracefs format file, and ignoring words in quoted string literals. "cpu" stays an ftrace filter as ftrace provides a generic "cpu" field for all tracepoints. Reject filters mixing BPF terms with tracepoint fields named like a BPF term (such as "pid" on sched:sched_wakeup) as the BPF filter would evaluate such fields against the current task.

Because perf_bpf_filter__pin() and perf_bpf_filter__unpin() only load perf_sample_filter and disable autoload on perf_tp_sample_filter, libbpf's bpf_object__pin() and bpf_object__unpin() can no longer be used directly (as bpf_object__pin_programs() and bpf_object__unpin_programs() iterate over all programs in the object without checking autoload and fail with -EINVAL when a program has not been loaded). Introduce pin_filter_object() and unpin_filter_object() to pin/unpin the maps and only the loaded perf_sample_filter program.

Before:

  # perf record -e kmem:mm_page_alloc --filter 'uid == 0' -- true
  libbpf: prog 'perf_sample_filter': failed to attach to perf_event FD 3: Invalid argument
  Failed to attach perf sample-filter program
  failed to set filter "BPF" on event kmem:mm_page_alloc with 22 (Invalid argument)

After:

  # perf record -e kmem:mm_page_alloc --filter 'uid == 0' -- true
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 0.024 MB perf.data (42 samples) ]
Fixes 466db4275edd ("perf parse-events: Add parse_uid_filter helper")
---
 tools/perf/Documentation/perf-record.txt     |  13 +-
 tools/perf/util/bpf-filter.c                 | 144 ++++++++++++++++---
 tools/perf/util/bpf_skel/sample_filter.bpf.c |  95 ++++++++++++
 tools/perf/util/parse-events.c               | 109 +++++++++++++-
 tools/perf/util/tp_pmu.c                     |  54 +++++++
 tools/perf/util/tp_pmu.h                     |   1 +
 6 files changed, 392 insertions(+), 24 deletions(-)
tools/perf/Documentation/perf-record.txt +12 -1
index 2351f7b4f5fc..6646e16633ef 100644
@@ -173,7 +173,18 @@ OPTIONS
 
 	A BPF filter can access the sample data and make a decision based on the
 	data.  Users need to set an appropriate sample type to use the BPF
-	filter.  BPF filters need root privilege.
+	filter.  BPF filters need root privilege (or CAP_BPF, or a pinned BPF
+	filter for non-tracepoint events).  On tracepoint events, BPF filters
+	support context-independent terms ('uid', 'gid', 'tid', 'pid', 'cpu',
+	'time', 'cgroup') by attaching a 'BPF_PROG_TYPE_TRACEPOINT' program to
+	the tracepoint's shared 'trace_event_call->prog_array', which filters
+	the tracepoint before 'perf_tp_event()' runs across concurrent
+	perf_event listeners on that tracepoint.  A tracepoint filter is only
+	treated as a BPF filter when it uses one of these terms that is not a
+	field of the tracepoint (a filter only using 'cpu' remains an ftrace
+	filter on the generic 'cpu' field).  Filters mixing such BPF terms with
+	tracepoint fields of the same name (e.g. 'pid' on sched:sched_wakeup)
+	are rejected; use separate --filter options instead.
 
 	The sample data field can be specified in lower case letter.  Multiple
 	filters can be separated with comma.  For example,
tools/perf/util/bpf-filter.c +125 -19

236 lines not on this page · raw message

tools/perf/util/bpf_skel/sample_filter.bpf.c +95 -0

105 lines not on this page · raw message

tools/perf/util/parse-events.c +105 -4

136 lines not on this page · raw message

tools/perf/util/tp_pmu.c +54 -0

66 lines not on this page · raw message

tools/perf/util/tp_pmu.h +1 -0
index 30456bd6943d..a60ec0e8a176 100644
@@ -8,6 +8,7 @@ typedef int (*tp_sys_callback)(void *state, const char *sys_name);
 typedef int (*tp_event_callback)(void *state, const char *sys_name, const char *evt_name);
 
 int tp_pmu__id(const char *sys, const char *name);
+bool tp_pmu__has_field(const char *sys, const char *name, const char *field);
 int tp_pmu__for_each_tp_event(const char *sys, void *state, tp_event_callback cb);
 int tp_pmu__for_each_tp_sys(void *state, tp_sys_callback cb);
 
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#110 lore raw

Re: [PATCH v7 02/11] perf bpf-filter: Support BPF sample filters on tracepoint events

Sashiko has reviewed this patch and found no issues.
Quoted 19 lines

Commit 466db4275edd ("perf parse-events: Add parse_uid_filter helper") updated set_filter() to route non-tracepoint filter terms (such as uid and gid) on PERF_TYPE_TRACEPOINT events to evsel->bpf_filters instead of the ftrace tracepoint predicate filter.

However, in the kernel's __perf_event_set_bpf_prog() (kernel/events/core.c), attaching a BPF program to a perf_event fd branches on perf_event_is_tracing(event):
- Non-tracing events (hardware PMU, software events, breakpoints) call perf_event_set_bpf_handler(), which requires BPF_PROG_TYPE_PERF_EVENT (SEC("perf_event")).
- Tracepoint events (event->pmu == &perf_tracepoint) reject BPF_PROG_TYPE_PERF_EVENT with -EINVAL and instead require BPF_PROG_TYPE_TRACEPOINT (SEC("tracepoint")), which is attached to event->tp_event->prog_array and executed in
[ ... ]
[ perf record: Woken up 1 times to write data ]
[ perf record: Captured and wrote 0.024 MB perf.data (42 samples) ]

Quoted 2 lines
Fixes 466db4275edd ("perf parse-events: Add parse_uid_filter helper")

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 3/11 perf lock contention: Share common BPF and lock type definitions in lock_data.h

In reply to Ian Rogers

Move lock_type_table, LCB_F_* flags, and the common BPF lock helpers (get_lock_owner, get_current_mmap_lock, get_current_siglock, get_lock_addr, check_lock_type, do_collect_zone_lock, do_collect_lock_syms, do_slab_cache_iter) and shared CO-RE structs into tools/perf/util/bpf_skel/lock_data.h and tools/perf/util/lock-contention.[ch] so they can be reused by BPF sample filtering.

---
 tools/perf/builtin-lock.c                     |  27 --
 .../perf/util/bpf_skel/lock_contention.bpf.c  | 235 +-------------
 tools/perf/util/bpf_skel/lock_data.h          | 303 ++++++++++++++++++
 tools/perf/util/lock-contention.c             |  19 ++
 tools/perf/util/lock-contention.h             |  13 +
 5 files changed, 338 insertions(+), 259 deletions(-)
tools/perf/builtin-lock.c +0 -27
index d5c0d55cb82d..feaf1cfd08cf 100644
@@ -1477,33 +1477,6 @@ static void sort_result(void)
 	}
 }
 
-static const struct {
-	unsigned int flags;
-	/*
-	 * Name of the lock flags (access), with delimeter ':'.
-	 * For example, rwsem:R of rwsem:W.
-	 */
-	const char *flags_name;
-	/* Name of the lock (type), for example, rwlock or rwsem. */
-	const char *lock_name;
-} lock_type_table[] = {
-	{ 0,				"semaphore",	"semaphore" },
-	{ LCB_F_SPIN,			"spinlock",	"spinlock" },
-	{ LCB_F_SPIN | LCB_F_READ,	"rwlock:R",	"rwlock" },
-	{ LCB_F_SPIN | LCB_F_WRITE,	"rwlock:W",	"rwlock" },
-	{ LCB_F_READ,			"rwsem:R",	"rwsem" },
-	{ LCB_F_WRITE,			"rwsem:W",	"rwsem" },
-	{ LCB_F_RT,			"rt-mutex",	"rt-mutex" },
-	{ LCB_F_RT | LCB_F_READ,	"rwlock-rt:R",	"rwlock-rt" },
-	{ LCB_F_RT | LCB_F_WRITE,	"rwlock-rt:W",	"rwlock-rt" },
-	{ LCB_F_PERCPU | LCB_F_READ,	"pcpu-sem:R",	"percpu-rwsem" },
-	{ LCB_F_PERCPU | LCB_F_WRITE,	"pcpu-sem:W",	"percpu-rwsem" },
-	{ LCB_F_MUTEX,			"mutex",	"mutex" },
-	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex",	"mutex" },
-	/* alias for optimistic spinning only */
-	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex:spin",	"mutex-spin" },
-};
-
 static const char *get_type_flags_name(unsigned int flags)
 {
 	flags &= LCB_F_TYPE_MASK;
tools/perf/util/bpf_skel/lock_contention.bpf.c +3 -232

291 lines not on this page · raw message

tools/perf/util/bpf_skel/lock_data.h +303 -0

313 lines not on this page · raw message

tools/perf/util/lock-contention.c +19 -0
index 119a7206f3cd..f6e68d740860 100644
@@ -6,6 +6,7 @@
 #include "symbol.h"
 
 #include <limits.h>
+#include <stdlib.h>
 #include <string.h>
 
 #include <linux/hash.h>
@@ -22,6 +23,24 @@ struct callstack_filter {
 static LIST_HEAD(callstack_filters);
 struct hlist_head *lockhash_table;
 
+const struct perf_lock_type lock_type_table[] = {
+	{ 0,				"semaphore",	"semaphore" },
+	{ LCB_F_SPIN,			"spinlock",	"spinlock" },
+	{ LCB_F_SPIN | LCB_F_READ,	"rwlock:R",	"rwlock" },
+	{ LCB_F_SPIN | LCB_F_WRITE,	"rwlock:W",	"rwlock" },
+	{ LCB_F_READ,			"rwsem:R",	"rwsem" },
+	{ LCB_F_WRITE,			"rwsem:W",	"rwsem" },
+	{ LCB_F_RT,			"rt-mutex",	"rt-mutex" },
+	{ LCB_F_RT | LCB_F_READ,	"rwlock-rt:R",	"rwlock-rt" },
+	{ LCB_F_RT | LCB_F_WRITE,	"rwlock-rt:W",	"rwlock-rt" },
+	{ LCB_F_PERCPU | LCB_F_READ,	"pcpu-sem:R",	"percpu-rwsem" },
+	{ LCB_F_PERCPU | LCB_F_WRITE,	"pcpu-sem:W",	"percpu-rwsem" },
+	{ LCB_F_MUTEX,			"mutex",	"mutex" },
+	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex",	"mutex" },
+	/* alias for optimistic spinning only */
+	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex:spin",	"mutex-spin" },
+};
+
 int parse_call_stack(const struct option *opt __maybe_unused, const char *str,
 		     int unset __maybe_unused)
 {
tools/perf/util/lock-contention.h +13 -0
index 59c94190b092..68e9bd77e8a9 100644
@@ -129,6 +129,19 @@ struct thread_stat {
 #define LCB_F_PERCPU	(1U << 4)
 #define LCB_F_MUTEX	(1U << 5)
 
+struct perf_lock_type {
+	unsigned int flags;
+	/*
+	 * Name of the lock flags (access), with delimiter ':'.
+	 * For example, rwsem:R or rwsem:W.
+	 */
+	const char *flags_name;
+	/* Name of the lock (type), for example, rwlock or rwsem. */
+	const char *lock_name;
+};
+
+extern const struct perf_lock_type lock_type_table[14];
+
 struct evlist;
 struct machine;
 struct target;
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#112 lore raw

Re: [PATCH v7 03/11] perf lock contention: Share common BPF and lock type definitions in lock_data.h

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

Move lock_type_table, LCB_F_* flags, and the common BPF lock helpers (get_lock_owner, get_current_mmap_lock, get_current_siglock, get_lock_addr, check_lock_type, do_collect_zone_lock, do_collect_lock_syms, do_slab_cache_iter) and shared CO-RE structs into tools/perf/util/bpf_skel/lock_data.h and tools/perf/util/lock-contention.[ch] so they can be reused by BPF sample filtering.

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 4/11 perf lock contention: Extend get_lock_owner() for rt_mutex and mutex handoff

In reply to Ian Rogers

Extend get_lock_owner() in tools/perf/util/bpf_skel/lock_data.h to:
- Support rt_mutex locks (LCB_F_RT) and CONFIG_PREEMPT_RT mutexes via struct rt_mutex_base and struct rt_mutex___old, masking out the low waiter bit (0x1UL).
- Return NULL when a mutex has MUTEX_FLAG_HANDOFF (0x4UL) set on owner.counter and is in the middle of being handed off rather than actively held.

Also add rw_semaphore.count and struct rt_mutex_base to the fallback tools/perf/util/bpf_skel/vmlinux/vmlinux.h.

---
 tools/perf/util/bpf_skel/lock_data.h       | 62 ++++++++++++++++++----
 tools/perf/util/bpf_skel/vmlinux/vmlinux.h |  5 ++
 2 files changed, 58 insertions(+), 9 deletions(-)
tools/perf/util/bpf_skel/lock_data.h +53 -9
index 91d464ac18bd..43d8f5030bc1 100644
@@ -104,11 +104,24 @@ extern struct rq runqueues __ksym __weak;
 # define __has_builtin(x) 0
 #endif
 
+struct mutex___non_rt {
+	atomic_long_t owner;
+} __attribute__((preserve_access_index));
+
+struct rt_mutex_base___new {
+	struct task_struct *owner;
+} __attribute__((preserve_access_index));
+
+struct rt_mutex___old {
+	struct task_struct *owner;
+} __attribute__((preserve_access_index));
+
 struct rw_semaphore___old {
 	struct task_struct *owner;
 } __attribute__((preserve_access_index));
 
 struct rw_semaphore___new {
+	atomic_long_t count;
 	atomic_long_t owner;
 } __attribute__((preserve_access_index));
 
@@ -146,9 +159,25 @@ static __always_inline struct task_struct *get_lock_owner(__u64 lock, __u32 flag
 	__u64 owner = 0;
 
 	if (flags & LCB_F_MUTEX) {
-		struct mutex *mutex = (void *)lock;
-
-		owner = BPF_CORE_READ(mutex, owner.counter);
+		struct mutex___non_rt *mutex = (void *)lock;
+
+		if (bpf_core_field_exists(mutex->owner.counter)) {
+			owner = BPF_CORE_READ(mutex, owner.counter);
+			if (owner & 0x4UL)
+				return NULL;
+		} else if (bpf_core_type_exists(struct rt_mutex_base___new)) {
+			struct rt_mutex_base___new *rtm = (void *)lock;
+
+			owner = (__u64)BPF_CORE_READ(rtm, owner);
+			return (void *)(owner & ~1UL);
+		} else {
+			struct rt_mutex___old *rtm = (void *)lock;
+
+			if (bpf_core_field_exists(rtm->owner)) {
+				owner = (__u64)BPF_CORE_READ(rtm, owner);
+				return (void *)(owner & ~1UL);
+			}
+		}
 	} else if (flags == LCB_F_READ || flags == LCB_F_WRITE) {
 	/*
 	 * Support for the BPF_TYPE_MATCHES argument to the
@@ -158,20 +187,35 @@ static __always_inline struct task_struct *get_lock_owner(__u64 lock, __u32 flag
 	 */
 #if __has_builtin(__builtin_preserve_type_info) && __clang_major__ >= 15
 		if (bpf_core_type_matches(struct rw_semaphore___old)) {
-			struct rw_semaphore___old *rwsem = (void *)lock;
+			struct rw_semaphore___old *old = (void *)lock;
 
-			owner = (unsigned long)BPF_CORE_READ(rwsem, owner);
+			owner = (unsigned long)BPF_CORE_READ(old, owner);
 		} else if (bpf_core_type_matches(struct rw_semaphore___new)) {
-			struct rw_semaphore___new *rwsem = (void *)lock;
+			struct rw_semaphore___new *new = (void *)lock;
 
-			owner = BPF_CORE_READ(rwsem, owner.counter);
+			owner = BPF_CORE_READ(new, owner.counter);
 		}
 #else
 		/* assume new struct */
-		struct rw_semaphore *rwsem = (void *)lock;
+		struct rw_semaphore___new *new = (void *)lock;
 
-		owner = BPF_CORE_READ(rwsem, owner.counter);
+		if (bpf_core_field_exists(new->owner.counter))
+			owner = BPF_CORE_READ(new, owner.counter);
 #endif
+	} else if (flags == LCB_F_RT) {
+		if (bpf_core_type_exists(struct rt_mutex_base___new)) {
+			struct rt_mutex_base___new *rtm = (void *)lock;
+
+			owner = (__u64)BPF_CORE_READ(rtm, owner);
+			return (void *)(owner & ~1UL);
+		} else {
+			struct rt_mutex___old *rtm = (void *)lock;
+
+			if (bpf_core_field_exists(rtm->owner)) {
+				owner = (__u64)BPF_CORE_READ(rtm, owner);
+				return (void *)(owner & ~1UL);
+			}
+		}
 	}
 
 	if (!owner)
tools/perf/util/bpf_skel/vmlinux/vmlinux.h +5 -0
index 94e42b022ab1..b75ddc6846bb 100644
@@ -76,6 +76,7 @@ struct signal_struct {
 } __attribute__((preserve_access_index));
 
 struct rw_semaphore {
+	atomic_long_t count;
 	atomic_long_t owner;
 } __attribute__((preserve_access_index));
 
@@ -83,6 +84,10 @@ struct mutex {
 	atomic_long_t owner;
 } __attribute__((preserve_access_index));
 
+struct rt_mutex_base {
+	struct task_struct *owner;
+} __attribute__((preserve_access_index));
+
 struct kernfs_node {
 	u64 id;
 } __attribute__((preserve_access_index));
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#114 lore raw

Re: [PATCH v7 04/11] perf lock contention: Extend get_lock_owner() for rt_mutex and mutex handoff

Sashiko has reviewed this patch and found no issues.
Quoted 8 lines

Extend get_lock_owner() in tools/perf/util/bpf_skel/lock_data.h to:
- Support rt_mutex locks (LCB_F_RT) and CONFIG_PREEMPT_RT mutexes via struct rt_mutex_base and struct rt_mutex___old, masking out the low waiter bit (0x1UL).
- Return NULL when a mutex has MUTEX_FLAG_HANDOFF (0x4UL) set on owner.counter and is in the middle of being handed off rather than actively held.

Quoted 4 lines

Also add rw_semaphore.count and struct rt_mutex_base to the fallback tools/perf/util/bpf_skel/vmlinux/vmlinux.h.

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 5/11 perf bpf-filter: Add lock_held() sample filter for global mutexes

In reply to Ian Rogers

Add BPF sample filter predicates lock_held(<lock>), lock_held_read(<lock>) / lock_held_shared(<lock>), and lock_held_write(<lock>) / lock_held_exclusive(<lock>) (as well as ':R' and ':W' suffixes on <lock>) to allow recording perf event samples only when a specified kernel lock is held (or not held with '!').

In this initial step, support global/static kernel mutex symbols (e.g. lock_held(cgroup_mutex)) resolved via /proc/kallsyms. On sample overflow, perf_sample_filter and perf_tp_sample_filter inspect the mutex's owner field directly in kernel memory via get_lock_owner() without attaching any BPF fentry/fexit hooks.

Lock symbols are classified by classify_lock_sym(). As kallsyms gives a symbol address but not its type, this uses BTF where possible: a __percpu_rwsem_rc_<name> per-CPU variable (always present in BTF) identifies percpu-rwsems, and the BTF_KIND_VAR type of the symbol (e.g. struct mutex) is used when vmlinux BTF has global variables (pahole --btf_features=global_var, which scripts/Makefile.btf doesn't enable by default). Otherwise the symbol name suffix (e.g. '_mutex') is used. A misclassification is benign: the owner field is only read with bpf_probe_read_kernel() at a kernel data/bss symbol address (functions are rejected), so at worst the filter won't match.

Subsequent commits extend lock_held() to other kernel lock types, per-process and semi-global locks, slab cache locks, and RCU/SRCU.

---
 tools/perf/Documentation/perf-record.txt     |  16 +-
 tools/perf/util/bpf-filter.c                 | 516 ++++++++++++++++++-
 tools/perf/util/bpf-filter.h                 |  13 +
 tools/perf/util/bpf-filter.l                 |  31 +-
 tools/perf/util/bpf-filter.y                 |  47 +-
 tools/perf/util/bpf_skel/sample-filter.h     |  36 ++
 tools/perf/util/bpf_skel/sample_filter.bpf.c |  54 ++
 tools/perf/util/parse-events.c               |   2 +
 8 files changed, 695 insertions(+), 20 deletions(-)
tools/perf/Documentation/perf-record.txt +15 -1
index 6646e16633ef..34dd9b1a5365 100644
@@ -215,7 +215,21 @@ OPTIONS
 	  ip, id, tid, pid, cpu, time, addr, period, txn, weight, phys_addr,
 	  code_pgsz, data_pgsz, weight1, weight2, weight3, ins_lat, retire_lat,
 	  p_stage_cyc, mem_op, mem_lvl, mem_snoop, mem_remote, mem_lock,
-	  mem_dtlb, mem_blk, mem_hops, uid, gid
+	  mem_dtlb, mem_blk, mem_hops, uid, gid, cgroup, lock_held(<lock>),
+	  lock_held_read(<lock>), lock_held_shared(<lock>),
+	  lock_held_write(<lock>), lock_held_exclusive(<lock>)
+
+	The 'lock_held(<lock>)' predicate (or '!lock_held(<lock>)') filters
+	samples based on whether the specified kernel lock is currently held
+	by the kernel thread.  To differentiate between shared/read holding
+	and exclusive/write holding, use 'lock_held_read(<lock>)' (alias
+	'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)' (alias
+	'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to <lock>.
+	<lock> can be a kernel mutex symbol name (e.g.
+	'lock_held(cgroup_mutex)').  When filtering on a mutex symbol
+	('*_mutex'), 'perf_sample_filter' inspects the lock's 'owner' field
+	directly in kernel memory on each sample without attaching any BPF
+	fentry/fexit hooks.
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +501 -15

642 lines not on this page · raw message

tools/perf/util/bpf-filter.h +13 -0
index 818c554b91b2..fda95ff226b3 100644
@@ -14,6 +14,13 @@ struct perf_bpf_filter_expr {
 	int part;
 	enum perf_bpf_filter_term term;
 	unsigned long val;
+	/*
+	 * Raw lock descriptor string for PBF_TERM_LOCK_HELD expressions
+	 * (e.g. "&cgroup_mutex", "mmap_lock", "&dentry", "rwsem:R").
+	 * Resolved into `entry.part` and `entry.target` during
+	 * perf_bpf_filter__prepare().
+	 */
+	char *lock_name;
 };
 
 struct evsel;
@@ -27,6 +34,12 @@ struct perf_bpf_filter_expr *perf_bpf_filter_expr__new(enum perf_bpf_filter_term
 						       int part,
 						       enum perf_bpf_filter_op op,
 						       unsigned long val);
+struct perf_bpf_filter_expr *perf_bpf_filter_expr__new_lock(const char *lock_name,
+							    int mode,
+							    enum perf_bpf_filter_op op,
+							    unsigned long val);
+void perf_bpf_filter_expr__delete(struct perf_bpf_filter_expr *expr);
+int __perf_bpf_filter__parse(struct list_head *expr_head, const char *str);
 int perf_bpf_filter__parse(struct list_head *expr_head, const char *str);
 int perf_bpf_filter__prepare(struct evsel *evsel, struct target *target);
 int perf_bpf_filter__destroy(struct evsel *evsel);
tools/perf/util/bpf-filter.l +29 -2
index 1be9df6550fc..b4022110f1e5 100644
@@ -1,9 +1,12 @@
 %option prefix="perf_bpf_filter_"
 %option noyywrap
 
+%x LOCK_ARG
+
 %{
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
 #include <linux/perf_event.h>
 
 #include "bpf-filter.h"
@@ -76,7 +79,7 @@ static int path_or_error(void)
 num_dec		[0-9]+
 num_hex		0[Xx][0-9a-fA-F]+
 space		[ \t]+
-path		[^ \t\n,]+
+path		[^ \t\n,()!=>&|<]+
 ident		[_a-zA-Z][_a-zA-Z0-9]+
 
 %%
@@ -116,7 +119,31 @@ mem_hops	{ return sample_part(PBF_TERM_DATA_SRC, 8); }
 uid		{ return sample(PBF_TERM_UID); }
 gid		{ return sample(PBF_TERM_GID); }
 cgroup		{ return sample_path(PBF_TERM_CGROUP); }
-
+lock_held[ \t]*"("	{
+				BEGIN(LOCK_ARG);
+				perf_bpf_filter_lval.num = PBF_LOCK_MODE_ANY;
+				return BFT_LOCK_HELD;
+			}
+(lock_held_read|lock_held_shared)[ \t]*"("	{
+				BEGIN(LOCK_ARG);
+				perf_bpf_filter_lval.num = PBF_LOCK_MODE_READ;
+				return BFT_LOCK_HELD;
+			}
+(lock_held_write|lock_held_exclusive)[ \t]*"("	{
+				BEGIN(LOCK_ARG);
+				perf_bpf_filter_lval.num = PBF_LOCK_MODE_WRITE;
+				return BFT_LOCK_HELD;
+			}
+
+<LOCK_ARG>{space}	{ }
+<LOCK_ARG>[^ \t\n()]+	{
+				perf_bpf_filter_lval.lock_name = strdup(perf_bpf_filter_text);
+				return BFT_LOCK_NAME;
+			}
+<LOCK_ARG>")"		{ BEGIN(INITIAL); return ')'; }
+<LOCK_ARG>.|\n		{ BEGIN(INITIAL); return BFT_ERROR; }
+
+"!"		{ return '!'; }
 "=="		{ return operator(PBF_OP_EQ); }
 "!="		{ return operator(PBF_OP_NEQ); }
 ">"		{ return operator(PBF_OP_GT); }
tools/perf/util/bpf-filter.y +45 -2

77 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +36 -0
index 683fec85e71e..ca1cf586ed6e 100644
@@ -53,8 +53,44 @@ enum perf_bpf_filter_term {
 	/* Terms computed from BPF helpers. */
 	PBF_TERM_UID,
 	PBF_TERM_GID,
+	/*
+	 * Kernel lock held predicate (`lock_held(...)`). Evaluates whether the
+	 * specified kernel lock is currently held by the running task/CPU.
+	 * The lock specification kind is stored in `entry.part`
+	 * (`enum perf_bpf_lock_target_kind`), `entry.op` is normalized to
+	 * `PBF_OP_EQ` (match when held) or `PBF_OP_NEQ` (match when not held),
+	 * and the resolved target address is stored in `entry.value`.
+	 */
+	PBF_TERM_LOCK_HELD,
 };
 
+/*
+ * Lock target categories for PBF_TERM_LOCK_HELD filters.
+ * Stored in `perf_bpf_filter_entry.part`.
+ */
+enum perf_bpf_lock_target_kind {
+	PBF_LOCK_NONE = 0,
+	/*
+	 * Specific global or static lock address resolved from kallsyms.
+	 * `entry.value` holds the kernel address.
+	 */
+	PBF_LOCK_ADDR,
+};
+
+/*
+ * `perf_bpf_filter_entry.part` layout for PBF_TERM_LOCK_HELD:
+ *   Bits 0..3: `enum perf_bpf_lock_target_kind`
+ *   Bit  4:    PBF_LOCK_MODE_READ      (match read/shared lock holding)
+ *   Bit  5:    PBF_LOCK_MODE_WRITE     (match write/exclusive lock holding)
+ *   Bit  6:    PBF_LOCK_DIRECT_MUTEX   (inspect struct mutex owner)
+ */
+#define PBF_LOCK_KIND_MASK	0x0fU
+#define PBF_LOCK_MODE_READ	(1U << 4)
+#define PBF_LOCK_MODE_WRITE	(1U << 5)
+#define PBF_LOCK_MODE_ANY	(PBF_LOCK_MODE_READ | PBF_LOCK_MODE_WRITE)
+#define PBF_LOCK_MODE_MASK	PBF_LOCK_MODE_ANY
+#define PBF_LOCK_DIRECT_MUTEX	(1U << 6)
+
 /* BPF map entry for filtering */
 struct perf_bpf_filter_entry {
 	enum perf_bpf_filter_op op;
tools/perf/util/bpf_skel/sample_filter.bpf.c +54 -0

80 lines not on this page · raw message

tools/perf/util/parse-events.c +2 -0
index 7110c9ca928e..81316fabf496 100644
@@ -2672,6 +2672,8 @@ static int is_possible_tp_filter(struct evsel *evsel, const char *str)
 	 */
 	static const char *const bpf_tp_terms[] = {
 		"uid", "gid", "tid", "pid", "time", "cgroup",
+		"lock_held", "lock_held_read", "lock_held_shared",
+		"lock_held_write", "lock_held_exclusive",
 	};
 	const char *bpf_term = NULL, *tp_field = NULL;
 
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#116 lore raw

Re: [PATCH v7 05/11] perf bpf-filter: Add lock_held() sample filter for global mutexes

Sashiko has reviewed this patch and found no issues.
Quoted 23 lines

Add BPF sample filter predicates lock_held(<lock>), lock_held_read(<lock>) / lock_held_shared(<lock>), and lock_held_write(<lock>) / lock_held_exclusive(<lock>) (as well as ':R' and ':W' suffixes on <lock>) to allow recording perf event samples only when a specified kernel lock is held (or not held with '!').

In this initial step, support global/static kernel mutex symbols (e.g. lock_held(cgroup_mutex)) resolved via /proc/kallsyms. On sample overflow, perf_sample_filter and perf_tp_sample_filter inspect the mutex's owner field directly in kernel memory via get_lock_owner() without attaching any BPF fentry/fexit hooks.

Lock symbols are classified by classify_lock_sym(). As kallsyms gives a symbol address but not its type, this uses BTF where possible: a __percpu_rwsem_rc_<name> per-CPU variable (always present in BTF) identifies percpu-rwsems, and the BTF_KIND_VAR type of the symbol (e.g. struct mutex) is used when vmlinux BTF has global variables (pahole --btf_features=global_var, which scripts/Makefile.btf doesn't enable by default). Otherwise the symbol name suffix (e.g. '_mutex') is used. A misclassification is benign: the owner field is only read with bpf_probe_read_kernel() at a kernel data/bss symbol address (functions are rejected), so at worst the filter won't match.

Quoted 4 lines

Subsequent commits extend lock_held() to other kernel lock types, per-process and semi-global locks, slab cache locks, and RCU/SRCU.

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 6/11 perf bpf-filter: Extend lock_held() to other kernel lock types

In reply to Ian Rogers

Extend the lock_held() BPF sample filter beyond global mutexes to support:
- Other global/static kernel lock symbols (rwsem, spinlock, rwlock, rt-mutex, percpu-rwsem, semaphore) and hexadecimal kernel lock addresses.
- Lock types and flags: mutex, spinlock, rwsem, rwsem:R, rwsem:W, rwlock, rwlock:R, rwlock:W, rt-mutex, percpu-rwsem, pcpu-sem:W, semaphore.

For rt-mutexes and write-locked rwsems, perf_sample_filter inspects the lock's owner field directly in kernel memory. For locks and modes without an authoritative per-task owner pointer (spinlocks, rwlocks, semaphores, reader-locked rwsems, percpu-rwsems, and lock type filters), attach BPF fentry/fexit hooks on kernel lock acquire and release functions to track held locks in the held_locks BPF LRU hash map.

Use classify_lock_sym() both when selecting which hooks to load and when resolving the filter, so the two agree. A '*_sem' suffix may be either a semaphore (console_sem) or an rw_semaphore (namespace_sem), so hook both and allow read mode.

Note that counting semaphores (down*() / up()) do not enforce same-task ownership in the kernel: when a semaphore is used as a cross-task completion/signaling mechanism, fexit/down and fentry/up will not pair on the same task ID. Semaphore hooks are therefore only enabled when 'semaphore' or a '*_sem' symbol (such as console_sem) is explicitly specified, and held_locks uses BPF_MAP_TYPE_LRU_HASH so any unpaired cross-task entries are automatically evicted.

---
 tools/perf/Documentation/perf-record.txt     |  53 +-
 tools/perf/util/bpf-filter.c                 | 601 ++++++++++++-
 tools/perf/util/bpf_skel/sample-filter.h     |  17 +-
 tools/perf/util/bpf_skel/sample_filter.bpf.c | 851 ++++++++++++++++++-
 4 files changed, 1470 insertions(+), 52 deletions(-)
tools/perf/Documentation/perf-record.txt +44 -9
index 34dd9b1a5365..d603820b51c9 100644
@@ -221,15 +221,50 @@ OPTIONS
 
 	The 'lock_held(<lock>)' predicate (or '!lock_held(<lock>)') filters
 	samples based on whether the specified kernel lock is currently held
-	by the kernel thread.  To differentiate between shared/read holding
-	and exclusive/write holding, use 'lock_held_read(<lock>)' (alias
-	'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)' (alias
-	'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to <lock>.
-	<lock> can be a kernel mutex symbol name (e.g.
-	'lock_held(cgroup_mutex)').  When filtering on a mutex symbol
-	('*_mutex'), 'perf_sample_filter' inspects the lock's 'owner' field
-	directly in kernel memory on each sample without attaching any BPF
-	fentry/fexit hooks.
+	by the kernel thread or CPU.  To differentiate between shared/read
+	holding and exclusive/write holding, use 'lock_held_read(<lock>)'
+	(alias 'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)'
+	(alias 'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to
+	<lock> (e.g. 'lock_held(rwsem:R)' or 'lock_held(rwsem:W)').
+	<lock> can be a kernel lock symbol name (e.g.
+	'lock_held(cgroup_mutex)'), a hexadecimal lock address, or a lock type
+	('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
+	'rwlock:R', 'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W',
+	'semaphore').  Both read/shared and write/exclusive tracking are
+	supported for 'rwsem' and 'rwlock'; 'mutex', 'spinlock', 'rt-mutex',
+	'semaphore', and 'percpu-rwsem' ('percpu_down_write()') support
+	write/exclusive tracking only.  Note that 'semaphore' tracking
+	('down*()' / 'up()') assumes binary mutex-like usage where the
+	acquiring task also releases the semaphore (such as 'console_sem'),
+	rather than cross-task completion signaling.
+
+	For example, 'lock_held()' can be combined with memory allocation or
+	reclaim events to detect allocations or direct memory reclaim occurring
+	while a kernel lock is held (which can stall lock waiters for extended
+	periods):
+
+	  # perf record -a -g -e vmscan:mm_vmscan_direct_reclaim_begin \
+	      --filter 'lock_held(mutex) || lock_held(rwsem)'
+	  # perf record -a -g -e kmem:mm_page_alloc \
+	      --filter 'gfp_flags & 0x400' \
+	      --filter 'lock_held(mutex) || lock_held(rwsem)'
+	  # perf record -a -g -e major-faults \
+	      --filter 'lock_held(mutex) || lock_held(rwsem)'
+
+	When filtering on a specific mutex symbol ('*_mutex') or rt-mutex
+	symbol ('*_rt_mutex'), 'perf_sample_filter' inspects the lock's
+	'owner' field directly in kernel memory on each sample without attaching
+	any BPF fentry/fexit hooks.  For locks that do not maintain an
+	authoritative per-task owner pointer (such as spinlocks, rwlocks,
+	semaphores, reader-locked rwsems, and lock type filters), it attaches
+	BPF fentry/fexit programs to kernel lock acquire and release functions
+	to track held locks in a BPF map.  These BPF hooks run on every kernel
+	lock acquisition and release for the attached lock family, even when no
+	perf sample is being taken.  To minimize this overhead, only the hooks
+	for the relevant lock family and mode are attached when known, whereas
+	raw hex addresses or symbols without a recognizable lock-type suffix
+	attach hooks across all lock families (including high-frequency
+	spinlocks).
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +564 -37

759 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +14 -3
index ca1cf586ed6e..c240eee782f8 100644
@@ -59,7 +59,8 @@ enum perf_bpf_filter_term {
 	 * The lock specification kind is stored in `entry.part`
 	 * (`enum perf_bpf_lock_target_kind`), `entry.op` is normalized to
 	 * `PBF_OP_EQ` (match when held) or `PBF_OP_NEQ` (match when not held),
-	 * and the resolved target address is stored in `entry.value`.
+	 * and the resolved target address or type flag encoding is stored in
+	 * `entry.value`.
 	 */
 	PBF_TERM_LOCK_HELD,
 };
@@ -71,10 +72,16 @@ enum perf_bpf_filter_term {
 enum perf_bpf_lock_target_kind {
 	PBF_LOCK_NONE = 0,
 	/*
-	 * Specific global or static lock address resolved from kallsyms.
-	 * `entry.value` holds the kernel address.
+	 * Specific global or static lock address (resolved from kallsyms or
+	 * given as a hex address). `entry.value` holds the kernel address.
 	 */
 	PBF_LOCK_ADDR,
+	/*
+	 * Lock type filter (`mutex`, `spinlock`, `rwsem`, `rwsem:R`, etc.).
+	 * `entry.value` packs up to two `LCB_F_*` flag combinations in the
+	 * low two bytes: `flag1 | (flag2 << 8)` (with 0xff indicating unused).
+	 */
+	PBF_LOCK_TYPE,
 };
 
 /*
@@ -83,6 +90,8 @@ enum perf_bpf_lock_target_kind {
  *   Bit  4:    PBF_LOCK_MODE_READ      (match read/shared lock holding)
  *   Bit  5:    PBF_LOCK_MODE_WRITE     (match write/exclusive lock holding)
  *   Bit  6:    PBF_LOCK_DIRECT_MUTEX   (inspect struct mutex owner)
+ *   Bit  7:    PBF_LOCK_DIRECT_RWSEM   (inspect struct rw_semaphore writer owner)
+ *   Bit  8:    PBF_LOCK_DIRECT_RTMUTEX (inspect struct rt_mutex_base / rt_mutex owner)
  */
 #define PBF_LOCK_KIND_MASK	0x0fU
 #define PBF_LOCK_MODE_READ	(1U << 4)
@@ -90,6 +99,8 @@ enum perf_bpf_lock_target_kind {
 #define PBF_LOCK_MODE_ANY	(PBF_LOCK_MODE_READ | PBF_LOCK_MODE_WRITE)
 #define PBF_LOCK_MODE_MASK	PBF_LOCK_MODE_ANY
 #define PBF_LOCK_DIRECT_MUTEX	(1U << 6)
+#define PBF_LOCK_DIRECT_RWSEM	(1U << 7)
+#define PBF_LOCK_DIRECT_RTMUTEX	(1U << 8)
 
 /* BPF map entry for filtering */
 struct perf_bpf_filter_entry {
tools/perf/util/bpf_skel/sample_filter.bpf.c +848 -3

895 lines not on this page · raw message

Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#118 lore raw

Re: [PATCH v7 06/11] perf bpf-filter: Extend lock_held() to other kernel lock types

Sashiko has reviewed this patch and found no issues.
Quoted 29 lines

Extend the lock_held() BPF sample filter beyond global mutexes to support:
- Other global/static kernel lock symbols (rwsem, spinlock, rwlock, rt-mutex, percpu-rwsem, semaphore) and hexadecimal kernel lock addresses.
- Lock types and flags: mutex, spinlock, rwsem, rwsem:R, rwsem:W, rwlock, rwlock:R, rwlock:W, rt-mutex, percpu-rwsem, pcpu-sem:W, semaphore.

For rt-mutexes and write-locked rwsems, perf_sample_filter inspects the lock's owner field directly in kernel memory. For locks and modes without an authoritative per-task owner pointer (spinlocks, rwlocks, semaphores, reader-locked rwsems, percpu-rwsems, and lock type filters), attach BPF fentry/fexit hooks on kernel lock acquire and release functions to track held locks in the held_locks BPF LRU hash map.

Use classify_lock_sym() both when selecting which hooks to load and when resolving the filter, so the two agree. A '*_sem' suffix may be either a semaphore (console_sem) or an rw_semaphore (namespace_sem), so hook both and allow read mode.

Note that counting semaphores (down*() / up()) do not enforce same-task ownership in the kernel: when a semaphore is used as a cross-task completion/signaling mechanism, fexit/down and fentry/up will not pair on the same task ID. Semaphore hooks are therefore only enabled when 'semaphore' or a '*_sem' symbol (such as console_sem) is explicitly specified, and held_locks uses BPF_MAP_TYPE_LRU_HASH so any unpaired cross-task entries are automatically evicted.

Quoted 1 line

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 7/11 perf bpf-filter: Support per-process and semi-global locks in lock_held()

In reply to Ian Rogers

Extend the lock_held() BPF sample filter to support well-known per-process and semi-global kernel locks:
- mmap_lock (or mmap_sem): current->mm->mmap_lock, supporting both read/shared (lock_held_read(mmap_lock) / lock_held(mmap_lock:R)) and write/exclusive (lock_held_write(mmap_lock) / lock_held(mmap_lock:W)) modes. Write ownership is inspected directly via is_rwsem_writer_owner() without attaching fentry/fexit hooks.
- siglock: current->sighand->siglock.
- rq_lock: per-CPU scheduler runqueue locks.
- zone_lock: memory management NUMA zone locks.

For rq_lock and zone_lock, reuse do_collect_lock_syms() from lock_data.h via a raw_tp/bpf_test_finish program run at filter setup time to populate the lock_syms map with each CPU's rq_lock and each NUMA node's zone_lock addresses.

Only zone_lock needs NUMA zone data from kallsyms and sysfs, so fail filter setup if it can't be found rather than attaching a filter that can never match.

Example usage:

  # perf record -a -g -e cycles --filter 'lock_held(mmap_lock)' \
      -- perf bench mem mmap -t 2 -l 100
  # perf record -a -g -e cycles --filter 'lock_held_read(mmap_lock)' ...
  # perf record -a -g -e cycles --filter 'lock_held_write(mmap_lock)' ...
  # perf record -a -g -e cycles --filter 'lock_held(mmap_lock:W)' ...
---
 tools/perf/Documentation/perf-record.txt     |  24 ++-
 tools/perf/util/bpf-filter.c                 | 194 +++++++++++++++++--
 tools/perf/util/bpf_skel/sample-filter.h     |  18 +-
 tools/perf/util/bpf_skel/sample_filter.bpf.c |  67 +++++++
 4 files changed, 277 insertions(+), 26 deletions(-)
tools/perf/Documentation/perf-record.txt +14 -10
index d603820b51c9..1c65f90dfb6b 100644
@@ -225,13 +225,15 @@ OPTIONS
 	holding and exclusive/write holding, use 'lock_held_read(<lock>)'
 	(alias 'lock_held_shared(<lock>)') or 'lock_held_write(<lock>)'
 	(alias 'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to
-	<lock> (e.g. 'lock_held(rwsem:R)' or 'lock_held(rwsem:W)').
+	<lock> (e.g. 'lock_held(mmap_lock:R)' or 'lock_held(mmap_lock:W)').
 	<lock> can be a kernel lock symbol name (e.g.
-	'lock_held(cgroup_mutex)'), a hexadecimal lock address, or a lock type
-	('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
+	'lock_held(cgroup_mutex)'), a hexadecimal lock address, a well-known
+	lock name ('mmap_lock', 'siglock', 'rq_lock', 'zone_lock'), or a lock
+	type ('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
 	'rwlock:R', 'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W',
 	'semaphore').  Both read/shared and write/exclusive tracking are
-	supported for 'rwsem' and 'rwlock'; 'mutex', 'spinlock', 'rt-mutex',
+	supported for 'rwsem' (including 'mmap_lock') and 'rwlock'; 'mutex',
+	'spinlock' (including 'siglock', 'rq_lock', 'zone_lock'), 'rt-mutex',
 	'semaphore', and 'percpu-rwsem' ('percpu_down_write()') support
 	write/exclusive tracking only.  Note that 'semaphore' tracking
 	('down*()' / 'up()') assumes binary mutex-like usage where the
@@ -251,8 +253,9 @@ OPTIONS
 	  # perf record -a -g -e major-faults \
 	      --filter 'lock_held(mutex) || lock_held(rwsem)'
 
-	When filtering on a specific mutex symbol ('*_mutex') or rt-mutex
-	symbol ('*_rt_mutex'), 'perf_sample_filter' inspects the lock's
+	When filtering on a specific mutex symbol ('*_mutex'), rt-mutex symbol
+	('*_rt_mutex'), or write-locked 'mmap_lock' ('lock_held_write(mmap_lock)'
+	or 'lock_held(mmap_lock:W)'), 'perf_sample_filter' inspects the lock's
 	'owner' field directly in kernel memory on each sample without attaching
 	any BPF fentry/fexit hooks.  For locks that do not maintain an
 	authoritative per-task owner pointer (such as spinlocks, rwlocks,
@@ -261,10 +264,11 @@ OPTIONS
 	to track held locks in a BPF map.  These BPF hooks run on every kernel
 	lock acquisition and release for the attached lock family, even when no
 	perf sample is being taken.  To minimize this overhead, only the hooks
-	for the relevant lock family and mode are attached when known, whereas
-	raw hex addresses or symbols without a recognizable lock-type suffix
-	attach hooks across all lock families (including high-frequency
-	spinlocks).
+	for the relevant lock family and mode are attached when known (for
+	example, 'lock_held_read(mmap_lock)' only hooks rwsem read functions
+	and 'rq_lock' only hooks spinlock functions), whereas raw hex addresses
+	or symbols without a recognizable lock-type suffix attach hooks across
+	all lock families (including high-frequency spinlocks).
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +180 -14

297 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +16 -2
index c240eee782f8..836b398dc62b 100644
@@ -59,8 +59,8 @@ enum perf_bpf_filter_term {
 	 * The lock specification kind is stored in `entry.part`
 	 * (`enum perf_bpf_lock_target_kind`), `entry.op` is normalized to
 	 * `PBF_OP_EQ` (match when held) or `PBF_OP_NEQ` (match when not held),
-	 * and the resolved target address or type flag encoding is stored in
-	 * `entry.value`.
+	 * and the resolved target address, class ID, or type flag encoding is
+	 * stored in `entry.value`.
 	 */
 	PBF_TERM_LOCK_HELD,
 };
@@ -76,6 +76,20 @@ enum perf_bpf_lock_target_kind {
 	 * given as a hex address). `entry.value` holds the kernel address.
 	 */
 	PBF_LOCK_ADDR,
+	/*
+	 * Per-process `current->mm->mmap_lock` (or `mmap_sem`).
+	 */
+	PBF_LOCK_MMAP,
+	/*
+	 * Per-process `current->sighand->siglock`.
+	 */
+	PBF_LOCK_SIGHAND,
+	/*
+	 * Semi-global lock class (`rq_lock` or `zone_lock`).
+	 * `entry.value` holds `enum lock_class_sym` (LOCK_CLASS_RQLOCK or
+	 * LOCK_CLASS_ZONE_LOCK).
+	 */
+	PBF_LOCK_CLASS,
 	/*
 	 * Lock type filter (`mutex`, `spinlock`, `rwsem`, `rwsem:R`, etc.).
 	 * `entry.value` packs up to two `LCB_F_*` flag combinations in the
tools/perf/util/bpf_skel/sample_filter.bpf.c +67 -0

113 lines not on this page · raw message

Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#120 lore raw

Re: [PATCH v7 07/11] perf bpf-filter: Support per-process and semi-global locks in lock_held()

Sashiko has reviewed this patch and found no issues.
Quoted 22 lines

Extend the lock_held() BPF sample filter to support well-known per-process and semi-global kernel locks:
- mmap_lock (or mmap_sem): current->mm->mmap_lock, supporting both read/shared (lock_held_read(mmap_lock) / lock_held(mmap_lock:R)) and write/exclusive (lock_held_write(mmap_lock) / lock_held(mmap_lock:W)) modes. Write ownership is inspected directly via is_rwsem_writer_owner() without attaching fentry/fexit hooks.
- siglock: current->sighand->siglock.
- rq_lock: per-CPU scheduler runqueue locks.
- zone_lock: memory management NUMA zone locks.

For rq_lock and zone_lock, reuse do_collect_lock_syms() from lock_data.h via a raw_tp/bpf_test_finish program run at filter setup time to populate the lock_syms map with each CPU's rq_lock and each NUMA node's zone_lock addresses.

Only zone_lock needs NUMA zone data from kallsyms and sysfs, so fail filter setup if it can't be found rather than attaching a filter that can never match.

Example usage:

Quoted 7 lines
  # perf record -a -g -e cycles --filter 'lock_held(mmap_lock)' \
      -- perf bench mem mmap -t 2 -l 100
  # perf record -a -g -e cycles --filter 'lock_held_read(mmap_lock)' ...
  # perf record -a -g -e cycles --filter 'lock_held_write(mmap_lock)' ...
  # perf record -a -g -e cycles --filter 'lock_held(mmap_lock:W)' ...

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 8/11 perf bpf-filter: Support slab cache locks (&<name>) in lock_held()

In reply to Ian Rogers

Extend the lock_held() BPF sample filter to support dynamically allocated kernel locks inside slab caches prefixed with '&' (e.g. lock_held(&dentry), lock_held_read(&dentry), lock_held_write(&dentry)).

Reuse do_slab_cache_iter() from lock_data.h via a SEC("iter/kmem_cache") program to resolve the requested slab cache name to its kernel struct kmem_cache * address, and use the bpf_get_kmem_cache() kfunc in record_lock_acquired_owner() and record_lock_released_addr() to match held locks allocated from that slab cache.

---
 tools/perf/Documentation/perf-record.txt     |  25 ++--
 tools/perf/util/bpf-filter.c                 | 124 ++++++++++++++++---
 tools/perf/util/bpf_skel/sample-filter.h     |   5 +
 tools/perf/util/bpf_skel/sample_filter.bpf.c |  48 +++++++
 4 files changed, 175 insertions(+), 27 deletions(-)
tools/perf/Documentation/perf-record.txt +14 -11
index 1c65f90dfb6b..8a160317304a 100644
@@ -227,13 +227,15 @@ OPTIONS
 	(alias 'lock_held_exclusive(<lock>)'), or append ':R' or ':W' to
 	<lock> (e.g. 'lock_held(mmap_lock:R)' or 'lock_held(mmap_lock:W)').
 	<lock> can be a kernel lock symbol name (e.g.
-	'lock_held(cgroup_mutex)'), a hexadecimal lock address, a well-known
-	lock name ('mmap_lock', 'siglock', 'rq_lock', 'zone_lock'), or a lock
-	type ('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
-	'rwlock:R', 'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W',
-	'semaphore').  Both read/shared and write/exclusive tracking are
-	supported for 'rwsem' (including 'mmap_lock') and 'rwlock'; 'mutex',
-	'spinlock' (including 'siglock', 'rq_lock', 'zone_lock'), 'rt-mutex',
+	'lock_held(cgroup_mutex)'), a hexadecimal lock address, a slab cache
+	name prefixed with '&' (e.g. 'lock_held(&dentry)',
+	'lock_held_read(&dentry)'), a well-known lock name ('mmap_lock',
+	'siglock', 'rq_lock', 'zone_lock'), or a lock type ('mutex',
+	'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock', 'rwlock:R',
+	'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W', 'semaphore').
+	Both read/shared and write/exclusive tracking are supported for
+	'rwsem' (including 'mmap_lock') and 'rwlock'; 'mutex', 'spinlock'
+	(including 'siglock', 'rq_lock', 'zone_lock'), 'rt-mutex',
 	'semaphore', and 'percpu-rwsem' ('percpu_down_write()') support
 	write/exclusive tracking only.  Note that 'semaphore' tracking
 	('down*()' / 'up()') assumes binary mutex-like usage where the
@@ -259,16 +261,17 @@ OPTIONS
 	'owner' field directly in kernel memory on each sample without attaching
 	any BPF fentry/fexit hooks.  For locks that do not maintain an
 	authoritative per-task owner pointer (such as spinlocks, rwlocks,
-	semaphores, reader-locked rwsems, and lock type filters), it attaches
+	semaphores, reader-locked rwsems, and slab/type filters), it attaches
 	BPF fentry/fexit programs to kernel lock acquire and release functions
 	to track held locks in a BPF map.  These BPF hooks run on every kernel
 	lock acquisition and release for the attached lock family, even when no
 	perf sample is being taken.  To minimize this overhead, only the hooks
 	for the relevant lock family and mode are attached when known (for
 	example, 'lock_held_read(mmap_lock)' only hooks rwsem read functions
-	and 'rq_lock' only hooks spinlock functions), whereas raw hex addresses
-	or symbols without a recognizable lock-type suffix attach hooks across
-	all lock families (including high-frequency spinlocks).
+	and 'rq_lock' only hooks spinlock functions), whereas slab filters
+	('&<slab>'), raw hex addresses, or symbols without a recognizable
+	lock-type suffix attach hooks across all lock families (including
+	high-frequency spinlocks).
 
 	The <operator> can be one of:
 	  ==, !=, >, >=, <, <=, &
tools/perf/util/bpf-filter.c +108 -16

247 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +5 -0
index 836b398dc62b..a65ee780d64d 100644
@@ -76,6 +76,11 @@ enum perf_bpf_lock_target_kind {
 	 * given as a hex address). `entry.value` holds the kernel address.
 	 */
 	PBF_LOCK_ADDR,
+	/*
+	 * Dynamic lock allocated inside a slab cache (`&slab_name`).
+	 * `entry.value` holds the kernel `struct kmem_cache *` address.
+	 */
+	PBF_LOCK_SLAB,
 	/*
 	 * Per-process `current->mm->mmap_lock` (or `mmap_sem`).
 	 */
tools/perf/util/bpf_skel/sample_filter.bpf.c +48 -0

97 lines not on this page · raw message

Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#122 lore raw

Re: [PATCH v7 08/11] perf bpf-filter: Support slab cache locks (&<name>) in lock_held()

Sashiko has reviewed this patch and found no issues.
Quoted 11 lines

Extend the lock_held() BPF sample filter to support dynamically allocated kernel locks inside slab caches prefixed with '&' (e.g. lock_held(&dentry), lock_held_read(&dentry), lock_held_write(&dentry)).

Reuse do_slab_cache_iter() from lock_data.h via a SEC("iter/kmem_cache") program to resolve the requested slab cache name to its kernel struct kmem_cache * address, and use the bpf_get_kmem_cache() kfunc in record_lock_acquired_owner() and record_lock_released_addr() to match held locks allocated from that slab cache.

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 9/11 perf test: Add tests for lock_held() BPF sample filter

In reply to Ian Rogers

Add unit tests in parse-events.c for parsing lock_held(), lock_held_read(), and lock_held_exclusive() BPF filter expressions (standalone predicates, negated predicates, and compound group expressions) and extend record_bpf_filter.sh with lock_held(), lock_held_read()/lock_held_write(), and ':R'/':W' recording tests.

Example output:

  # perf test -v 'Parsing of BPF sample filters'
    5: Parse event definition strings               :
    5.7: Parsing of BPF sample filters              : Ok
  # perf test -v 'perf record sample filtering (by BPF) tests'
  112: perf record sample filtering (by BPF) tests  :
  Checking BPF-filter privilege
  Basic bpf-filter test
  Basic bpf-filter test [Success]
  Failing bpf-filter test
  Failing bpf-filter test [Success]
  Group bpf-filter test
  Group bpf-filter test [Success]
  Multiple bpf-filter test
  Multiple bpf-filter test [Success]
  Cgroup bpf-filter test
  Cgroup bpf-filter test [Success]
  Lock-held bpf-filter test
  Lock-held bpf-filter test [Success]
  112: perf record sample filtering (by BPF) tests  : Ok
---
 tools/perf/tests/parse-events.c             | 108 +++++++++++++++++
 tools/perf/tests/shell/record_bpf_filter.sh | 122 ++++++++++++++++++++
 2 files changed, 230 insertions(+)
tools/perf/tests/parse-events.c +108 -0
index 5f6f95c8a5b4..4cf9192762f2 100644
@@ -8,9 +8,11 @@
 #include "debug.h"
 #include "pmu.h"
 #include "pmus.h"
+#include "bpf-filter.h"
 #include "strbuf.h"
 #include <dirent.h>
 #include <errno.h>
+#include <string.h>
 #include "fncache.h"
 #include <sys/types.h>
 #include <sys/stat.h>
@@ -2938,6 +2940,111 @@ static int test__pmu_events_alias2(struct test_suite *test __maybe_unused,
 	return ret;
 }
 
+#ifdef HAVE_BPF_SKEL
+static void clear_bpf_filter_exprs(struct list_head *expr_head)
+{
+	struct perf_bpf_filter_expr *expr, *tmp;
+
+	list_for_each_entry_safe(expr, tmp, expr_head, list) {
+		list_del(&expr->list);
+		perf_bpf_filter_expr__delete(expr);
+	}
+}
+
+static int do_test_bpf_filters(struct list_head *expr_head)
+{
+	struct perf_bpf_filter_expr *expr, *group;
+	const char *compound = "lock_held(rwsem:R) == 1 || lock_held(&dentry) != 0, period > 100";
+
+	/* Simple lock_held(&cgroup_mutex) */
+	TEST_ASSERT_VAL("parse lock_held(&cgroup_mutex)",
+			__perf_bpf_filter__parse(expr_head, "lock_held(&cgroup_mutex)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 1", expr->val == 1);
+	TEST_ASSERT_VAL("lock_name is &cgroup_mutex",
+			expr->lock_name && !strcmp(expr->lock_name, "&cgroup_mutex"));
+	clear_bpf_filter_exprs(expr_head);
+
+	/* Negated !lock_held(cgroup_mutex) */
+	TEST_ASSERT_VAL("parse !lock_held(cgroup_mutex)",
+			__perf_bpf_filter__parse(expr_head, "!lock_held(cgroup_mutex)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 0", expr->val == 0);
+	TEST_ASSERT_VAL("lock_name is cgroup_mutex",
+			expr->lock_name && !strcmp(expr->lock_name, "cgroup_mutex"));
+	clear_bpf_filter_exprs(expr_head);
+
+	/* Read/shared and write/exclusive predicates */
+	TEST_ASSERT_VAL("parse lock_held_read(&mmap_lock)",
+			__perf_bpf_filter__parse(expr_head, "lock_held_read(&mmap_lock)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("part is PBF_LOCK_MODE_READ", expr->part == PBF_LOCK_MODE_READ);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 1", expr->val == 1);
+	TEST_ASSERT_VAL("lock_name is &mmap_lock",
+			expr->lock_name && !strcmp(expr->lock_name, "&mmap_lock"));
+	clear_bpf_filter_exprs(expr_head);
+
+	TEST_ASSERT_VAL("parse !lock_held_exclusive(mmap_lock)",
+			__perf_bpf_filter__parse(expr_head,
+						 "!lock_held_exclusive(mmap_lock)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("part is PBF_LOCK_MODE_WRITE", expr->part == PBF_LOCK_MODE_WRITE);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 0", expr->val == 0);
+	TEST_ASSERT_VAL("lock_name is mmap_lock",
+			expr->lock_name && !strcmp(expr->lock_name, "mmap_lock"));
+	clear_bpf_filter_exprs(expr_head);
+
+	/*
+	 * Comparison and compound group:
+	 * lock_held(rwsem:R) == 1 || lock_held(&dentry) != 0, period > 100
+	 */
+	TEST_ASSERT_VAL("parse compound lock_held filter",
+			__perf_bpf_filter__parse(expr_head, compound) == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("group op", expr->op == PBF_OP_GROUP_BEGIN);
+	TEST_ASSERT_VAL("groups not empty", !list_empty(&expr->groups));
+	group = list_first_entry(&expr->groups, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("first group member lock_name",
+			group->lock_name && !strcmp(group->lock_name, "rwsem:R"));
+	TEST_ASSERT_VAL("first group member op", group->op == PBF_OP_EQ && group->val == 1);
+	group = list_last_entry(&expr->groups, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("second group member lock_name",
+			group->lock_name && !strcmp(group->lock_name, "&dentry"));
+	TEST_ASSERT_VAL("second group member op", group->op == PBF_OP_NEQ && group->val == 0);
+	expr = list_last_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("second term is period", expr->term == PBF_TERM_PERIOD && expr->val == 100);
+
+	return TEST_OK;
+}
+#endif
+
+static int test__bpf_filters(struct test_suite *test __maybe_unused,
+			     int subtest __maybe_unused)
+{
+#ifdef HAVE_BPF_SKEL
+	struct list_head expr_head = LIST_HEAD_INIT(expr_head);
+	int ret = do_test_bpf_filters(&expr_head);
+
+	clear_bpf_filter_exprs(&expr_head);
+	return ret;
+#else
+	return TEST_SKIP;
+#endif
+}
+
 static struct test_case tests__parse_events[] = {
 	TEST_CASE_REASON("Test event parsing",
 			 events2,
@@ -2952,6 +3059,7 @@ static struct test_case tests__parse_events[] = {
 			 "no aliases in sysfs"),
 	TEST_CASE("Parsing of aliased events", pmu_events_alias2),
 	TEST_CASE("Parsing of terms (event modifiers)", terms2),
+	TEST_CASE("Parsing of BPF sample filters", bpf_filters),
 	{	.name = NULL, }
 };
 
tools/perf/tests/shell/record_bpf_filter.sh +122 -0

133 lines not on this page · raw message

Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#124 lore raw

Re: [PATCH v7 09/11] perf test: Add tests for lock_held() BPF sample filter

Sashiko has reviewed this patch and found no issues.
Quoted 29 lines

Add unit tests in parse-events.c for parsing lock_held(), lock_held_read(), and lock_held_exclusive() BPF filter expressions (standalone predicates, negated predicates, and compound group expressions) and extend record_bpf_filter.sh with lock_held(), lock_held_read()/lock_held_write(), and ':R'/':W' recording tests.

Example output:

  # perf test -v 'Parsing of BPF sample filters'
    5: Parse event definition strings               :
    5.7: Parsing of BPF sample filters              : Ok
  # perf test -v 'perf record sample filtering (by BPF) tests'
  112: perf record sample filtering (by BPF) tests  :
  Checking BPF-filter privilege
  Basic bpf-filter test
  Basic bpf-filter test [Success]
  Failing bpf-filter test
  Failing bpf-filter test [Success]
  Group bpf-filter test
  Group bpf-filter test [Success]
  Multiple bpf-filter test
  Multiple bpf-filter test [Success]
  Cgroup bpf-filter test
  Cgroup bpf-filter test [Success]
  Lock-held bpf-filter test
  Lock-held bpf-filter test [Success]
  112: perf record sample filtering (by BPF) tests  : Ok
Quoted 1 line

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 10/11 perf bpf-filter: Extend lock_held() to support RCU, Tasks Trace RCU, and SRCU

In reply to Ian Rogers

Extend the lock_held(<lock>) BPF sample filter to support RCU, Tasks Trace RCU, and SRCU locks:

- 'rcu' (supports both read/shared and write/exclusive modes):
- Read/shared ('lock_held_read(rcu)', 'lock_held(rcu:R)', 'lock_held(rcu_read_lock)'): directly inspects current->rcu_read_lock_nesting in perf_sample_filter via CO-RE (on CONFIG_PREEMPT_RCU kernels), accounting for the baseline rcu_read_lock() nesting acquired by the perf overflow handler itself (bpf_overflow_handler() and do_perf_sw_event()) with zero extra fentry/fexit tracing hooks.
- Write/exclusive ('lock_held_write(rcu)', 'lock_held(rcu:W)'):
attaches fentry/fexit hooks to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), and rcu_barrier() to track grace-period and barrier waits.
- 'srcu' and specific SRCU symbols (e.g. '&srcu_symbol', supports both read/shared and write/exclusive modes):
- Read/shared ('lock_held_read(srcu)', 'lock_held(srcu:R)'): attaches fexit/__srcu_read_lock and fentry/__srcu_read_unlock.
- Write/exclusive ('lock_held_write(srcu)', 'lock_held(srcu:W)'):
attaches fentry/fexit on synchronize_srcu(), synchronize_srcu_expedited(), and srcu_barrier().
- 'rcu-trace' / 'rcu_trace' / 'rcu_read_lock_trace' (supports read/shared mode only): directly inspects current->trc_reader_nesting > 0 on CONFIG_TASKS_TRACE_RCU kernels with zero extra tracing hooks.

Example usage:

  # perf record -a -g -e cycles --filter 'lock_held_read(rcu)' -- sleep 1
  [ perf record: Woken up 1 times to write data ]
  [ perf record: Captured and wrote 1.482 MB perf.data (412 samples) ]
  # perf report --stdio --no-children
  # Overhead  Command  Shared Object      Symbol
  # ........  .......  .................  ........................
  #
      14.32%  perf     [kernel.kallsyms]  [k] __d_lookup_rcu
              |
              ---__d_lookup_rcu
                 lookup_fast
                 walk_component
                 link_path_walk
                 path_lookupat
                 filename_lookup
                 vfs_statx
                 __do_sys_newstat
                 do_syscall_64
                 entry_SYSCALL_64_after_hwframe
  # perf record -a -g -e task-clock --filter 'lock_held(rcu:W)' -- sleep 1
  # perf record -a -g -e cycles --filter 'lock_held(srcu)' -- sleep 1
---
 tools/perf/Documentation/perf-record.txt     |  44 ++--
 tools/perf/tests/parse-events.c              |  13 +
 tools/perf/tests/shell/record_bpf_filter.sh  |  20 ++
 tools/perf/util/bpf-filter.c                 | 244 ++++++++++++++++++-
 tools/perf/util/bpf_skel/lock_data.h         |  47 +++-
 tools/perf/util/bpf_skel/sample-filter.h     |  14 ++
 tools/perf/util/bpf_skel/sample_filter.bpf.c | 136 ++++++++++-
 tools/perf/util/bpf_skel/vmlinux/vmlinux.h   |   2 +
 tools/perf/util/lock-contention.c            |   4 +
 tools/perf/util/lock-contention.h            |   4 +-
 10 files changed, 497 insertions(+), 31 deletions(-)
tools/perf/Documentation/perf-record.txt +26 -18
index 8a160317304a..6e30cbef1878 100644
@@ -230,11 +230,17 @@ OPTIONS
 	'lock_held(cgroup_mutex)'), a hexadecimal lock address, a slab cache
 	name prefixed with '&' (e.g. 'lock_held(&dentry)',
 	'lock_held_read(&dentry)'), a well-known lock name ('mmap_lock',
-	'siglock', 'rq_lock', 'zone_lock'), or a lock type ('mutex',
-	'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock', 'rwlock:R',
-	'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W', 'semaphore').
-	Both read/shared and write/exclusive tracking are supported for
-	'rwsem' (including 'mmap_lock') and 'rwlock'; 'mutex', 'spinlock'
+	'siglock', 'rq_lock', 'zone_lock', 'rcu', 'rcu-trace'), or a lock
+	type ('mutex', 'spinlock', 'rwsem', 'rwsem:R', 'rwsem:W', 'rwlock',
+	'rwlock:R', 'rwlock:W', 'rt-mutex', 'percpu-rwsem', 'pcpu-sem:W',
+	'srcu', 'srcu:R', 'srcu:W', 'rcu:R', 'rcu:W', 'semaphore').  Both
+	read/shared and write/exclusive tracking are supported for 'rwsem'
+	(including 'mmap_lock'), 'rwlock', 'rcu', and 'srcu' (where
+	read/shared mode matches 'rcu_read_lock()' / 'srcu_read_lock()'
+	critical sections and write/exclusive mode matches grace-period
+	waits 'synchronize_rcu*()', 'synchronize_srcu*()', 'rcu_barrier()',
+	and 'srcu_barrier()'); 'rcu-trace' ('rcu_read_lock_trace()')
+	supports read/shared tracking only; and 'mutex', 'spinlock'
 	(including 'siglock', 'rq_lock', 'zone_lock'), 'rt-mutex',
 	'semaphore', and 'percpu-rwsem' ('percpu_down_write()') support
 	write/exclusive tracking only.  Note that 'semaphore' tracking
@@ -256,19 +262,21 @@ OPTIONS
 	      --filter 'lock_held(mutex) || lock_held(rwsem)'
 
 	When filtering on a specific mutex symbol ('*_mutex'), rt-mutex symbol
-	('*_rt_mutex'), or write-locked 'mmap_lock' ('lock_held_write(mmap_lock)'
-	or 'lock_held(mmap_lock:W)'), 'perf_sample_filter' inspects the lock's
-	'owner' field directly in kernel memory on each sample without attaching
-	any BPF fentry/fexit hooks.  For locks that do not maintain an
-	authoritative per-task owner pointer (such as spinlocks, rwlocks,
-	semaphores, reader-locked rwsems, and slab/type filters), it attaches
-	BPF fentry/fexit programs to kernel lock acquire and release functions
-	to track held locks in a BPF map.  These BPF hooks run on every kernel
-	lock acquisition and release for the attached lock family, even when no
-	perf sample is being taken.  To minimize this overhead, only the hooks
-	for the relevant lock family and mode are attached when known (for
-	example, 'lock_held_read(mmap_lock)' only hooks rwsem read functions
-	and 'rq_lock' only hooks spinlock functions), whereas slab filters
+	('*_rt_mutex'), write-locked 'mmap_lock' ('lock_held_write(mmap_lock)'
+	or 'lock_held(mmap_lock:W)'), or 'rcu:R' / 'rcu-trace' (which inspect
+	'current->rcu_read_lock_nesting' / 'current->trc_reader_nesting'),
+	'perf_sample_filter' inspects the kernel fields directly on each sample
+	without attaching any BPF fentry/fexit hooks.  For locks that do not
+	maintain an authoritative per-task owner pointer (such as spinlocks,
+	rwlocks, semaphores, reader-locked rwsems, SRCU locks, RCU synchronize
+	waits, and slab/type filters), it attaches BPF fentry/fexit programs to
+	kernel lock acquire and release functions to track held locks in a BPF
+	map.  These BPF hooks run on every kernel lock acquisition and release
+	for the attached lock family, even when no perf sample is being taken.
+	To minimize this overhead, only the hooks for the relevant lock family
+	and mode are attached when known (for example, 'lock_held_read(mmap_lock)'
+	only hooks rwsem read functions, 'srcu' only hooks SRCU functions, and
+	'rq_lock' only hooks spinlock functions), whereas slab filters
 	('&<slab>'), raw hex addresses, or symbols without a recognizable
 	lock-type suffix attach hooks across all lock families (including
 	high-frequency spinlocks).
tools/perf/tests/parse-events.c +13 -0
index 4cf9192762f2..730466b7ebf6 100644
@@ -2980,6 +2980,19 @@ static int do_test_bpf_filters(struct list_head *expr_head)
 			expr->lock_name && !strcmp(expr->lock_name, "cgroup_mutex"));
 	clear_bpf_filter_exprs(expr_head);
 
+	/* RCU and SRCU lock_held(rcu) || lock_held(srcu) */
+	TEST_ASSERT_VAL("parse lock_held(rcu)",
+			__perf_bpf_filter__parse(expr_head, "lock_held(rcu)") == 0);
+	TEST_ASSERT_VAL("not empty", !list_empty(expr_head));
+	expr = list_first_entry(expr_head, struct perf_bpf_filter_expr, list);
+	TEST_ASSERT_VAL("term is PBF_TERM_LOCK_HELD", expr->term == PBF_TERM_LOCK_HELD);
+	TEST_ASSERT_VAL("part is PBF_LOCK_MODE_ANY", expr->part == PBF_LOCK_MODE_ANY);
+	TEST_ASSERT_VAL("op is PBF_OP_EQ", expr->op == PBF_OP_EQ);
+	TEST_ASSERT_VAL("val is 1", expr->val == 1);
+	TEST_ASSERT_VAL("lock_name is rcu",
+			expr->lock_name && !strcmp(expr->lock_name, "rcu"));
+	clear_bpf_filter_exprs(expr_head);
+
 	/* Read/shared and write/exclusive predicates */
 	TEST_ASSERT_VAL("parse lock_held_read(&mmap_lock)",
 			__perf_bpf_filter__parse(expr_head, "lock_held_read(&mmap_lock)") == 0);
tools/perf/tests/shell/record_bpf_filter.sh +20 -0
index ebaf8ee41622..47f697f53a85 100755
@@ -247,6 +247,26 @@ test_bpf_filter_lock_held() {
     return
   fi
 
+  if ! perf record -e task-clock --filter 'lock_held_write(rcu) || lock_held(srcu)' \
+       -o "${perfdata}" true 2> /dev/null
+  then
+    echo "Lock-held bpf-filter test [Failed rcu:W/srcu]"
+    err=1
+    return
+  fi
+
+  if ! perf record -e task-clock --filter 'lock_held_read(rcu)' \
+       -o "${perfdata}" true 2> /dev/null
+  then
+    if ! perf record -e task-clock --filter 'lock_held_read(rcu)' \
+         -o /dev/null true 2>&1 | grep -q CONFIG_PREEMPT_RCU
+    then
+      echo "Lock-held bpf-filter test [Failed lock_held_read(rcu)]"
+      err=1
+      return
+    fi
+  fi
+
   if ! perf record -e task-clock \
        --filter 'lock_held_read(mmap_lock) || lock_held_write(mmap_lock)' \
        -o "${perfdata}" true 2> /dev/null
tools/perf/util/bpf-filter.c +236 -8

342 lines not on this page · raw message

tools/perf/util/bpf_skel/lock_data.h +45 -2

72 lines not on this page · raw message

tools/perf/util/bpf_skel/sample-filter.h +14 -0
index a65ee780d64d..7abc530ed50d 100644
@@ -101,6 +101,20 @@ enum perf_bpf_lock_target_kind {
 	 * low two bytes: `flag1 | (flag2 << 8)` (with 0xff indicating unused).
 	 */
 	PBF_LOCK_TYPE,
+	/*
+	 * Preemptible RCU read-side lock (`rcu` / `rcu_read_lock`).
+	 * Inspected directly via `current->rcu_read_lock_nesting > entry.value`,
+	 * where `entry.value` is the baseline RCU nesting depth added by the
+	 * kernel perf overflow path.
+	 */
+	PBF_LOCK_RCU,
+	/*
+	 * Tasks Trace RCU read-side lock (`rcu-trace` / `rcu_read_lock_trace`).
+	 * Inspected directly via `current->trc_reader_nesting > entry.value`,
+	 * where `entry.value` is the baseline nesting depth added by the
+	 * kernel event tracing path.
+	 */
+	PBF_LOCK_RCU_TRACE,
 };
 
 /*
tools/perf/util/bpf_skel/sample_filter.bpf.c +134 -2

169 lines not on this page · raw message

tools/perf/util/bpf_skel/vmlinux/vmlinux.h +2 -0
index b75ddc6846bb..1fb91a829d54 100644
@@ -119,6 +119,8 @@ struct task_struct {
 	struct signal_struct  *signal;
 	struct sighand_struct *sighand;
 	struct css_set	      *cgroups;
+	int		      rcu_read_lock_nesting;
+	int		      trc_reader_nesting;
 } __attribute__((preserve_access_index));
 
 struct trace_entry {
tools/perf/util/lock-contention.c +4 -0
index f6e68d740860..37415f7b7f2c 100644
@@ -39,6 +39,10 @@ const struct perf_lock_type lock_type_table[] = {
 	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex",	"mutex" },
 	/* alias for optimistic spinning only */
 	{ LCB_F_MUTEX | LCB_F_SPIN,	"mutex:spin",	"mutex-spin" },
+	{ LCB_F_SRCU | LCB_F_READ,	"srcu:R",	"srcu" },
+	{ LCB_F_SRCU | LCB_F_WRITE,	"srcu:W",	"srcu" },
+	{ LCB_F_RCU | LCB_F_READ,	"rcu:R",	"rcu" },
+	{ LCB_F_RCU | LCB_F_WRITE,	"rcu:W",	"rcu" },
 };
 
 int parse_call_stack(const struct option *opt __maybe_unused, const char *str,
tools/perf/util/lock-contention.h +3 -1
index 68e9bd77e8a9..88b2c11244ad 100644
@@ -128,6 +128,8 @@ struct thread_stat {
 #define LCB_F_RT	(1U << 3)
 #define LCB_F_PERCPU	(1U << 4)
 #define LCB_F_MUTEX	(1U << 5)
+#define LCB_F_SRCU	(1U << 6)
+#define LCB_F_RCU	(1U << 7)
 
 struct perf_lock_type {
 	unsigned int flags;
@@ -140,7 +142,7 @@ struct perf_lock_type {
 	const char *lock_name;
 };
 
-extern const struct perf_lock_type lock_type_table[14];
+extern const struct perf_lock_type lock_type_table[18];
 
 struct evlist;
 struct machine;
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#126 lore raw

Re: [PATCH v7 10/11] perf bpf-filter: Extend lock_held() to support RCU, Tasks Trace RCU, and SRCU

Sashiko has reviewed this patch and found no issues.
Quoted 17 lines

Extend the lock_held(<lock>) BPF sample filter to support RCU, Tasks Trace RCU, and SRCU locks:

- 'rcu' (supports both read/shared and write/exclusive modes):
- Read/shared ('lock_held_read(rcu)', 'lock_held(rcu:R)', 'lock_held(rcu_read_lock)'): directly inspects current->rcu_read_lock_nesting in perf_sample_filter via CO-RE (on CONFIG_PREEMPT_RCU kernels), accounting for the baseline rcu_read_lock() nesting acquired by the perf overflow handler itself (bpf_overflow_handler() and do_perf_sw_event()) with zero extra fentry/fexit tracing hooks.
- Write/exclusive ('lock_held_write(rcu)', 'lock_held(rcu:W)'):
attaches fentry/fexit hooks to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), and rcu_barrier() to track grace-period and barrier waits.
[ ... ]

Quoted 4 lines
  # perf record -a -g -e task-clock --filter 'lock_held(rcu:W)' -- sleep 1
  # perf record -a -g -e cycles --filter 'lock_held(srcu)' -- sleep 1

Sashiko has reviewed this patch and found no issues.

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

PATCH v7 11/11 perf lock contention: Extend BPF lock contention to RCU and SRCU

In reply to Ian Rogers

Extend 'perf lock contention --use-bpf' to track RCU and SRCU grace-period and barrier waits:

- Attach fentry/fexit programs to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), rcu_barrier(), synchronize_srcu(), synchronize_srcu_expedited(), and srcu_barrier() when available in BTF.
- Support filtering by lock type ('-Y rcu', '-Y rcu:W', '-Y srcu', '-Y srcu:W') and by lock name ('-L rcu' or specific srcu_struct symbol names).

Example usage:

  # perf lock con -a -b -Y rcu,srcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait         type   caller
       35.12 ms      8.78 ms        rcu:W   cleanup_net+0x284
        7.84 ms      3.92 ms       srcu:W   __fsnotify_parent+0x114
  # perf lock con -a -b -l -L rcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait            address   symbol
       35.12 ms      8.78 ms   ffffffff83754dc0   rcu (rcu)
---
 tools/perf/Documentation/perf-lock.txt        |   7 +-
 tools/perf/tests/shell/lock_contention.sh     |  14 ++
 tools/perf/util/bpf_lock_contention.c         | 174 +++++++++++++-
 .../perf/util/bpf_skel/lock_contention.bpf.c  | 222 ++++++++++++++----
 tools/perf/util/machine.c                     |  11 +
 5 files changed, 366 insertions(+), 62 deletions(-)
tools/perf/Documentation/perf-lock.txt +5 -2
index c17b3e318169..bfeb98c976e3 100644
@@ -188,11 +188,14 @@ CONTENTION OPTIONS
 	Show lock contention only for given lock types (comma separated list).
 	Available values are:
 	  semaphore, spinlock, rwlock, rwlock:R, rwlock:W, rwsem, rwsem:R, rwsem:W,
-	  rtmutex, rwlock-rt, rwlock-rt:R, rwlock-rt:W, percpu-rwmem, pcpu-sem,
-	  pcpu-sem:R, pcpu-sem:W, mutex
+	  rtmutex, rwlock-rt, rwlock-rt:R, rwlock-rt:W, percpu-rwsem, pcpu-sem,
+	  pcpu-sem:R, pcpu-sem:W, mutex, srcu, srcu:W, rcu, rcu:W
 
 	Note that RW-variant of locks have :R and :W suffix.  Names without the
 	suffix are shortcuts for the both variants.  Ex) rwsem = rwsem:R + rwsem:W.
+	For RCU and SRCU with --use-bpf, contention tracks grace-period and
+	barrier waits (synchronize_rcu*(), synchronize_srcu*(), rcu_barrier(),
+	srcu_barrier()).
 
 -L::
 --lock-filter=<value>::
tools/perf/tests/shell/lock_contention.sh +14 -0
index 5df9a0cd48a3..999dcfd1ef26 100755
@@ -181,6 +181,13 @@ test_type_filter()
 		err=1
 		exit
 	fi
+
+	perf lock con -a -b -Y rcu -q -- true > /dev/null 2> ${result}
+	if [ "$(grep -c -v -w rcu "${result}")" != "0" ]; then
+		echo "[Fail] BPF result should not have non-rcu locks:" "$(cat "${result}")"
+		err=1
+		exit
+	fi
 }
 
 test_lock_filter()
@@ -224,6 +231,13 @@ test_lock_filter()
 		err=1
 		exit
 	fi
+
+	perf lock con -a -b -L rcu -q -- true > /dev/null 2> ${result}
+	if [ "$(grep -c -v -w rcu "${result}")" != "0" ]; then
+		echo "[Fail] BPF result should not have non-rcu locks:" "$(cat "${result}")"
+		err=1
+		exit
+	fi
 }
 
 test_stack_filter()
tools/perf/util/bpf_lock_contention.c +161 -13

239 lines not on this page · raw message

tools/perf/util/bpf_skel/lock_contention.bpf.c +175 -47

361 lines not on this page · raw message

tools/perf/util/machine.c +11 -0
index 1d9d3bf57720..0a0f223b3335 100644
@@ -3379,6 +3379,17 @@ bool machine__is_lock_function(struct machine *machine, u64 addr)
 			return true;
 	}
 
+	{
+		struct symbol *sym = machine__find_kernel_symbol(machine, addr, NULL);
+
+		if (sym && (!strncmp(sym->name, "synchronize_rcu", 15) ||
+			    !strncmp(sym->name, "synchronize_srcu", 16) ||
+			    !strcmp(sym->name, "__synchronize_srcu") ||
+			    !strcmp(sym->name, "rcu_barrier") ||
+			    !strcmp(sym->name, "srcu_barrier")))
+			return true;
+	}
+
 	return false;
 }
 
Signature · 1 line
2.56.0.307.g5fe7bd680c-goog
#128 lore raw

Re: [PATCH v7 11/11] perf lock contention: Extend BPF lock contention to RCU and SRCU

Sashiko has reviewed this patch and found no issues.
Quoted 19 lines

Extend 'perf lock contention --use-bpf' to track RCU and SRCU grace-period and barrier waits:

- Attach fentry/fexit programs to synchronize_rcu(), synchronize_rcu_expedited(), synchronize_rcu_tasks(), rcu_barrier(), synchronize_srcu(), synchronize_srcu_expedited(), and srcu_barrier() when available in BTF.
- Support filtering by lock type ('-Y rcu', '-Y rcu:W', '-Y srcu', '-Y srcu:W') and by lock name ('-L rcu' or specific srcu_struct symbol names).

Example usage:

  # perf lock con -a -b -Y rcu,srcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait         type   caller
       35.12 ms      8.78 ms        rcu:W   cleanup_net+0x284
        7.84 ms      3.92 ms       srcu:W   __fsnotify_parent+0x114
Quoted 6 lines
  # perf lock con -a -b -l -L rcu -F wait_total,avg_wait -- sleep 1
     total wait     avg wait            address   symbol
       35.12 ms      8.78 ms   ffffffff83754dc0   rcu (rcu)

Sashiko has reviewed this patch and found no issues.

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