Add support for BPF monitors
Subsystems (4)
Gabriele Monaco
maintainerv2 cover Add support for BPF monitors
Extend the rv userspace tool to load BPF monitors, those can be found in specific locations (e.g. /usr/share/rv/bpf_monitors/) and are plain object files including BTF data.
This type of BPF monitors can be generated from rvgen using the -b flag just like in-kernel monitors and, after manual adaptation, can be built and run transparently by the rv userspace tool.
Only DA monitors are supported (as they are the only class the rv tool currenly supports) and the tool aims to work in the same way for both in-kernel and BPF monitors.
The da_monitor header is adapted to be included directly in BPF programs and share as much logic as possible.
BPF monitors are implemented purely in BPF and as such require the rv userspace tool for any operation:
* listing: find properly formatted objects in specific locations
* running: load trace handlers for events
* tracing: read event/errors from the ring buffer
* reactors: link a react() function over the object
Selftests (make -C tools/verification/rv check) are present to validate and demonstrate the usage, which is mostly equivalent to the standard rv tool usage.
Patch 1 adds tracepoints required in a later monitor example. Patch 2 improves the rv tool selftest reporting.
Patches 3-4 prepare the kernel headers for BPF support. Patch 5 adds a feature check for tools/build.
Patch 6-8 prepare and add support for BPF monitors in the rv tool. Patch 9-11 prepare and include BPF monitors examples.
Patch 12 adds support for BPF reactors.
Patch 13 adds support for generating BPF monitors in rvgen. Patch 14-15 adds BPF selftests (make check) for the rv and rvgen tools.
Changes since RFC [1]:
* Drop struct_ops integration to favour a BPF-only implementation.
* Implement BPF reactors with a dynamic linker.
* Don't pin programs and maps.
* Improve handler performance when not tracing.
[1] - https://lore.kernel.org/lkml/[email protected]
To: [email protected]
To: [email protected]
Cc: Steven Rostedt <[email protected]>
Cc: Alexei Starovoitov <[email protected]>
Cc: Nam Cao <[email protected]>
Cc: Wen Yang <[email protected]>
Cc: Tobias Schaffner <[email protected]>
Cc: Viktor Malik <[email protected]>
Gabriele Monaco (14):
tools/rv: Skip empty pid error in selftest if command failed
rv: Refactor da_trace() functions to get strings internally
rv: Cast result of model_get_*_name()
tools/rv: Move argument parsing from in_kernel to utils tools/build: Add a feature test for bpftool-btf tools/rv: Implement BPF monitor discovery and listing tools/rv: Implement BPF monitor loading and tracing tools/rv: Copy stripped bpf_atomic.h from libarena tools/rv: Add BPF monitors
tools/rv: Define CONFIG_X86_64 statically for BPF monitors tools/rv: Add reactors support to BPF monitors verification/rvgen: Add support for BPF monitors tools/rv: Add selftest for rv bpf monitors verification/rvgen: Add selftest for rvgen -b
Nam Cao (1):
sched: Add task enqueue/dequeue trace points
include/rv/automata.h | 4 +- include/rv/da_monitor.h | 61 +- include/trace/events/sched.h | 8 + kernel/sched/core.c | 12 +- kernel/sched/sched.h | 2 + tools/build/Makefile.feature | 1 + tools/build/feature/Makefile | 7 +- tools/verification/models/nohz.dot | 16 + tools/verification/models/tqueue.dot | 15 + tools/verification/rv/Makefile | 54 +- tools/verification/rv/Makefile.config | 49 + tools/verification/rv/Makefile.rv | 10 + tools/verification/rv/bpf_monitors/.gitignore | 2 + .../verification/rv/bpf_monitors/bpf_atomic.h | 105 ++ .../rv/bpf_monitors/da_monitor_bpf.h | 374 +++++++ tools/verification/rv/bpf_monitors/nohz.c | 42 + tools/verification/rv/bpf_monitors/nohz.h | 49 + tools/verification/rv/bpf_monitors/tqueue.c | 30 + tools/verification/rv/bpf_monitors/tqueue.h | 47 + tools/verification/rv/bpf_reactors/.gitignore | 2 + tools/verification/rv/bpf_reactors/panic.c | 15 + tools/verification/rv/bpf_reactors/printk.c | 13 + tools/verification/rv/include/bpf_monitor.h | 22 + tools/verification/rv/include/utils.h | 19 +- tools/verification/rv/src/Build | 5 + tools/verification/rv/src/bpf_monitor.c | 982 ++++++++++++++++++ tools/verification/rv/src/in_kernel.c | 176 +--- tools/verification/rv/src/rv.c | 5 + tools/verification/rv/src/utils.c | 98 +- tools/verification/rv/tests/rv_list.t | 6 +- tools/verification/rv/tests/rv_mon.t | 61 +- tools/verification/rvgen/__main__.py | 15 +- tools/verification/rvgen/rvgen/dot2c.py | 15 +- tools/verification/rvgen/rvgen/dot2k.py | 22 +- tools/verification/rvgen/rvgen/generator.py | 26 +- .../rvgen/rvgen/templates/dot2k/main_bpf.c | 21 + .../tests/golden/da_bpf_cpu/da_bpf_cpu.c | 35 + .../tests/golden/da_bpf_cpu/da_bpf_cpu.h | 47 + .../tests/golden/da_bpf_obj/da_bpf_obj.c | 49 + .../tests/golden/da_bpf_obj/da_bpf_obj.h | 47 + .../verification/rvgen/tests/rvgen_monitor.t | 11 + tools/verification/tests/engine.sh | 5 +- 42 files changed, 2392 insertions(+), 193 deletions(-) create mode 100644 tools/verification/models/nohz.dot create mode 100644 tools/verification/models/tqueue.dot create mode 100644 tools/verification/rv/bpf_monitors/.gitignore create mode 100644 tools/verification/rv/bpf_monitors/bpf_atomic.h create mode 100644 tools/verification/rv/bpf_monitors/da_monitor_bpf.h create mode 100644 tools/verification/rv/bpf_monitors/nohz.c create mode 100644 tools/verification/rv/bpf_monitors/nohz.h create mode 100644 tools/verification/rv/bpf_monitors/tqueue.c create mode 100644 tools/verification/rv/bpf_monitors/tqueue.h create mode 100644 tools/verification/rv/bpf_reactors/.gitignore create mode 100644 tools/verification/rv/bpf_reactors/panic.c create mode 100644 tools/verification/rv/bpf_reactors/printk.c create mode 100644 tools/verification/rv/include/bpf_monitor.h create mode 100644 tools/verification/rv/src/bpf_monitor.c create mode 100644 tools/verification/rvgen/rvgen/templates/dot2k/main_bpf.c create mode 100644 tools/verification/rvgen/tests/golden/da_bpf_cpu/da_bpf_cpu.c create mode 100644 tools/verification/rvgen/tests/golden/da_bpf_cpu/da_bpf_cpu.h create mode 100644 tools/verification/rvgen/tests/golden/da_bpf_obj/da_bpf_obj.c create mode 100644 tools/verification/rvgen/tests/golden/da_bpf_obj/da_bpf_obj.h
base-commit: 238650ef6c7c7cca08e032527329424c9fbd70e5
Signature · 1 line
2.55.0
Gabriele Monaco
maintainerPATCH v2 1/15 sched: Add task enqueue/dequeue trace points
From: Nam Cao <[email protected]>
Add trace points into enqueue_task() and dequeue_task().
--- include/trace/events/sched.h | 8 ++++++++ kernel/sched/core.c | 12 +++++++++++- kernel/sched/sched.h | 2 ++ 3 files changed, 21 insertions(+), 1 deletion(-)
include/trace/events/sched.h +8 -0
@@ -896,6 +896,14 @@ DECLARE_TRACE(sched_set_need_resched, TP_PROTO(struct task_struct *tsk, int cpu, int tif), TP_ARGS(tsk, cpu, tif)); +DECLARE_TRACE (sched_enqueue, + TP_PROTO(struct task_struct *tsk, int cpu), +TP_ARGS (tsk, cpu)); + +DECLARE_TRACE (sched_dequeue, + TP_PROTO(struct task_struct *tsk, int cpu), +TP_ARGS (tsk, cpu)); +#define DL_OTHER 0#define DL_TASK 1#define DL_SERVER_FAIR 2
kernel/sched/core.c +11 -1
@@ -121,6 +121,8 @@ EXPORT_TRACEPOINT_SYMBOL_GPL(sched_compute_energy_tp);EXPORT_TRACEPOINT_SYMBOL_GPL (sched_entry_tp);EXPORT_TRACEPOINT_SYMBOL_GPL (sched_exit_tp);EXPORT_TRACEPOINT_SYMBOL_GPL (sched_set_need_resched_tp); +EXPORT_TRACEPOINT_SYMBOL_GPL (sched_enqueue_tp); +EXPORT_TRACEPOINT_SYMBOL_GPL (sched_dequeue_tp);EXPORT_TRACEPOINT_SYMBOL_GPL (sched_dl_throttle_tp);EXPORT_TRACEPOINT_SYMBOL_GPL (sched_dl_replenish_tp);EXPORT_TRACEPOINT_SYMBOL_GPL (sched_dl_update_tp);
@@ -2181,6 +2183,9 @@ unsigned long get_wchan(struct task_struct *p)void enqueue_task (struct rq *rq,struct task_struct *p,int flags) { +if (trace_sched_enqueue_tp_enabled () && !(flags &ENQUEUE_DELAYED )) +trace_call__sched_enqueue_tp (p,cpu_of (rq)); +if (!(flags &ENQUEUE_NOCLOCK ))update_rq_clock (rq);
@@ -2207,6 +2212,8 @@ void enqueue_task(struct rq *rq, struct task_struct *p, int flags)*/ inline bool dequeue_task (struct rq *rq,struct task_struct *p,int flags) { +bool ret; +if (sched_core_enabled (rq))sched_core_dequeue (rq, p, flags);
@@ -2223,7 +2230,10 @@ inline bool dequeue_task(struct rq *rq, struct task_struct *p, int flags)* and mark the task ->sched_delayed. */ uclamp_rq_dec (rq, p); -return p->sched_class->dequeue_task (rq, p, flags); + ret = p->sched_class->dequeue_task (rq, p, flags); +if (trace_sched_dequeue_tp_enabled () && !(flags &DEQUEUE_SLEEP )) +trace_call__sched_dequeue_tp (p,cpu_of (rq)); +return ret; }void activate_task (struct rq *rq,struct task_struct *p,int flags)
kernel/sched/sched.h +2 -0
@@ -3070,6 +3070,8 @@ static inline void sub_nr_running(struct rq *rq, unsigned count)static inline void __block_task (struct rq *rq,struct task_struct *p) { +trace_sched_dequeue_tp (p,cpu_of (rq)); +if (p->sched_contributes_to_load) rq->nr_uninterruptible++;
Signature · 1 line
2.55.0
Peter Zijlstra
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
Quoted 6 lines · Gabriele Monaco
From: Nam Cao <[email protected]>
Add trace points into
enqueue_task()anddequeue_task().Signed-off-by Nam Cao <[email protected]>Suggested-by Peter Zijlstra <[email protected]>
Obviously I don't remember anything at all. But also, you 'forgot' to send me the rest of the patches which might hold a clue. As is I'm clueless as to why we want this, since the Changelog also offers none.
Gabriele Monaco
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
Quoted 11 lines · Peter Zijlstra
Quoted 6 lines · Gabriele Monaco
From: Nam Cao <[email protected]>
Add trace points into
enqueue_task()anddequeue_task().Signed-off-by Nam Cao <[email protected]>Suggested-by Peter Zijlstra <[email protected]>Obviously I don't remember anything at all. But also, you 'forgot' to send me the rest of the patches which might hold a clue. As is I'm clueless as to why we want this, since the Changelog also offers none.
Right..
This commit is part of [1], but borrowed from [2], which is actually more interesting to understand why I need those tracepoints.
[2] contains 3 other RV deadline monitors, I should have at least CC'd you in
[3] and [4].. Essentially the enqueue and dequeue tracepoints are used to:
* model the event from dl_server idle to ready (a new fair task is available)
* understand when a task is moved to and from another scheduler runqueue
Thanks,
Gabriele
[1] - https://lore.kernel.org/lkml/[email protected]
[2] - https://lore.kernel.org/lkml/[email protected]
[3] - https://lore.kernel.org/lkml/[email protected]
[4] - https://lore.kernel.org/lkml/[email protected]
Peter Zijlstra
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
Quoted 24 lines · Gabriele Monaco
Quoted 11 lines · Peter Zijlstra
Quoted 6 lines · Gabriele Monaco
From: Nam Cao <[email protected]>
Add trace points into
enqueue_task()anddequeue_task().Signed-off-by Nam Cao <[email protected]>Suggested-by Peter Zijlstra <[email protected]>Obviously I don't remember anything at all. But also, you 'forgot' to send me the rest of the patches which might hold a clue. As is I'm clueless as to why we want this, since the Changelog also offers none.
Right..
This commit is part of [1], but borrowed from [2], which is actually more interesting to understand why I need those tracepoints.
[2] contains 3 other RV deadline monitors, I should have at least CC'd you in
[3] and [4].. Essentially the enqueue and dequeue tracepoints are used to:* model the event from
dl_serveridle to ready (a new fair task is available)
* understand when a task is moved to and from another scheduler runqueue
Quoted 7 lines
Thanks,
Gabriele[1] - https://lore.kernel.org/lkml/[email protected]
[2] - https://lore.kernel.org/lkml/[email protected]
[3] - https://lore.kernel.org/lkml/[email protected]
[4] - https://lore.kernel.org/lkml/[email protected]
So mostly I flat out out ignore partial series. It means I have to go dig around to figure out the whole picture, and anything that requires extra effort goes on the 'later' pile, and you know where that lives.
Now, as to 3,4; I'm confused. If I search 'enqueue' I see there is a tracepoint attach thingy in the .c file, but I don't see the corresponding bits in the .dot file. And per my understanding the .c thing is an artifact of the .dot file.
So what gives?
Also, IMO it would be *much* preferred if the .rst file would not exist. Just have the graph-easy and the description as a comment in the .dot file. Then you have the whole thing in one *readable* place.
...insert rant on what a piece of shit rst is here...
Gabriele Monaco
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
Quoted 3 lines · Peter Zijlstra
So mostly I flat out out ignore partial series. It means I have to go dig around to figure out the whole picture, and anything that requires extra effort goes on the 'later' pile, and you know where that lives.
Alright, I guess I'm going to have to fix my to_cmd script.
Quoted 4 lines
Now, as to 3,4; I'm confused. If I search 'enqueue' I see there is a tracepoint attach thingy in the .c file, but I don't see the corresponding bits in the .dot file. And per my understanding the .c thing is an artifact of the .dot file.
Yes but only partially. There isn't always a 1-1 mapping with model events and tracepoints.
Throttle uses handle_sched_enqueue() for one case of dl_defer_arm, representing a fair task running not boosted, in the enqueue case, because it was running with another scheduler.
Boost uses handle_sched_dequeue() in a similar fashion to describe fair tasks that stop running on the fair runqueue (but may continue on another runqueue).
In both cases I'm reusing an event that can be triggered from other tracepoints too, ideally to keep the model simpler.
Then it uses handle_sched_enqueue() for dl_server_resume[_throttled]. They are both plain enqueues, in fact, so I could rename them to show what they are.
Quoted 3 lines
Also, IMO it would be *much* preferred if the .rst file would not exist. Just have the graph-easy and the description as a comment in the .dot file. Then you have the whole thing in one *readable* place.
Well, you make a fair point, I like to have it appear in the html docs, but obviously no one is going to build the docs to review a patch. I may look into ways to get both birds with a stone.
Thanks,
Gabriele
Peter Zijlstra
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
Quoted 7 lines · Gabriele Monaco
Quoted 3 lines · Peter Zijlstra
So mostly I flat out out ignore partial series. It means I have to go dig around to figure out the whole picture, and anything that requires extra effort goes on the 'later' pile, and you know where that lives.
Alright, I guess I'm going to have to fix my
to_cmdscript.
Quoted 7 lines
Quoted 4 lines
Now, as to 3,4; I'm confused. If I search 'enqueue' I see there is a tracepoint attach thingy in the .c file, but I don't see the corresponding bits in the .dot file. And per my understanding the .c thing is an artifact of the .dot file.
Yes but only partially. There isn't always a 1-1 mapping with model events and tracepoints.
So the .c files are no longer an artifact? That seems unfortunate. I thought the .dot file was fully descriptive and the .c file was fully generated by dot2c.
If we cannot fully express the automaton in .dot, we should look at extending the 'format' and teach dot2c new tricks.
Quoted 11 lines
Throttle uses
handle_sched_enqueue()for one case ofdl_defer_arm, representing a fair task running not boosted, in the enqueue case, because it was running with another scheduler.
Boost useshandle_sched_dequeue()in a similar fashion to describe fair tasks that stop running on the fair runqueue (but may continue on another runqueue).In both cases I'm reusing an event that can be triggered from other tracepoints too, ideally to keep the model simpler.
Then it uses
handle_sched_enqueue()for dl_server_resume[_throttled]. They are both plain enqueues, in fact, so I could rename them to show what they are.
I'm not sure I'm following. Will you be in Prague next week?
Quoted 7 lines
Quoted 3 lines
Also, IMO it would be *much* preferred if the .rst file would not exist. Just have the graph-easy and the description as a comment in the .dot file. Then you have the whole thing in one *readable* place.
Well, you make a fair point, I like to have it appear in the html docs, but obviously no one is going to build the docs to review a patch. I may look into ways to get both birds with a stone.
So personally I have 0 interest or use for html. Mail is text, code is text, we use a text editor (neovim is my current poison of choice). Nowhere is there html. So then having to look at rst is just crap. rst gets in the way of actually reading the thing. All down-sides, no up-sides.
Gabriele Monaco
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
Il 2 ottobre 2026 19:18:42 UTC, Peter Zijlstra <[email protected]> ha scritto:
Quoted 16 lines · Gabriele Monaco
Quoted 7 lines · Peter Zijlstra
Quoted 3 lines
So mostly I flat out out ignore partial series. It means I have to go dig around to figure out the whole picture, and anything that requires extra effort goes on the 'later' pile, and you know where that lives.
Alright, I guess I'm going to have to fix my
to_cmdscript.Quoted 7 lines
Quoted 4 lines
Now, as to 3,4; I'm confused. If I search 'enqueue' I see there is a tracepoint attach thingy in the .c file, but I don't see the corresponding bits in the .dot file. And per my understanding the .c thing is an artifact of the .dot file.
Yes but only partially. There isn't always a 1-1 mapping with model events and tracepoints.
Quoted 6 lines
So the .c files are no longer an artifact? That seems unfortunate. I thought the .dot file was fully descriptive and the .c file was fully generated by dot2c.
If we cannot fully express the automaton in .dot, we should look at extending the 'format' and teach dot2c new tricks.
The linking between events and tracepoint has always been manual, but yeah, it would be nice to describe the whole thing in the specification.
Though that would require quite a bit of work, deadline and LTL monitors have some more complicated mapping.
Quoted 7 lines
Quoted 7 lines
Throttle uses
handle_sched_enqueue()for one case ofdl_defer_arm, representing a fair task running not boosted, in the enqueue case, because it was running with another scheduler.
Boost useshandle_sched_dequeue()in a similar fashion to describe fair tasks that stop running on the fair runqueue (but may continue on another runqueue).
Quoted 8 lines
Quoted 5 lines
In both cases I'm reusing an event that can be triggered from other tracepoints too, ideally to keep the model simpler.
Then it uses
handle_sched_enqueue()for dl_server_resume[_throttled]. They are both plain enqueues, in fact, so I could rename them to show what they are.I'm not sure I'm following. Will you be in Prague next week?
Yes I'll be there. We can definitely discuss this better.
Thanks,
Gabriele
Quoted 14 lines
Quoted 7 lines
Quoted 3 lines
Also, IMO it would be *much* preferred if the .rst file would not exist. Just have the graph-easy and the description as a comment in the .dot file. Then you have the whole thing in one *readable* place.
Well, you make a fair point, I like to have it appear in the html docs, but obviously no one is going to build the docs to review a patch. I may look into ways to get both birds with a stone.
So personally I have 0 interest or use for html. Mail is text, code is text, we use a text editor (neovim is my current poison of choice). Nowhere is there html. So then having to look at rst is just crap. rst gets in the way of actually reading the thing. All down-sides, no up-sides.
Steven Rostedt
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
In reply to Peter ZijlstraQuoted 5 lines · On Fri, 2 Oct 2026 21:18:42 +0200 Peter Zijlstra <[email protected]> wrote:
So personally I have 0 interest or use for html. Mail is text, code is text, we use a text editor (neovim is my current poison of choice). Nowhere is there html. So then having to look at rst is just crap. rst gets in the way of actually reading the thing. All down-sides, no up-sides.
This is specifically your opinion. I really liked text files, but I have fallen to the dark side and found reading the Documentation directory from docs.kernel.org so much nicer than reading the text files directly.
I think most people feel the same.
As for Cc'ing entire patches, if I get a patch series Cc'd to me in my inbox and there's one or two patches that are supposed to be for me, I ignore the entire thing. I'm not going to waste my time trying to figure out why I was Cc'd, unless it is obvious in the cover letter. Which in most cases it is not.
If I get Cc'd on one patch in a series and I want to see the entire thing, lore is beautiful. If you don't want to look at a web page then b4 is your friend. But since there's maintainers that want everything, I'm constantly Cc'd for 23 patches where I need to see one. Hence, I hit delete on the entire thing and will not ever see what I was Cc'd for. Why should I waste my time on that? The burden is much higher to read 23 patches to find the one you are looking for than when wanting to see all patches to open a web browser or just using b4. And no, seldom is the subject line obvious to why I was Cc'd. I have to actually read what files each patch touches to figure out if it's applicable to me or not. I've done that too many times and don't have the time to waste on that anymore.
-- Steve
Peter Zijlstra
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
Quoted 9 lines · Steven Rostedt
Quoted 5 lines · On Fri, 2 Oct 2026 21:18:42 +0200 Peter Zijlstra <[email protected]> wrote:
So personally I have 0 interest or use for html. Mail is text, code is text, we use a text editor (neovim is my current poison of choice). Nowhere is there html. So then having to look at rst is just crap. rst gets in the way of actually reading the thing. All down-sides, no up-sides.
Quoted 3 lines
This is specifically your opinion. I really liked text files, but I have fallen to the dark side and found reading the Documentation directory from docs.kernel.org so much nicer than reading the text files directly.
For me it means having to use a mouse. It means having to deal with dumb shit like non monospace fonts and endless annoying stuff like that.
I know I'm a minority, but the web *SUCKS*. There are no wins for me.
Steven Rostedt
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
In reply to Peter ZijlstraQuoted 1 line · On Fri, 2 Oct 2026 12:29:39 +0200 Peter Zijlstra <[email protected]> wrote:
...insert rant on what a piece of shit rst is here...
Rant from grumpy old guy that doesn't like the new stuff ;-)
-- Steve
Peter Zijlstra
maintainerRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
Quoted 6 lines · Steven Rostedt
Quoted 1 line · On Fri, 2 Oct 2026 12:29:39 +0200 Peter Zijlstra <[email protected]> wrote:
...insert rant on what a piece of shit rst is here...
Rant from grumpy old guy that doesn't like the new stuff ;-)
Absolutely. But very much also that the new stuff isn't actually making my life better. While at the same time it *IS* making it worse.
I'm not hating on this just because things change, but because the change is getting in the way of things.
[email protected]
AI reviewRe: [PATCH v2 01/15] sched: Add task enqueue/dequeue trace points
In reply to Gabriele MonacoTL;DR: Commit message only: the changelog just restates the diff and doesn't explain why the new sched_enqueue/sched_dequeue tracepoints are needed, a question Peter Zijlstra raised on v2 that went…
Quoted 1 line
sched: Add task enqueue/dequeue trace points
TL;DR: Commit message only: the changelog just restates the diff and doesn't explain why the new sched_enqueue/sched_dequeue tracepoints are needed, a question Peter Zijlstra raised on v2 that went unanswered.
Quoted 9 lines
sched: Add task enqueue/dequeue trace points
Add trace points into
enqueue_task()anddequeue_task().Signed-off-by Nam Cao <[email protected]>Suggested-by Peter Zijlstra <[email protected]>Reviewed-by K Prateek Nayak <[email protected]>Co-developed-by Gabriele Monaco <[email protected]>Signed-off-by Gabriele Monaco <[email protected]>
Peter Zijlstra asked about the rationale for these tracepoints in the v2 thread:
"As is I'm clueless as to why we want this, since the Changelog also offers none."
https://lore.kernel.org/all/[email protected]/
No reply was found in the archive, and the changelog above still consists of the single sentence restating the diff.
Could the changelog explain why the sched_enqueue and sched_dequeue tracepoints are needed?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Gabriele Monaco
maintainerPATCH v2 2/15 tools/rv: Skip empty pid error in selftest if command failed
In reply to Gabriele MonacoSome rv userspace selftests rely on the pid of the rv process to match with the output and fail prematurely in case the pid was not found. If the rv process failed, however, it's likely it will terminate before catching the pid, and the test reports empty pid ignoring the error that caused the process to fail.
Report empty pid only when the rv process succeeds (exit code not what was expected) and continue showing exit code and output otherwise.
--- tools/verification/tests/engine.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-)
tools/verification/tests/engine.sh +3 -2
@@ -60,8 +60,9 @@ _check() { failbuf='' fail=0 - # Suppress any other error if a needed pid is empty - if [ -z "$pid" ] && grep -q "\$pid" <<< "$patterns"; then + # Suppress any other error if a needed pid is empty and there was no other error + if [ -z "$pid" ] && grep -q "\$pid" <<< "$patterns" \ + && [ $exitcode -eq "$expected_exitcode" ]; then result='' failure "# Empty pid for $command" return 1
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 02/15] tools/rv: Skip empty pid error in selftest if command failed
TL;DR: Commit message only: the parenthetical "(exit code not what was expected)" looks inverted relative to the code, which reports the empty pid only when the exit code matches the expected one.…
Quoted 1 line
tools/rv: Skip empty pid error in selftest if command failed
TL;DR: Commit message only: the parenthetical "(exit code not what was expected)" looks inverted relative to the code, which reports the empty pid only when the exit code matches the expected one. No code bug.
Quoted 8 lines
tools/rv: Skip empty pid error in selftest if command failedSome rv userspace selftests rely on the pid of the rv process to match with the output and fail prematurely in case the pid was not found. If the rv process failed, however, it's likely it will terminate before catching the pid, and the test reports empty pid ignoring the error that caused the process to fail.
Quoted 4 lines
Report empty pid only when the rv process succeeds (exit code not what was expected) and continue showing exit code and output otherwise.
Signed-off-by Gabriele Monaco <[email protected]>
This isn't a bug in the code, but the parenthetical in the commit message looks inverted. Is "(exit code not what was expected)" meant to read "(exit code is what was expected)"?
The patch adds this condition to the empty-pid check in _check():
if [ -z "$pid" ] && grep -q "\$pid" <<< "$patterns" \
&& [ $exitcode -eq "$expected_exitcode" ]; then
result=''
failure "# Empty pid for $command"
return 1
fiso "# Empty pid for $command" is reported only when the exit code equals the expected exit code. When the exit code differs, the check is skipped and the "# Expected exit code" failure is still recorded along with the output.
As written, the message describes the pre-patch behaviour that the change removes. Something like this would match the code:
Report empty pid only when the rv process succeeds (exit code is what was expected) and continue showing exit code and output otherwise.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Gabriele Monaco
maintainerPATCH v2 3/15 Refactor da_trace() functions to get strings internally
In reply to Gabriele MonacoThe da_trace_event() and da_trace_error() functions are currently called with strings and the callers are converting the state/event enums to the corresponding string representation.
This is unnecessary and is problematic if an alternative implementation is needed (e.g. BPF without using strings).
Change the functions to accept enums and pass the string representations to the tracepoints only internally.
--- include/rv/da_monitor.h | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-)
include/rv/da_monitor.h +22 -18
@@ -633,19 +633,22 @@ static inline void da_monitor_destroy(void)*/ static inline void da_trace_event (struct da_monitor *da_mon, -char *curr_state,char *event, -char *next_state,bool is_final, +enum states curr_state,enum events event, +enum states next_state,da_id_type id) { -CONCATENATE (trace_event_,MONITOR_NAME )(curr_state, event, next_state, - is_final); +CONCATENATE (trace_event_,MONITOR_NAME )(model_get_state_name (curr_state), +model_get_event_name (event), +model_get_state_name (next_state), +model_is_final_state (next_state)); }static inline void da_trace_error (struct da_monitor *da_mon, -char *curr_state,char *event, +enum states curr_state,enum events event,da_id_type id) { -CONCATENATE (trace_error_,MONITOR_NAME )(curr_state, event); +CONCATENATE (trace_error_,MONITOR_NAME )(model_get_state_name (curr_state), +model_get_event_name (event)); }/*
@@ -662,19 +665,24 @@ static inline da_id_type da_get_id(struct da_monitor *da_mon)*/ static inline void da_trace_event (struct da_monitor *da_mon, -char *curr_state,char *event, -char *next_state,bool is_final, +enum states curr_state,enum events event, +enum states next_state,da_id_type id) { -CONCATENATE (trace_event_,MONITOR_NAME )(id, curr_state, event, - next_state, is_final); +CONCATENATE (trace_event_,MONITOR_NAME )(id, +model_get_state_name (curr_state), +model_get_event_name (event), +model_get_state_name (next_state), +model_is_final_state (next_state)); }static inline void da_trace_error (struct da_monitor *da_mon, -char *curr_state,char *event, +enum states curr_state,enum events event,da_id_type id) { -CONCATENATE (trace_error_,MONITOR_NAME )(id, curr_state, event); +CONCATENATE (trace_error_,MONITOR_NAME )(id, +model_get_state_name (curr_state), +model_get_event_name (event)); }#endif /* RV_MON_TYPE */
@@ -695,17 +703,13 @@ static inline bool da_event(struct da_monitor *da_mon, enum events event, da_id_ next_state =model_get_next_state (curr_state, event);if (next_state ==INVALID_STATE ) {react (curr_state, event); -da_trace_error (da_mon,model_get_state_name (curr_state), -model_get_event_name (event), id); +da_trace_error (da_mon, curr_state, event, id);return false; }if (likely (try_cmpxchg (&da_mon->curr_state, &curr_state, next_state))) {if (!da_monitor_event_hook (da_mon, curr_state, event, next_state, id))return false; -da_trace_event (da_mon,model_get_state_name (curr_state), -model_get_event_name (event), -model_get_state_name (next_state), -model_is_final_state (next_state), id); +da_trace_event (da_mon, curr_state, event, next_state, id);return true; } }
Signature · 1 line
2.55.0
Gabriele Monaco
maintainerPATCH v2 4/15 Cast result of model_get_*_name()
In reply to Gabriele MonacoFunctions like model_get_event_name() and model_get_state_name() are shared with BPF monitors, however those programs don't play nice with string pointers without fixed length and the event_name and state_name arrays need to be defined differently. This gets the compiler to notice those are const char and the above function discard the const qualifier.
Drop the warning by casting the result to (char *). Note, a cleaner solution would require to modify all callers, but that would require changing every single monitor's tracepoint and the advantage is minimal.
--- include/rv/automata.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-)
include/rv/automata.h +2 -2
@@ -27,7 +27,7 @@ static char *model_get_state_name(enum states state)if ((state <0 ) || (state >=STATE_MAX ))return "INVALID" ; -return RV_AUTOMATON_NAME .state_names[state]; +return (char *)RV_AUTOMATON_NAME .state_names[state]; }/*
@@ -38,7 +38,7 @@ static char *model_get_event_name(enum events event)if ((event <0 ) || (event >=EVENT_MAX ))return "INVALID" ; -return RV_AUTOMATON_NAME .event_names[event]; +return (char *)RV_AUTOMATON_NAME .event_names[event]; }/*
Signature · 1 line
2.55.0
Re: [PATCH v2 04/15] rv: Cast result of model_get_*_name()
Quoted 9 lines · Gabriele Monaco
Functions like
model_get_event_name()andmodel_get_state_name()are shared with BPF monitors, however those programs don't play nice with string pointers without fixed length and theevent_nameandstate_namearrays need to be defined differently. This gets the compiler to notice those are const char and the above function discard the const qualifier.Drop the warning by casting the result to (char *). Note, a cleaner solution would require to modify all callers, but that would require changing every single monitor's tracepoint and the advantage is minimal.
I prefer the cleaner solution. Just mass replace "char *" with "const char *", and manually fix up a few errors and we are done.
include/rv/automata.h +2 -2
@@ -22,7 +22,7 @@/* * model_get_state_name - return the (string) name of the given state */ -static char *model_get_state_name (enum states state) +static const char *model_get_state_name (enum states state) {if ((state <0 ) || (state >=STATE_MAX ))return "INVALID" ;
@@ -33,7 +33,7 @@ static char *model_get_state_name(enum states state)/* * model_get_event_name - return the (string) name of the given event */ -static char *model_get_event_name (enum events event) +static const char *model_get_event_name (enum events event) {if ((event <0 ) || (event >=EVENT_MAX ))return "INVALID" ;
include/rv/da_monitor.h +6 -6
@@ -633,8 +633,8 @@ static inline void da_monitor_destroy(void)*/ static inline void da_trace_event (struct da_monitor *da_mon, -char *curr_state,char *event, -char *next_state,bool is_final, +const char *curr_state,const char *event, +const char *next_state,bool is_final,da_id_type id) { CONCATENATE(trace_event_, MONITOR_NAME)(curr_state, event, next_state,
@@ -642,7 +642,7 @@ static inline void da_trace_event(struct da_monitor *da_mon, }static inline void da_trace_error (struct da_monitor *da_mon, -char *curr_state,char *event, +const char *curr_state,const char *event,da_id_type id) {CONCATENATE (trace_error_,MONITOR_NAME )(curr_state, event);
@@ -662,8 +662,8 @@ static inline da_id_type da_get_id(struct da_monitor *da_mon)*/ static inline void da_trace_event (struct da_monitor *da_mon, -char *curr_state,char *event, -char *next_state,bool is_final, +const char *curr_state,const char *event, +const char *next_state,bool is_final,da_id_type id) { CONCATENATE(trace_event_, MONITOR_NAME)(id, curr_state, event,
@@ -671,7 +671,7 @@ static inline void da_trace_event(struct da_monitor *da_mon, }static inline void da_trace_error (struct da_monitor *da_mon, -char *curr_state,char *event, +const char *curr_state,const char *event,da_id_type id) {CONCATENATE (trace_error_,MONITOR_NAME )(id, curr_state, event);
include/rv/ha_monitor.h +5 -5
@@ -87,7 +87,7 @@ _Static_assert(offsetof(struct ha_monitor, da_mon) == 0,* environment constraint is false. This function can be called also with no * event from a timer (state constraints only). */ -static void ha_react (enum states curr_state,enum events event,char *env) +static void ha_react (enum states curr_state,enum events event,const char *env) { rv_react(&rv_this, "rv: monitor %s does not allow event %s on state %s with env %s\n",
@@ -98,13 +98,13 @@ static void ha_react(enum states curr_state, enum events event, char *env)#else /* CONFIG_RV_REACTOR */ -static void ha_react (enum states curr_state,enum events event,char *env) { } +static void ha_react (enum states curr_state,enum events event,const char *env) { }#endif /* * model_get_state_name - return the (string) name of the given state */ -static char *model_get_env_name (enum envs env) +static const char *model_get_env_name (enum envs env) {if ((env <0 ) || (env >=ENV_MAX ))return "INVALID" ;
@@ -227,7 +227,7 @@ static inline void ha_get_env_string(struct seq_buf *s,#if RV_MON_TYPE ==RV_MON_GLOBAL ||RV_MON_TYPE ==RV_MON_PER_CPU static inline void ha_trace_error_env (struct ha_monitor *ha_mon, -char *curr_state,char *event,char *env, +const char *curr_state,const char *event,const char *env,da_id_type id) {CONCATENATE (trace_error_env_,MONITOR_NAME )(curr_state, event, env);
@@ -237,7 +237,7 @@ static inline void ha_trace_error_env(struct ha_monitor *ha_mon,#define ha_get_target (ha_mon) da_get_target(&ha_mon->da_mon)static inline void ha_trace_error_env (struct ha_monitor *ha_mon, -char *curr_state,char *event,char *env, +const char *curr_state,const char *event,const char *env,da_id_type id) {CONCATENATE (trace_error_env_,MONITOR_NAME )(id, curr_state, event, env);
kernel/trace/rv/monitors/nomiss/nomiss.h +3 -3
@@ -41,9 +41,9 @@ _Static_assert(env_max_stored_nomiss <= MAX_HA_ENV_LEN, "Not enough slots");#define HA_CLK_NS struct automaton_nomiss { -char *state_names[state_max_nomiss]; -char *event_names[event_max_nomiss]; -char *env_names[env_max_nomiss]; +const char *state_names[state_max_nomiss]; +const char *event_names[event_max_nomiss]; +const char *env_names[env_max_nomiss];unsigned char function[state_max_nomiss][event_max_nomiss];unsigned char initial_state;bool final_states[state_max_nomiss];
kernel/trace/rv/monitors/nomiss/nomiss_trace.h +3 -3
@@ -6,14 +6,14 @@#ifdef CONFIG_RV_MON_NOMISS DEFINE_EVENT (event_da_monitor_id, event_nomiss, - TP_PROTO(int id, char *state, char *event, char *next_state, bool final_state), + TP_PROTO(int id, const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (id, state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor_id, error_nomiss, - TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),TP_ARGS (id, state, event));DEFINE_EVENT (error_env_da_monitor_id, error_env_nomiss, - TP_PROTO(int id, char *state, char *event, char *env), + TP_PROTO(int id, const char *state, const char *event, const char *env),TP_ARGS (id, state, event, env));#endif /* CONFIG_RV_MON_NOMISS */
kernel/trace/rv/monitors/nrp/nrp.h +2 -2
@@ -26,8 +26,8 @@ enum events_nrp { };struct automaton_nrp { -char *state_names[state_max_nrp]; -char *event_names[event_max_nrp]; +const char *state_names[state_max_nrp]; +const char *event_names[event_max_nrp];unsigned char function[state_max_nrp][event_max_nrp];unsigned char initial_state;bool final_states[state_max_nrp];
kernel/trace/rv/monitors/nrp/nrp_trace.h +2 -2
@@ -6,10 +6,10 @@#ifdef CONFIG_RV_MON_NRP DEFINE_EVENT (event_da_monitor_id, event_nrp, - TP_PROTO(int id, char *state, char *event, char *next_state, bool final_state), + TP_PROTO(int id, const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (id, state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor_id, error_nrp, - TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),TP_ARGS (id, state, event));#endif /* CONFIG_RV_MON_NRP */
kernel/trace/rv/monitors/opid/opid.h +3 -3
@@ -30,9 +30,9 @@ enum envs_opid {_Static_assert (env_max_stored_opid <=MAX_HA_ENV_LEN ,"Not enough slots" );struct automaton_opid { -char *state_names[state_max_opid]; -char *event_names[event_max_opid]; -char *env_names[env_max_opid]; +const char *state_names[state_max_opid]; +const char *event_names[event_max_opid]; +const char *env_names[env_max_opid];unsigned char function[state_max_opid][event_max_opid];unsigned char initial_state;bool final_states[state_max_opid];
kernel/trace/rv/monitors/opid/opid_trace.h +3 -3
@@ -6,14 +6,14 @@#ifdef CONFIG_RV_MON_OPID DEFINE_EVENT (event_da_monitor, event_opid, - TP_PROTO(char *state, char *event, char *next_state, bool final_state), + TP_PROTO(const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor, error_opid, -TP_PROTO (char *state, char *event), + TP_PROTO(const char *state, const char *event),TP_ARGS (state, event));DEFINE_EVENT (error_env_da_monitor, error_env_opid, -TP_PROTO (char *state, char *event, char *env), + TP_PROTO(const char *state, const char *event, const char *env),TP_ARGS (state, event, env));#endif /* CONFIG_RV_MON_OPID */
kernel/trace/rv/monitors/pagefault/pagefault_trace.h +1 -1
@@ -6,7 +6,7 @@#ifdef CONFIG_RV_MON_PAGEFAULT DEFINE_EVENT (event_ltl_monitor_id, event_pagefault, - TP_PROTO(struct task_struct *task, char *states, char *atoms, char *next), + TP_PROTO(struct task_struct *task, const char *states, const char *atoms, const char *next),TP_ARGS (task, states, atoms, next)); DEFINE_EVENT(error_ltl_monitor_id, error_pagefault, TP_PROTO(struct task_struct *task),
kernel/trace/rv/monitors/sco/sco.h +2 -2
@@ -23,8 +23,8 @@ enum events_sco { };struct automaton_sco { -char *state_names[state_max_sco]; -char *event_names[event_max_sco]; +const char *state_names[state_max_sco]; +const char *event_names[event_max_sco];unsigned char function[state_max_sco][event_max_sco];unsigned char initial_state;bool final_states[state_max_sco];
kernel/trace/rv/monitors/sco/sco_trace.h +2 -2
@@ -6,10 +6,10 @@#ifdef CONFIG_RV_MON_SCO DEFINE_EVENT (event_da_monitor, event_sco, - TP_PROTO(char *state, char *event, char *next_state, bool final_state), + TP_PROTO(const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor, error_sco, -TP_PROTO (char *state, char *event), + TP_PROTO(const char *state, const char *event),TP_ARGS (state, event));#endif /* CONFIG_RV_MON_SCO */
kernel/trace/rv/monitors/scpd/scpd.h +2 -2
@@ -24,8 +24,8 @@ enum events_scpd { };struct automaton_scpd { -char *state_names[state_max_scpd]; -char *event_names[event_max_scpd]; +const char *state_names[state_max_scpd]; +const char *event_names[event_max_scpd];unsigned char function[state_max_scpd][event_max_scpd];unsigned char initial_state;bool final_states[state_max_scpd];
kernel/trace/rv/monitors/scpd/scpd_trace.h +2 -2
@@ -6,10 +6,10 @@#ifdef CONFIG_RV_MON_SCPD DEFINE_EVENT (event_da_monitor, event_scpd, - TP_PROTO(char *state, char *event, char *next_state, bool final_state), + TP_PROTO(const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor, error_scpd, -TP_PROTO (char *state, char *event), + TP_PROTO(const char *state, const char *event),TP_ARGS (state, event));#endif /* CONFIG_RV_MON_SCPD */
kernel/trace/rv/monitors/sleep/sleep_trace.h +1 -1
@@ -6,7 +6,7 @@#ifdef CONFIG_RV_MON_SLEEP DEFINE_EVENT (event_ltl_monitor_id, event_sleep, - TP_PROTO(struct task_struct *task, char *states, char *atoms, char *next), + TP_PROTO(struct task_struct *task, const char *states, const char *atoms, const char *next),TP_ARGS (task, states, atoms, next)); DEFINE_EVENT(error_ltl_monitor_id, error_sleep, TP_PROTO(struct task_struct *task),
kernel/trace/rv/monitors/snep/snep.h +2 -2
@@ -24,8 +24,8 @@ enum events_snep { };struct automaton_snep { -char *state_names[state_max_snep]; -char *event_names[event_max_snep]; +const char *state_names[state_max_snep]; +const char *event_names[event_max_snep];unsigned char function[state_max_snep][event_max_snep];unsigned char initial_state;bool final_states[state_max_snep];
kernel/trace/rv/monitors/snep/snep_trace.h +2 -2
@@ -6,10 +6,10 @@#ifdef CONFIG_RV_MON_SNEP DEFINE_EVENT (event_da_monitor, event_snep, - TP_PROTO(char *state, char *event, char *next_state, bool final_state), + TP_PROTO(const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor, error_snep, -TP_PROTO (char *state, char *event), + TP_PROTO(const char *state, const char *event),TP_ARGS (state, event));#endif /* CONFIG_RV_MON_SNEP */
kernel/trace/rv/monitors/snroc/snroc.h +2 -2
@@ -23,8 +23,8 @@ enum events_snroc { };struct automaton_snroc { -char *state_names[state_max_snroc]; -char *event_names[event_max_snroc]; +const char *state_names[state_max_snroc]; +const char *event_names[event_max_snroc];unsigned char function[state_max_snroc][event_max_snroc];unsigned char initial_state;bool final_states[state_max_snroc];
kernel/trace/rv/monitors/snroc/snroc_trace.h +2 -2
@@ -6,10 +6,10 @@#ifdef CONFIG_RV_MON_SNROC DEFINE_EVENT (event_da_monitor_id, event_snroc, - TP_PROTO(int id, char *state, char *event, char *next_state, bool final_state), + TP_PROTO(int id, const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (id, state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor_id, error_snroc, - TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),TP_ARGS (id, state, event));#endif /* CONFIG_RV_MON_SNROC */
kernel/trace/rv/monitors/sssw/sssw.h +2 -2
@@ -31,8 +31,8 @@ enum events_sssw { };struct automaton_sssw { -char *state_names[state_max_sssw]; -char *event_names[event_max_sssw]; +const char *state_names[state_max_sssw]; +const char *event_names[event_max_sssw];unsigned char function[state_max_sssw][event_max_sssw];unsigned char initial_state;bool final_states[state_max_sssw];
kernel/trace/rv/monitors/sssw/sssw_trace.h +2 -2
@@ -6,10 +6,10 @@#ifdef CONFIG_RV_MON_SSSW DEFINE_EVENT (event_da_monitor_id, event_sssw, - TP_PROTO(int id, char *state, char *event, char *next_state, bool final_state), + TP_PROTO(int id, const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (id, state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor_id, error_sssw, - TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),TP_ARGS (id, state, event));#endif /* CONFIG_RV_MON_SSSW */
kernel/trace/rv/monitors/stall/stall.h +3 -3
@@ -33,9 +33,9 @@ enum envs_stall {_Static_assert (env_max_stored_stall <=MAX_HA_ENV_LEN ,"Not enough slots" );struct automaton_stall { -char *state_names[state_max_stall]; -char *event_names[event_max_stall]; -char *env_names[env_max_stall]; +const char *state_names[state_max_stall]; +const char *event_names[event_max_stall]; +const char *env_names[env_max_stall];unsigned char function[state_max_stall][event_max_stall];unsigned char initial_state;bool final_states[state_max_stall];
kernel/trace/rv/monitors/stall/stall_trace.h +3 -3
@@ -6,14 +6,14 @@#ifdef CONFIG_RV_MON_STALL DEFINE_EVENT (event_da_monitor_id, event_stall, - TP_PROTO(int id, char *state, char *event, char *next_state, bool final_state), + TP_PROTO(int id, const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (id, state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor_id, error_stall, - TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),TP_ARGS (id, state, event));DEFINE_EVENT (error_env_da_monitor_id, error_env_stall, - TP_PROTO(int id, char *state, char *event, char *env), + TP_PROTO(int id, const char *state, const char *event, const char *env),TP_ARGS (id, state, event, env));#endif /* CONFIG_RV_MON_STALL */
kernel/trace/rv/monitors/sts/sts.h +2 -2
@@ -31,8 +31,8 @@ enum events_sts { };struct automaton_sts { -char *state_names[state_max_sts]; -char *event_names[event_max_sts]; +const char *state_names[state_max_sts]; +const char *event_names[event_max_sts];unsigned char function[state_max_sts][event_max_sts];unsigned char initial_state;bool final_states[state_max_sts];
kernel/trace/rv/monitors/sts/sts_trace.h +2 -2
@@ -6,10 +6,10 @@#ifdef CONFIG_RV_MON_STS DEFINE_EVENT (event_da_monitor, event_sts, - TP_PROTO(char *state, char *event, char *next_state, bool final_state), + TP_PROTO(const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor, error_sts, -TP_PROTO (char *state, char *event), + TP_PROTO(const char *state, const char *event),TP_ARGS (state, event));#endif /* CONFIG_RV_MON_STS */
kernel/trace/rv/monitors/wakeup/wakeup_trace.h +1 -1
@@ -6,7 +6,7 @@#ifdef CONFIG_RV_MON_WAKEUP DEFINE_EVENT (event_ltl_monitor_id, event_wakeup, - TP_PROTO(struct task_struct *task, char *states, char *atoms, char *next), + TP_PROTO(struct task_struct *task, const char *states, const char *atoms, const char *next),TP_ARGS (task, states, atoms, next)); DEFINE_EVENT(error_ltl_monitor_id, error_wakeup, TP_PROTO(struct task_struct *task),
kernel/trace/rv/monitors/wip/wip.h +2 -2
@@ -23,8 +23,8 @@ enum events_wip { };struct automaton_wip { -char *state_names[state_max_wip]; -char *event_names[event_max_wip]; +const char *state_names[state_max_wip]; +const char *event_names[event_max_wip];unsigned char function[state_max_wip][event_max_wip];unsigned char initial_state;bool final_states[state_max_wip];
kernel/trace/rv/monitors/wip/wip_trace.h +2 -2
@@ -6,10 +6,10 @@#ifdef CONFIG_RV_MON_WIP DEFINE_EVENT (event_da_monitor, event_wip, - TP_PROTO(char *state, char *event, char *next_state, bool final_state), + TP_PROTO(const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor, error_wip, -TP_PROTO (char *state, char *event), + TP_PROTO(const char *state, const char *event),TP_ARGS (state, event));#endif /* CONFIG_RV_MON_WIP */
kernel/trace/rv/monitors/wwnr/wwnr.h +2 -2
@@ -23,8 +23,8 @@ enum events_wwnr { };struct automaton_wwnr { -char *state_names[state_max_wwnr]; -char *event_names[event_max_wwnr]; +const char *state_names[state_max_wwnr]; +const char *event_names[event_max_wwnr];unsigned char function[state_max_wwnr][event_max_wwnr];unsigned char initial_state;bool final_states[state_max_wwnr];
kernel/trace/rv/monitors/wwnr/wwnr_trace.h +2 -2
@@ -7,10 +7,10 @@#ifdef CONFIG_RV_MON_WWNR /* id is the pid of the task */ DEFINE_EVENT (event_da_monitor_id, event_wwnr, - TP_PROTO(int id, char *state, char *event, char *next_state, bool final_state), + TP_PROTO(int id, const char *state, const char *event, const char *next_state, bool final_state),TP_ARGS (id, state, event, next_state, final_state));DEFINE_EVENT (error_da_monitor_id, error_wwnr, - TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),TP_ARGS (id, state, event));#endif /* CONFIG_RV_MON_WWNR */
kernel/trace/rv/rv_monitors_test.c +1 -1
@@ -21,7 +21,7 @@static struct rv_kunit_ctx *active_ctx; __printf(1, 0) -static void rv_kunit_mock_react (const char *msg,va_list args) +static void rv_kunit_mock_react (const const char *msg,va_list args) {if (active_ctx) ++active_ctx->reactions;
kernel/trace/rv/rv_reactors.c +1 -1
@@ -71,7 +71,7 @@*/ static LIST_HEAD (rv_reactors_list); -static struct rv_reactor *get_reactor_rdef_by_name (char *name) +static struct rv_reactor *get_reactor_rdef_by_name (const char *name) {struct rv_reactor *r;
kernel/trace/rv/rv_trace.h +8 -8
@@ -11,7 +11,7 @@#ifdef CONFIG_DA_MON_EVENTS_IMPLICIT DECLARE_EVENT_CLASS(event_da_monitor, - TP_PROTO(char *state, char *event, char *next_state, bool final_state), + TP_PROTO(const char *state, const char *event, const char *next_state, bool final_state), TP_ARGS(state, event, next_state, final_state),
@@ -38,7 +38,7 @@ DECLARE_EVENT_CLASS(event_da_monitor, DECLARE_EVENT_CLASS(error_da_monitor, - TP_PROTO(char *state, char *event), + TP_PROTO(const char *state, const char *event), TP_ARGS(state, event),
@@ -68,7 +68,7 @@ DECLARE_EVENT_CLASS(error_da_monitor,/* For simplicity this class is marked as DA although relevant only for HA */ DECLARE_EVENT_CLASS(error_env_da_monitor, - TP_PROTO(char *state, char *event, char *env), + TP_PROTO(const char *state, const char *event, const char *env), TP_ARGS(state, event, env),
@@ -100,7 +100,7 @@ DECLARE_EVENT_CLASS(error_env_da_monitor,#ifdef CONFIG_DA_MON_EVENTS_ID DECLARE_EVENT_CLASS(event_da_monitor_id, - TP_PROTO(int id, char *state, char *event, char *next_state, bool final_state), + TP_PROTO(int id, const char *state, const char *event, const char *next_state, bool final_state), TP_ARGS(id, state, event, next_state, final_state),
@@ -130,7 +130,7 @@ DECLARE_EVENT_CLASS(event_da_monitor_id, DECLARE_EVENT_CLASS(error_da_monitor_id, - TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event), TP_ARGS(id, state, event),
@@ -162,7 +162,7 @@ DECLARE_EVENT_CLASS(error_da_monitor_id,/* For simplicity this class is marked as DA although relevant only for HA */ DECLARE_EVENT_CLASS(error_env_da_monitor_id, - TP_PROTO(int id, char *state, char *event, char *env), + TP_PROTO(int id, const char *state, const char *event, const char *env), TP_ARGS(id, state, event, env),
@@ -197,7 +197,7 @@ DECLARE_EVENT_CLASS(error_env_da_monitor_id,#ifdef CONFIG_LTL_MON_EVENTS_ID DECLARE_EVENT_CLASS(event_ltl_monitor_id, - TP_PROTO(struct task_struct *task, char *states, char *atoms, char *next), + TP_PROTO(struct task_struct *task, const char *states, const char *atoms, const char *next), TP_ARGS(task, states, atoms, next),
@@ -249,7 +249,7 @@ DECLARE_EVENT_CLASS(error_ltl_monitor_id,/* Tracepoint useful for monitors development, currenly only used in DA */ TRACE_EVENT(rv_retries_error, - TP_PROTO(char *name, char *event), + TP_PROTO(const char *name, const char *event), TP_ARGS(name, event),
Gabriele Monaco
maintainerRe: [PATCH v2 04/15] rv: Cast result of model_get_*_name()
Quoted 8 lines · Nam Cao
Quoted 6 lines · Gabriele Monaco
Functions like
model_get_event_name()andmodel_get_state_name()are shared with BPF monitors, however those programs don't play nice with string pointers without fixed length and theevent_nameandstate_namearrays need to be defined differently. This gets the compiler to notice those are const char and the above function discard the const qualifier.
Quoted 6 lines
Quoted 3 lines
Drop the warning by casting the result to (char *). Note, a cleaner solution would require to modify all callers, but that would require changing every single monitor's tracepoint and the advantage is minimal.
I prefer the cleaner solution. Just mass replace "char *" with "const char *", and manually fix up a few errors and we are done.
Right, no excuse for being lazy in the era of LLMs..
Thanks for the patch,
Gabriele
Quoted 743 lines
include/rv/automata.h +2
-2@@ -22,7 +22,7 @@ /** model_get_state_name - return the (string) name of the given state */ -static char *model_get_state_name (enum states state) +static const char *model_get_state_name (enum states state) { if ((state < 0) || (state >= STATE_MAX)) return "INVALID";@@ -33,7 +33,7 @@ static char *model_get_state_name(enum states state) /** model_get_event_name - return the (string) name of the given event */ -static char *model_get_event_name (enum events event) +static const char *model_get_event_name (enum events event) { if ((event < 0) || (event >= EVENT_MAX)) return "INVALID";include/rv/da_monitor.h +0
-0@@ -633,8 +633,8 @@ static inline void da_monitor_destroy(void)*/
static inline void da_trace_event(structda_monitor*da_mon,include/rv/da_monitor.h +2
-2- char *curr_state, char *event, - char *next_state, bool is_final, + const char *curr_state, const char *event, + const char *next_state, bool is_final,
da_id_typeid)
{
CONCATENATE(trace_event_, MONITOR_NAME)(curr_state, event,next_state,include/rv/da_monitor.h +0
-0@@ -642,7 +642,7 @@ static inline void da_trace_event(struct da_monitor *da_mon, }
static inline void da_trace_error(structda_monitor*da_mon,include/rv/da_monitor.h +1
-1- char *curr_state, char *event, + const char *curr_state, const char *event,
da_id_typeid)
{
CONCATENATE(trace_error_, MONITOR_NAME)(curr_state, event);include/rv/da_monitor.h +0
-0@@ -662,8 +662,8 @@ static inline da_id_type da_get_id(struct da_monitor*da_mon) */
static inline void da_trace_event(structda_monitor*da_mon,include/rv/da_monitor.h +2
-2- char *curr_state, char *event, - char *next_state, bool is_final, + const char *curr_state, const char *event, + const char *next_state, bool is_final,
da_id_typeid)
{
CONCATENATE(trace_event_, MONITOR_NAME)(id,curr_state, event,include/rv/da_monitor.h +0
-0@@ -671,7 +671,7 @@ static inline void da_trace_event(struct da_monitor *da_mon, }
static inline void da_trace_error(structda_monitor*da_mon,include/rv/da_monitor.h +1
-1- char *curr_state, char *event, + const char *curr_state, const char *event,
da_id_typeid)
{
CONCATENATE(trace_error_, MONITOR_NAME)(id,curr_state, event);include/rv/ha_monitor.h +1
-1@@ -87,7 +87,7 @@ _Static_assert(offsetof(struct ha_monitor, da_mon) == 0,* environment constraint is false. This function can be called also with no * event from a timer (state constraints only). */ -static void ha_react (enum states curr_state,enum events event,char *env) +static void ha_react (enum states curr_state,enum events event,const char *env) { rv_react(&rv_this,"rv: monitor %s does not allow event %s on state %s with env %s\n",
include/rv/ha_monitor.h +0
-0@@ -98,13 +98,13 @@ static void ha_react(enum states curr_state, enum events event, char *env)
#else /*CONFIG_RV_REACTOR*/
-static voidha_react(enum states curr_state, enum events event, char *env){ }
+static voidha_react(enum states curr_state, enum events event, const char *env){ }
#endif
/*
*model_get_state_name- return the (string) name of the given state */include/rv/ha_monitor.h +1
-1-static char *model_get_env_name (enum envs env) +static const char *model_get_env_name (enum envs env){
if ((env < 0) || (env >=ENV_MAX))
return "INVALID";include/rv/ha_monitor.h +0
-0@@ -227,7 +227,7 @@ static inline void ha_get_env_string(struct seq_buf *s,
#ifRV_MON_TYPE==RV_MON_GLOBAL||RV_MON_TYPE==RV_MON_PER_CPUstatic inline void ha_trace_error_env(structha_monitor*ha_mon,include/rv/ha_monitor.h +0
-1- char *curr_state, char *event, char*env,
include/rv/ha_monitor.h +1
-0+ const char *curr_state, const char*event, const char *env,
da_id_typeid)
{
CONCATENATE(trace_error_env_, MONITOR_NAME)(curr_state, event, env);include/rv/ha_monitor.h +0
-0@@ -237,7 +237,7 @@ static inline void ha_trace_error_env(struct ha_monitor *ha_mon, #define ha_get_target(ha_mon) da_get_target(&ha_mon->da_mon)
static inline void ha_trace_error_env(structha_monitor*ha_mon,include/rv/ha_monitor.h +0
-1- char *curr_state, char *event, char*env,
include/rv/ha_monitor.h +1
-0+ const char *curr_state, const char*event, const char *env,
da_id_typeid)
{
CONCATENATE(trace_error_env_, MONITOR_NAME)(id,curr_state, event, env);kernel/trace/rv/monitors/nomiss/nomiss.h +0
-0@@ -41,9 +41,9 @@ _Static_assert(env_max_stored_nomiss <= MAX_HA_ENV_LEN, "Not enough slots"); #define HA_CLK_NS
structautomaton_nomiss{kernel/trace/rv/monitors/nomiss/nomiss.h +3
-3-char *state_names[state_max_nomiss]; -char *event_names[event_max_nomiss]; -char *env_names[env_max_nomiss]; +const char *state_names[state_max_nomiss]; +const char *event_names[event_max_nomiss]; +const char *env_names[env_max_nomiss];unsigned char function[state_max_nomiss][event_max_nomiss]; unsigned char
initial_state;
bool final_states[state_max_nomiss];kernel/trace/rv/monitors/nomiss/nomiss_trace.h +0
-0@@ -6,14 +6,14 @@
#ifdefCONFIG_RV_MON_NOMISS
DEFINE_EVENT(event_da_monitor_id,event_nomiss,kernel/trace/rv/monitors/nomiss/nomiss_trace.h +0
-1- TP_PROTO(int id, char *state, char *event, char *next_state,bool
final_state),kernel/trace/rv/monitors/nomiss/nomiss_trace.h +1
-0+ TP_PROTO(int id, const char *state, const char *event, constchar
*next_state, boolfinal_state),
TP_ARGS(id, state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor_id,error_nomiss,kernel/trace/rv/monitors/nomiss/nomiss_trace.h +1
-1- TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),
TP_ARGS(id, state, event));
DEFINE_EVENT(error_env_da_monitor_id,error_env_nomiss,kernel/trace/rv/monitors/nomiss/nomiss_trace.h +1
-1- TP_PROTO(int id, char *state, char *event, char *env), + TP_PROTO(int id, const char *state, const char *event, constchar *env),
TP_ARGS(id, state, event, env));
#endif /*CONFIG_RV_MON_NOMISS*/kernel/trace/rv/monitors/nrp/nrp.h +0
-0@@ -26,8 +26,8 @@ enum events_nrp { };
structautomaton_nrp{kernel/trace/rv/monitors/nrp/nrp.h +2
-2-char *state_names[state_max_nrp]; -char *event_names[event_max_nrp]; +const char *state_names[state_max_nrp]; +const char *event_names[event_max_nrp];unsigned char function[state_max_nrp][event_max_nrp]; unsigned char
initial_state;
bool final_states[state_max_nrp];kernel/trace/rv/monitors/nrp/nrp_trace.h +0
-0@@ -6,10 +6,10 @@
#ifdefCONFIG_RV_MON_NRP
DEFINE_EVENT(event_da_monitor_id,event_nrp,kernel/trace/rv/monitors/nrp/nrp_trace.h +0
-1- TP_PROTO(int id, char *state, char *event, char *next_state,bool
final_state),kernel/trace/rv/monitors/nrp/nrp_trace.h +1
-0+ TP_PROTO(int id, const char *state, const char *event, constchar
*next_state, boolfinal_state),
TP_ARGS(id, state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor_id,error_nrp,kernel/trace/rv/monitors/nrp/nrp_trace.h +1
-1- TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),
TP_ARGS(id, state, event));
#endif /*CONFIG_RV_MON_NRP*/kernel/trace/rv/monitors/opid/opid.h +0
-0@@ -30,9 +30,9 @@ enum envs_opid { _Static_assert(env_max_stored_opid <= MAX_HA_ENV_LEN, "Not enough slots");
structautomaton_opid{kernel/trace/rv/monitors/opid/opid.h +3
-3-char *state_names[state_max_opid]; -char *event_names[event_max_opid]; -char *env_names[env_max_opid]; +const char *state_names[state_max_opid]; +const char *event_names[event_max_opid]; +const char *env_names[env_max_opid];unsigned char function[state_max_opid][event_max_opid]; unsigned char
initial_state;
bool final_states[state_max_opid];kernel/trace/rv/monitors/opid/opid_trace.h +0
-0@@ -6,14 +6,14 @@
#ifdefCONFIG_RV_MON_OPID
DEFINE_EVENT(event_da_monitor,event_opid,kernel/trace/rv/monitors/opid/opid_trace.h +0
-1- TP_PROTO(char *state, char *event, char *next_state, bool
final_state),kernel/trace/rv/monitors/opid/opid_trace.h +1
-0+ TP_PROTO(const char *state, const char *event, const char
*next_state, boolfinal_state),
TP_ARGS(state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor,error_opid,kernel/trace/rv/monitors/opid/opid_trace.h +1
-1- TP_PROTO(char *state, char *event), + TP_PROTO(const char *state, const char *event),
TP_ARGS(state, event));
DEFINE_EVENT(error_env_da_monitor,error_env_opid,kernel/trace/rv/monitors/opid/opid_trace.h +1
-1- TP_PROTO(char *state, char *event, char *env), + TP_PROTO(const char *state, const char *event, const char *env),
TP_ARGS(state, event, env));
#endif /*CONFIG_RV_MON_OPID*/kernel/trace/rv/monitors/pagefault/pagefault_trace.h +0
-0@@ -6,7 +6,7 @@
#ifdefCONFIG_RV_MON_PAGEFAULTDEFINE_EVENT(event_ltl_monitor_id,event_pagefault,kernel/trace/rv/monitors/pagefault/pagefault_trace.h +0
-1- TP_PROTO(struct task_struct *task, char *states, char *atoms,char *next),
kernel/trace/rv/monitors/pagefault/pagefault_trace.h +1
-0+ TP_PROTO(struct task_struct *task, const char *states, constchar *atoms, const char *next),
TP_ARGS(task, states, atoms, next)); DEFINE_EVENT(error_ltl_monitor_id,error_pagefault,TP_PROTO(struct task_struct *task),kernel/trace/rv/monitors/sco/sco.h +0
-0@@ -23,8 +23,8 @@ enum events_sco { };
structautomaton_sco{kernel/trace/rv/monitors/sco/sco.h +2
-2-char *state_names[state_max_sco]; -char *event_names[event_max_sco]; +const char *state_names[state_max_sco]; +const char *event_names[event_max_sco];unsigned char function[state_max_sco][event_max_sco]; unsigned char
initial_state;
bool final_states[state_max_sco];kernel/trace/rv/monitors/sco/sco_trace.h +0
-0@@ -6,10 +6,10 @@
#ifdefCONFIG_RV_MON_SCO
DEFINE_EVENT(event_da_monitor,event_sco,kernel/trace/rv/monitors/sco/sco_trace.h +0
-1- TP_PROTO(char *state, char *event, char *next_state, bool
final_state),kernel/trace/rv/monitors/sco/sco_trace.h +1
-0+ TP_PROTO(const char *state, const char *event, const char
*next_state, boolfinal_state),
TP_ARGS(state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor,error_sco,kernel/trace/rv/monitors/sco/sco_trace.h +1
-1- TP_PROTO(char *state, char *event), + TP_PROTO(const char *state, const char *event),
TP_ARGS(state, event));
#endif /*CONFIG_RV_MON_SCO*/kernel/trace/rv/monitors/scpd/scpd.h +0
-0@@ -24,8 +24,8 @@ enum events_scpd { };
structautomaton_scpd{kernel/trace/rv/monitors/scpd/scpd.h +2
-2-char *state_names[state_max_scpd]; -char *event_names[event_max_scpd]; +const char *state_names[state_max_scpd]; +const char *event_names[event_max_scpd];unsigned char function[state_max_scpd][event_max_scpd]; unsigned char
initial_state;
bool final_states[state_max_scpd];kernel/trace/rv/monitors/scpd/scpd_trace.h +0
-0@@ -6,10 +6,10 @@
#ifdefCONFIG_RV_MON_SCPD
DEFINE_EVENT(event_da_monitor,event_scpd,kernel/trace/rv/monitors/scpd/scpd_trace.h +0
-1- TP_PROTO(char *state, char *event, char *next_state, bool
final_state),kernel/trace/rv/monitors/scpd/scpd_trace.h +1
-0+ TP_PROTO(const char *state, const char *event, const char
*next_state, boolfinal_state),
TP_ARGS(state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor,error_scpd,kernel/trace/rv/monitors/scpd/scpd_trace.h +1
-1- TP_PROTO(char *state, char *event), + TP_PROTO(const char *state, const char *event),
TP_ARGS(state, event));
#endif /*CONFIG_RV_MON_SCPD*/kernel/trace/rv/monitors/sleep/sleep_trace.h +0
-0@@ -6,7 +6,7 @@
#ifdefCONFIG_RV_MON_SLEEP
DEFINE_EVENT(event_ltl_monitor_id,event_sleep,kernel/trace/rv/monitors/sleep/sleep_trace.h +0
-1- TP_PROTO(struct task_struct *task, char *states, char *atoms,char *next),
kernel/trace/rv/monitors/sleep/sleep_trace.h +1
-0+ TP_PROTO(struct task_struct *task, const char *states, constchar *atoms, const char *next),
TP_ARGS(task, states, atoms, next));
DEFINE_EVENT(error_ltl_monitor_id,error_sleep,
TP_PROTO(struct task_struct *task),kernel/trace/rv/monitors/snep/snep.h +0
-0@@ -24,8 +24,8 @@ enum events_snep { };
structautomaton_snep{kernel/trace/rv/monitors/snep/snep.h +2
-2-char *state_names[state_max_snep]; -char *event_names[event_max_snep]; +const char *state_names[state_max_snep]; +const char *event_names[event_max_snep];unsigned char function[state_max_snep][event_max_snep]; unsigned char
initial_state;
bool final_states[state_max_snep];kernel/trace/rv/monitors/snep/snep_trace.h +0
-0@@ -6,10 +6,10 @@
#ifdefCONFIG_RV_MON_SNEP
DEFINE_EVENT(event_da_monitor,event_snep,kernel/trace/rv/monitors/snep/snep_trace.h +0
-1- TP_PROTO(char *state, char *event, char *next_state, bool
final_state),kernel/trace/rv/monitors/snep/snep_trace.h +1
-0+ TP_PROTO(const char *state, const char *event, const char
*next_state, boolfinal_state),
TP_ARGS(state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor,error_snep,kernel/trace/rv/monitors/snep/snep_trace.h +1
-1- TP_PROTO(char *state, char *event), + TP_PROTO(const char *state, const char *event),
TP_ARGS(state, event));
#endif /*CONFIG_RV_MON_SNEP*/kernel/trace/rv/monitors/snroc/snroc.h +0
-0@@ -23,8 +23,8 @@ enum events_snroc { };
structautomaton_snroc{kernel/trace/rv/monitors/snroc/snroc.h +2
-2-char *state_names[state_max_snroc]; -char *event_names[event_max_snroc]; +const char *state_names[state_max_snroc]; +const char *event_names[event_max_snroc];unsigned char function[state_max_snroc][event_max_snroc]; unsigned char
initial_state;
bool final_states[state_max_snroc];kernel/trace/rv/monitors/snroc/snroc_trace.h +0
-0@@ -6,10 +6,10 @@
#ifdefCONFIG_RV_MON_SNROC
DEFINE_EVENT(event_da_monitor_id,event_snroc,kernel/trace/rv/monitors/snroc/snroc_trace.h +0
-1- TP_PROTO(int id, char *state, char *event, char *next_state,bool
final_state),kernel/trace/rv/monitors/snroc/snroc_trace.h +1
-0+ TP_PROTO(int id, const char *state, const char *event, constchar
*next_state, boolfinal_state),
TP_ARGS(id, state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor_id,error_snroc,kernel/trace/rv/monitors/snroc/snroc_trace.h +1
-1- TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),
TP_ARGS(id, state, event));
#endif /*CONFIG_RV_MON_SNROC*/kernel/trace/rv/monitors/sssw/sssw.h +0
-0@@ -31,8 +31,8 @@ enum events_sssw { };
structautomaton_sssw{kernel/trace/rv/monitors/sssw/sssw.h +2
-2-char *state_names[state_max_sssw]; -char *event_names[event_max_sssw]; +const char *state_names[state_max_sssw]; +const char *event_names[event_max_sssw];unsigned char function[state_max_sssw][event_max_sssw]; unsigned char
initial_state;
bool final_states[state_max_sssw];kernel/trace/rv/monitors/sssw/sssw_trace.h +0
-0@@ -6,10 +6,10 @@
#ifdefCONFIG_RV_MON_SSSW
DEFINE_EVENT(event_da_monitor_id,event_sssw,kernel/trace/rv/monitors/sssw/sssw_trace.h +0
-1- TP_PROTO(int id, char *state, char *event, char *next_state,bool
final_state),kernel/trace/rv/monitors/sssw/sssw_trace.h +1
-0+ TP_PROTO(int id, const char *state, const char *event, constchar
*next_state, boolfinal_state),
TP_ARGS(id, state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor_id,error_sssw,kernel/trace/rv/monitors/sssw/sssw_trace.h +1
-1- TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),
TP_ARGS(id, state, event));
#endif /*CONFIG_RV_MON_SSSW*/kernel/trace/rv/monitors/stall/stall.h +0
-0@@ -33,9 +33,9 @@ enum envs_stall { _Static_assert(env_max_stored_stall <= MAX_HA_ENV_LEN, "Not enough slots");
structautomaton_stall{kernel/trace/rv/monitors/stall/stall.h +3
-3-char *state_names[state_max_stall]; -char *event_names[event_max_stall]; -char *env_names[env_max_stall]; +const char *state_names[state_max_stall]; +const char *event_names[event_max_stall]; +const char *env_names[env_max_stall];unsigned char function[state_max_stall][event_max_stall]; unsigned char
initial_state;
bool final_states[state_max_stall];kernel/trace/rv/monitors/stall/stall_trace.h +0
-0@@ -6,14 +6,14 @@
#ifdefCONFIG_RV_MON_STALL
DEFINE_EVENT(event_da_monitor_id,event_stall,kernel/trace/rv/monitors/stall/stall_trace.h +0
-1- TP_PROTO(int id, char *state, char *event, char *next_state,bool
final_state),kernel/trace/rv/monitors/stall/stall_trace.h +1
-0+ TP_PROTO(int id, const char *state, const char *event, constchar
*next_state, boolfinal_state),
TP_ARGS(id, state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor_id,error_stall,kernel/trace/rv/monitors/stall/stall_trace.h +1
-1- TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),
TP_ARGS(id, state, event));
DEFINE_EVENT(error_env_da_monitor_id,error_env_stall,kernel/trace/rv/monitors/stall/stall_trace.h +1
-1- TP_PROTO(int id, char *state, char *event, char *env), + TP_PROTO(int id, const char *state, const char *event, constchar *env),
TP_ARGS(id, state, event, env));
#endif /*CONFIG_RV_MON_STALL*/kernel/trace/rv/monitors/sts/sts.h +0
-0@@ -31,8 +31,8 @@ enum events_sts { };
structautomaton_sts{kernel/trace/rv/monitors/sts/sts.h +2
-2-char *state_names[state_max_sts]; -char *event_names[event_max_sts]; +const char *state_names[state_max_sts]; +const char *event_names[event_max_sts];unsigned char function[state_max_sts][event_max_sts]; unsigned char
initial_state;
bool final_states[state_max_sts];kernel/trace/rv/monitors/sts/sts_trace.h +0
-0@@ -6,10 +6,10 @@
#ifdefCONFIG_RV_MON_STS
DEFINE_EVENT(event_da_monitor,event_sts,kernel/trace/rv/monitors/sts/sts_trace.h +0
-1- TP_PROTO(char *state, char *event, char *next_state, bool
final_state),kernel/trace/rv/monitors/sts/sts_trace.h +1
-0+ TP_PROTO(const char *state, const char *event, const char
*next_state, boolfinal_state),
TP_ARGS(state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor,error_sts,kernel/trace/rv/monitors/sts/sts_trace.h +1
-1- TP_PROTO(char *state, char *event), + TP_PROTO(const char *state, const char *event),
TP_ARGS(state, event));
#endif /*CONFIG_RV_MON_STS*/kernel/trace/rv/monitors/wakeup/wakeup_trace.h +0
-0@@ -6,7 +6,7 @@
#ifdefCONFIG_RV_MON_WAKEUP
DEFINE_EVENT(event_ltl_monitor_id,event_wakeup,kernel/trace/rv/monitors/wakeup/wakeup_trace.h +0
-1- TP_PROTO(struct task_struct *task, char *states, char *atoms,char *next),
kernel/trace/rv/monitors/wakeup/wakeup_trace.h +1
-0+ TP_PROTO(struct task_struct *task, const char *states, constchar *atoms, const char *next),
TP_ARGS(task, states, atoms, next));
DEFINE_EVENT(error_ltl_monitor_id,error_wakeup,
TP_PROTO(struct task_struct *task),kernel/trace/rv/monitors/wip/wip.h +0
-0@@ -23,8 +23,8 @@ enum events_wip { };
structautomaton_wip{kernel/trace/rv/monitors/wip/wip.h +2
-2-char *state_names[state_max_wip]; -char *event_names[event_max_wip]; +const char *state_names[state_max_wip]; +const char *event_names[event_max_wip];unsigned char function[state_max_wip][event_max_wip]; unsigned char
initial_state;
bool final_states[state_max_wip];kernel/trace/rv/monitors/wip/wip_trace.h +0
-0@@ -6,10 +6,10 @@
#ifdefCONFIG_RV_MON_WIP
DEFINE_EVENT(event_da_monitor,event_wip,kernel/trace/rv/monitors/wip/wip_trace.h +0
-1- TP_PROTO(char *state, char *event, char *next_state, bool
final_state),kernel/trace/rv/monitors/wip/wip_trace.h +1
-0+ TP_PROTO(const char *state, const char *event, const char
*next_state, boolfinal_state),
TP_ARGS(state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor,error_wip,kernel/trace/rv/monitors/wip/wip_trace.h +1
-1- TP_PROTO(char *state, char *event), + TP_PROTO(const char *state, const char *event),
TP_ARGS(state, event));
#endif /*CONFIG_RV_MON_WIP*/kernel/trace/rv/monitors/wwnr/wwnr.h +0
-0@@ -23,8 +23,8 @@ enum events_wwnr { };
structautomaton_wwnr{kernel/trace/rv/monitors/wwnr/wwnr.h +2
-2-char *state_names[state_max_wwnr]; -char *event_names[event_max_wwnr]; +const char *state_names[state_max_wwnr]; +const char *event_names[event_max_wwnr];unsigned char function[state_max_wwnr][event_max_wwnr]; unsigned char
initial_state;
bool final_states[state_max_wwnr];kernel/trace/rv/monitors/wwnr/wwnr_trace.h +1
-1@@ -7,10 +7,10 @@ #ifdef CONFIG_RV_MON_WWNR /* id is the pid of the task */ DEFINE_EVENT(event_da_monitor_id, event_wwnr, - TP_PROTO(int id, char *state, char *event, char *next_state, bool final_state), + TP_PROTO(int id, const char *state, const char *event, const char *next_state, bool final_state), TP_ARGS(id, state, event, next_state, final_state));
DEFINE_EVENT(error_da_monitor_id,error_wwnr,kernel/trace/rv/monitors/wwnr/wwnr_trace.h +1
-1- TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),
TP_ARGS(id, state, event));
#endif /*CONFIG_RV_MON_WWNR*/kernel/trace/rv/rv_monitors_test.c +0
-0@@ -21,7 +21,7 @@ static struct rv_kunit_ctx *active_ctx;
__printf(1, 0)kernel/trace/rv/rv_monitors_test.c +1
-1-static void rv_kunit_mock_react (const char *msg,va_list args) +static void rv_kunit_mock_react (const const char *msg,va_list args){
if (active_ctx)
++active_ctx->reactions;kernel/trace/rv/rv_reactors.c +0
-0@@ -71,7 +71,7 @@*/ static LIST_HEAD(rv_reactors_list);kernel/trace/rv/rv_reactors.c +1
-1-static struct rv_reactor *get_reactor_rdef_by_name (char *name) +static struct rv_reactor *get_reactor_rdef_by_name (const char *name){
structrv_reactor*r;kernel/trace/rv/rv_trace.h +0
-0@@ -11,7 +11,7 @@ #ifdef CONFIG_DA_MON_EVENTS_IMPLICIT DECLARE_EVENT_CLASS(event_da_monitor,kernel/trace/rv/rv_trace.h +0
-1- TP_PROTO(char *state, char *event, char *next_state, bool
final_state),kernel/trace/rv/rv_trace.h +1
-0+ TP_PROTO(const char *state, const char *event, const char
*next_state, boolfinal_state),
TP_ARGS(state, event, next_state, final_state),kernel/trace/rv/rv_trace.h +0
-0@@ -38,7 +38,7 @@ DECLARE_EVENT_CLASS(event_da_monitor,
DECLARE_EVENT_CLASS(error_da_monitor,kernel/trace/rv/rv_trace.h +1
-1- TP_PROTO(char *state, char *event), + TP_PROTO(const char *state, const char *event),
TP_ARGS(state, event),kernel/trace/rv/rv_trace.h +0
-0@@ -68,7 +68,7 @@ DECLARE_EVENT_CLASS(error_da_monitor, /* For simplicity this class is marked as DA although relevant only for HA */ DECLARE_EVENT_CLASS(error_env_da_monitor,kernel/trace/rv/rv_trace.h +1
-1- TP_PROTO(char *state, char *event, char *env), + TP_PROTO(const char *state, const char *event, const char *env),
TP_ARGS(state, event, env),kernel/trace/rv/rv_trace.h +0
-0@@ -100,7 +100,7 @@ DECLARE_EVENT_CLASS(error_env_da_monitor, #ifdef CONFIG_DA_MON_EVENTS_ID DECLARE_EVENT_CLASS(event_da_monitor_id,kernel/trace/rv/rv_trace.h +0
-1- TP_PROTO(int id, char *state, char *event, char *next_state, bool
final_state),kernel/trace/rv/rv_trace.h +1
-0+ TP_PROTO(int id, const char *state, const char *event, const char
*next_state, boolfinal_state),
TP_ARGS(id, state, event, next_state, final_state),kernel/trace/rv/rv_trace.h +0
-0@@ -130,7 +130,7 @@ DECLARE_EVENT_CLASS(event_da_monitor_id,
DECLARE_EVENT_CLASS(error_da_monitor_id,kernel/trace/rv/rv_trace.h +1
-1- TP_PROTO(int id, char *state, char *event), + TP_PROTO(int id, const char *state, const char *event),
TP_ARGS(id, state, event),kernel/trace/rv/rv_trace.h +0
-0@@ -162,7 +162,7 @@ DECLARE_EVENT_CLASS(error_da_monitor_id, /* For simplicity this class is marked as DA although relevant only for HA */ DECLARE_EVENT_CLASS(error_env_da_monitor_id,kernel/trace/rv/rv_trace.h +1
-1- TP_PROTO(int id, char *state, char *event, char *env), + TP_PROTO(int id, const char *state, const char *event, const char*env),
TP_ARGS(id, state, event, env),kernel/trace/rv/rv_trace.h +0
-0@@ -197,7 +197,7 @@ DECLARE_EVENT_CLASS(error_env_da_monitor_id, #ifdef CONFIG_LTL_MON_EVENTS_ID DECLARE_EVENT_CLASS(event_ltl_monitor_id,kernel/trace/rv/rv_trace.h +0
-1- TP_PROTO(struct task_struct *task, char *states, char *atoms, char*next),
kernel/trace/rv/rv_trace.h +1
-0+ TP_PROTO(struct task_struct *task, const char *states, const char*atoms, const char *next),
TP_ARGS(task, states, atoms, next),kernel/trace/rv/rv_trace.h +0
-0@@ -249,7 +249,7 @@ DECLARE_EVENT_CLASS(error_ltl_monitor_id, /* Tracepoint useful for monitors development, currenly only used in DA */ TRACE_EVENT(rv_retries_error,kernel/trace/rv/rv_trace.h +1
-1- TP_PROTO(char *name, char *event), + TP_PROTO(const char *name, const char *event),
TP_ARGS(name, event),
Gabriele Monaco
maintainerRe: [PATCH v2 04/15] rv: Cast result of model_get_*_name()
In reply to Nam CaoQuoted 8 lines · Nam Cao
Quoted 6 lines · Gabriele Monaco
Functions like
model_get_event_name()andmodel_get_state_name()are shared with BPF monitors, however those programs don't play nice with string pointers without fixed length and theevent_nameandstate_namearrays need to be defined differently. This gets the compiler to notice those are const char and the above function discard the const qualifier.
Quoted 6 lines
Quoted 3 lines
Drop the warning by casting the result to (char *). Note, a cleaner solution would require to modify all callers, but that would require changing every single monitor's tracepoint and the advantage is minimal.
I prefer the cleaner solution. Just mass replace "char *" with "const char *", and manually fix up a few errors and we are done.
The reason I initially didn't do this was that some lines get beyond 100 characters adding the const, so I'd need to break them and make rvgen even more complicated to generate things (TL;DR still laziness).
I'm actually taking a different approach and storing everything in macros like:
#define DEFINE_DA_EVENT(name) \ DEFINE_EVENT(event_da_monitor, name, \ TP_PROTO(char *state, char *event, \ char *next_state, bool final_state), \ TP_ARGS(state, event, next_state, final_state))
So both per-monitor trace headers and rvgen get simpler and if we ever need to change something again, it comes for free.
Gabriele
Re: [PATCH v2 04/15] rv: Cast result of model_get_*_name()
Quoted 3 lines · Gabriele Monaco
The reason I initially didn't do this was that some lines get beyond 100 characters adding the const, so I'd need to break them and make rvgen even more complicated to generate things (TL;DR still laziness).
There is also coccinelle which can automate this and can handle the 100 column limit. Just FYI.
Quoted 10 lines
I'm actually taking a different approach and storing everything in macros like:
#define DEFINE_DA_EVENT(name) \ DEFINE_EVENT(event_da_monitor, name, \ TP_PROTO(char *state, char *event, \ char *next_state, bool final_state), \ TP_ARGS(state, event, next_state, final_state))So both per-monitor trace headers and rvgen get simpler and if we ever need to change something again, it comes for free.
Sounds good.
Nam
Gabriele Monaco
maintainerPATCH v2 5/15 tools/rv: Move argument parsing from in_kernel to utils
In reply to Gabriele MonacoThe configuration of the in-kernel RV monitor is relying on global variables, some static and some extern and the argument parsing occurs there. That's not scalable especially if the configuration needs to be shared by other monitor implementations (e.g. BPF).
Move the common argument parsing in utils and use a global struct for the configuration. Implementation-specific configuration such as the reactors are still handled in the in-kernel source.
--- tools/verification/rv/include/utils.h | 17 ++- tools/verification/rv/src/in_kernel.c | 176 ++++++-------------------- tools/verification/rv/src/utils.c | 95 +++++++++++++- 3 files changed, 149 insertions(+), 139 deletions(-)
tools/verification/rv/include/utils.h +16 -1
@@ -1,8 +1,23 @@// SPDX-License-Identifier: GPL-2.0 +#include <stdbool.h> +#define MAX_PATH 1024void debug_msg (const char *fmt, ...);void err_msg (const char *fmt, ...); +void mon_usage (int exit_val,char *monitor_name,const char *fmt, ...); +int parse_arguments (char *monitor_name,int argc,char **argv); + +void ikm_usage_print_reactors (void ); -extern int config_debug; +struct config { +bool debug; +bool is_container; +bool trace; +int has_id; +int my_pid; +char *initial_reactor; +char *reactor; +}; +extern struct config config;
tools/verification/rv/src/in_kernel.c +40 -136
307 lines not on this page · raw message
tools/verification/rv/src/utils.c +93 -2
114 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 05/15] tools/rv: Move argument parsing from in_kernel to utils
TL;DR: Nit only: the shared parse_arguments() in utils.c still prints an "ikm:" prefix in its debug message, which would mislabel -v output for BPF monitors later in the series. Cosmetic, no…
Quoted 1 line
tools/rv: Move argument parsing fromin_kernelto utils
TL;DR: Nit only: the shared parse_arguments() in utils.c still prints an "ikm:" prefix in its debug message, which would mislabel -v output for BPF monitors later in the series. Cosmetic, no behaviour change.
Quoted 4 lines
tools/verification/rv/src/utils.c +0
-0
[ ... ]
Quoted 1 line
tools/verification/rv/src/utils.c +0
-0@@ -45,3 +48,91 @@ void debug_msg(const char *fmt, ...)
[ ... ]
tools/verification/rv/src/utils.c void debug_msg(const char *fmt, ...) · line 135
Quoted 4 lines
tools/verification/rv/src/utils.c +4
-0+ } + } + +debug_msg ("ikm: my pid is %d\n" , config.my_pid);
Is the "ikm: " prefix still appropriate in this debug message now that parse_arguments() lives in the shared utils.c?
At this commit only ikm_run_monitor() calls parse_arguments(), so the output is correct. Later in the series, 46210ac84ea4 ("tools/rv: Implement BPF monitor loading and tracing") adds bpf_run_monitor(), which sets config.is_bpf = true and then calls parse_arguments(monitor_name, argc, argv).
With that, running "rv mon <bpf_monitor> -v" prints "ikm: my pid is N", even though bpf_run_monitor() labels its own messages with "bpf:" (for example "bpf: failed parsing arguments"). The message is still unchanged at the series tip, 3b00bc9b2e54.
Would dropping the "ikm: " prefix from the shared helper work? The selftest in tests/rv_mon.t only matches "my pid is $pid", so it should keep passing.
This is cosmetic, it only mislabels the -v output and does not change behaviour.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Gabriele Monaco
maintainerPATCH v2 6/15 tools/build: Add a feature test for bpftool-btf
In reply to Gabriele MonacoRV can run bpf monitors and also build them, only the latter requires the vmlinux.h from bpftool btf.
Add a feature so that RV can be built with BPF support without having to build in-tree BPF monitors if not supported on the system.
--- tools/build/Makefile.feature | 1 + tools/build/feature/Makefile | 7 ++++++- 2 files changed, 7 insertions(+), 1 deletion(-)
tools/build/Makefile.feature +1 -0
@@ -129,6 +129,7 @@ FEATURE_TESTS_EXTRA := \ libdebuginfod \ clang-bpf-co-re \ bpftool-skeletons \ + bpftool-btf \ libunwind \ libunwind-debug-frame \ $(foreach arch,$(LIBUNWIND_ARCHS),libunwind-$(arch) libunwind-debug-frame-$(arch))
tools/build/feature/Makefile +6 -1
@@ -71,7 +71,8 @@ FILES= \ test-libpfm4.bin \ test-rust.bin \ test-libopenssl.bin \ - test-bpftool-skeletons.bin + test-bpftool-skeletons.bin \ + test-bpftool-btf.bin FILES := $(addprefix $(OUTPUT),$(FILES))
@@ -383,6 +384,10 @@ $(OUTPUT)test-bpftool-skeletons.bin: { $(SYSTEM_BPFTOOL) version | grep '^features:.*skeletons'; } \ > $(@:.bin=.make.output) 2>&1 && touch $@ +$(OUTPUT)test-bpftool-btf.bin: + $(SYSTEM_BPFTOOL) btf help \ + > $(@:.bin=.make.output) 2>&1 && touch $@ + # Testing Rust is special: we don't compile anything, it's enough to check the # compiler presence. Compiling a test code for this purposes is problematic, # because Rust will emit a dependency file without any external references,
Signature · 1 line
2.55.0
Gabriele Monaco
maintainerPATCH v2 7/15 tools/rv: Implement BPF monitor discovery and listing
In reply to Gabriele MonacoImplement the BPF monitor listing functionality that scans for compiled BPF monitor object files and displays them in the monitor list.
If enabled, running rv list shows in-kernel and BPF monitors found in /usr/share/rv/bpf_monitors/ or in ./bpf_monitors/ relative to the RV binary's location (used during development).
--- tools/verification/rv/Makefile | 4 +- tools/verification/rv/Makefile.config | 23 ++ tools/verification/rv/include/bpf_monitor.h | 14 ++ tools/verification/rv/src/Build | 5 + tools/verification/rv/src/bpf_monitor.c | 223 ++++++++++++++++++++ tools/verification/rv/src/rv.c | 2 + 6 files changed, 270 insertions(+), 1 deletion(-) create mode 100644 tools/verification/rv/include/bpf_monitor.h create mode 100644 tools/verification/rv/src/bpf_monitor.c
tools/verification/rv/Makefile +3 -1
@@ -32,8 +32,10 @@ DOCSRC := ../../../Documentation/tools/rv/ FEATURE_TESTS := libtraceevent FEATURE_TESTS += libtracefs +FEATURE_TESTS += libbpf FEATURE_DISPLAY := libtraceevent FEATURE_DISPLAY += libtracefs +FEATURE_DISPLAY += libbpf all: $(RV)
@@ -57,7 +59,7 @@ endif CFLAGS += $(INCLUDES) $(LIB_INCLUDES) -export CFLAGS OUTPUT srctree +export CFLAGS OUTPUT srctree BUILD_BPF $(RV): $(RV_IN) $(QUIET_LINK)$(CC) $(LDFLAGS) -o $(RV) $(RV_IN) $(EXTLIBS)
tools/verification/rv/Makefile.config +23 -0
@@ -43,6 +43,29 @@ else $(info libtracefs is missing. Please install libtracefs-dev/libtracefs-devel) endif +ifndef BUILD_BPF + # BPF monitors are optional but enabled by default + BUILD_BPF := 1 +endif + +ifeq ($(BUILD_BPF),0) + $(info BPF monitor support disabled, building without BPF monitor support.) +endif + +$(call feature_check,libbpf) +ifeq ($(feature-libbpf), 1) + $(call detected,CONFIG_LIBBPF) +else + $(info libbpf is missing, building without BPF monitor support.) + $(info Please install libbpf-dev/libbpf-devel) + BUILD_BPF := 0 +endif + +ifeq ($(BUILD_BPF),1) + CFLAGS += -DHAVE_LIBBPF + $(call lib_setup,bpf) +endif + ifeq ($(STOP_ERROR),1) $(error Please, check the errors above.) endif
tools/verification/rv/include/bpf_monitor.h new file +14 -0
@@ -0,0 +1,14 @@ +// SPDX-License-Identifier: GPL-2.0 +#ifndef _BPF_MONITOR_H +#define _BPF_MONITOR_H + +#ifdef HAVE_LIBBPF +int bpf_list_monitors (char *container); +#else +static inline int bpf_list_monitors (char *container) +{ +return 0 ; +} +#endif /* HAVE_LIBBPF */ + +#endif
tools/verification/rv/src/Build +5 -0
@@ -1,4 +1,9 @@ rv-y += trace.o rv-y += utils.o rv-y += in_kernel.o + +ifeq ($(BUILD_BPF),1) + rv-y += bpf_monitor.o +endif + rv-y += rv.o
tools/verification/rv/src/bpf_monitor.c new file +223 -0
223 lines not on this page · raw message
tools/verification/rv/src/rv.c +2 -0
@@ -13,6 +13,7 @@#include <trace.h> #include <utils.h> #include <in_kernel.h> +#include <bpf_monitor.h> static int stop_session;
@@ -76,6 +77,7 @@ static void rv_list(int argc, char **argv) }ikm_list_monitors (container); +bpf_list_monitors (container);exit (EXIT_SUCCESS ); }
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 07/15] tools/rv: Implement BPF monitor discovery and listing
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] bpf: stack OOB access via unterminated strncpy() - [Low] bpf: off-by-one snprintf check and file…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] bpf: stack OOB access via unterminated strncpy()
- [Low] bpf: off-by-one snprintf check and file leak
--
commit 87f9013a78d7a34904987bd2e9122ad081e635b2
Author: Gabriele Monaco <[email protected]>
tools/rv: Implement BPF monitor discovery and listing
Implement the BPF monitor listing functionality that scans for compiled BPF monitor object files and displays them in the monitor list.
Quoted 5 lines
tools/verification/rv/src/bpf_monitor.c new file +0
-0
[ ... ]
Quoted 21 lines
tools/verification/rv/src/bpf_monitor.c new file +21
-0+static void bpf_object_iterate_path (const char *base_path,const char *subdir, +void (*action)(const char *name,struct bpf_object *obj)) +{ +char path[MAX_PATH ]; +struct dirent *entry; +DIR *dir; +char *ext; + +snprintf (path,sizeof (path),"%s/%s" , base_path, subdir); + dir =opendir (path); +if (!dir) { +debug_msg ("bpf: error opening directory: %s\n" , path); +return ; + } + +while ((entry =readdir (dir)) !=NULL ) { +size_t size; +struct bpf_object *obj; +char name[MAX_DA_NAME_LEN ], obj_path[MAX_PATH ]; + +if (entry->d_name[0 ] =='.' )
tools/verification/rv/src/bpf_monitor.c line 167
Quoted 10 lines
tools/verification/rv/src/bpf_monitor.c new file +10
-0+continue ; + + ext =strrchr (entry->d_name,'.' ); +if (!ext ||strcmp (ext,".o" ) !=0 ) +continue ; + + size =snprintf (obj_path,sizeof (obj_path),"%s/%s" , path, + entry->d_name); + obj =bpf_object__open_file (obj_path,NULL ); +if (!obj || size >MAX_PATH ) {
[Severity: Low]
Does this logic correctly handle path truncation?
The check size > MAX_PATH has an off-by-one error since snprintf() returns the number of characters that would have been written excluding the null byte, meaning truncation occurs if size >= MAX_PATH (or sizeof(obj_path)).
Also, bpf_object__open_file() is called before this check, potentially operating on truncated paths. If open_file succeeds on a truncated string, would the obj resource be leaked on the error path via the continue statement?
tools/verification/rv/src/bpf_monitor.c line 176
Quoted 9 lines
tools/verification/rv/src/bpf_monitor.c new file +9
-0+err_msg ("bpf: error opening object file %s: %s\n" , + obj_path,strerror (errno)); +continue ; + } + +strncpy (name, entry->d_name,sizeof (name)); + ext =strrchr (name,'.' ); +if (ext) + *ext ='\0' ;
[Severity: Medium]
Could this sequence result in a stack out-of-bounds read and write?
If entry->d_name is exactly MAX_DA_NAME_LEN characters or longer, strncpy() will leave the name array without a null terminator.
This causes strrchr() to scan adjacent stack memory (such as obj_path) to find a '.', and potentially write a '\0' out of bounds if one is found. Can this be triggered by a local user placing a file with a long name in the bpf_monitors directory?
Quoted 8 lines
tools/verification/rv/src/bpf_monitor.c new file +8
-0+ +action (name, obj); + +bpf_object__close (obj); + } + +closedir (dir); +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=7
[email protected]
AI reviewRe: [PATCH v2 07/15] tools/rv: Implement BPF monitor discovery and listing
In reply to Gabriele MonacoTL;DR: - "make static" may now fail to link libbpf (missing -lelf/-lz) now that BPF is on by default - Changelog lists fewer search paths than the code scans, including a cwd fallback
Quoted 1 line
tools/rv: Implement BPF monitor discovery and listing
TL;DR:
- "make static" may now fail to link libbpf (missing -lelf/-lz) now that BPF is on by default
- Changelog lists fewer search paths than the code scans, including a cwd fallback
Quoted 10 lines
tools/rv: Implement BPF monitor discovery and listingImplement the BPF monitor listing functionality that scans for compiled BPF monitor object files and displays them in the monitor list.
If enabled, running rv list shows in-kernel and BPF monitors found in
/usr/share/rv/bpf_monitors/or in ./bpf_monitors/ relative to the RV binary's location (used during development).Signed-off-by Gabriele Monaco <[email protected]>
The commit message names /usr/share/rv/bpf_monitors/ and ./bpf_monitors/ relative to the rv binary. Is that the complete search list?
bpf_list_monitors() scans every entry of bpf_base_paths[] with /bpf_monitors appended:
static char bpf_base_paths[][MAX_PATH] = {
".",
"/etc/rv",
"/usr/local/share/rv",
"/usr/share/rv",
"", /* Marker */
};so /etc/rv/bpf_monitors and /usr/local/share/rv/bpf_monitors are searched as well.
Entry 0 is replaced with the binary's directory only when readlink("/proc/self/exe") succeeds in bpf_fill_base_paths(). Otherwise it stays ".", and the current working directory's bpf_monitors is scanned instead.
All of the directories are scanned, not one or the other, so a monitor present in more than one of them is listed more than once.
Should the changelog describe the actual search list and the working directory fallback, or should the list be trimmed to what is documented? Is /etc/rv an appropriate place to look for BPF object files?
Quoted 4 lines
tools/verification/rv/Makefile.config +0
-0
[ ... ]
Quoted 17 lines
tools/verification/rv/Makefile.config +13
-0@@ -43,6 +43,29 @@ else $(info libtracefs is missing. Please install libtracefs-dev/libtracefs-devel) endif +ifndef BUILD_BPF + # BPF monitors are optional but enabled by default + BUILD_BPF := 1 +endif + +ifeq ($(BUILD_BPF),0) + $(info BPF monitor support disabled, building without BPF monitor support.) +endif + +$(call feature_check,libbpf) +ifeq ($(feature-libbpf), 1) + $(call detected,CONFIG_LIBBPF) +else
tools/verification/rv/Makefile.config else · line 68
Quoted 10 lines
tools/verification/rv/Makefile.config +10
-0+ $(info libbpf is missing, building without BPF monitor support.) + $(info Please install libbpf-dev/libbpf-devel) + BUILD_BPF := 0 +endif + +ifeq ($(BUILD_BPF),1) + CFLAGS += -DHAVE_LIBBPF + $(call lib_setup,bpf) +endif +
Can this break "make static" on systems where it worked before this patch?
BPF support is now on by default whenever the libbpf feature test passes, and lib_setup only adds the output of pkg-config --libs-only-l libbpf, which is just -lbpf. libbpf.pc declares:
Requires.private: libelf zlib
and pkg-config only reports those with --static. The existing static target in tools/verification/rv/Makefile links with -static and $(EXTLIBS):
static: $(RV_IN)
$(eval LDFLAGS += -static) $(QUIET_LINK)$(CC) $(LDFLAGS) -o $(RV)-static $(RV_IN) $(EXTLIBS)
Would that link libbpf.a without -lelf and -lz and fail with unresolved libelf and zlib symbols, so that users now need BUILD_BPF=0 to get a static build?
Could pkg-config be called with --static for the static target, the private dependencies be added, or BPF support be disabled for static builds?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Gabriele Monaco
maintainerPATCH v2 8/15 tools/rv: Implement BPF monitor loading and tracing
In reply to Gabriele MonacoImplement BPF monitor loading, execution, and optional tracing functionality.
Running rv mon MON loads the MON monitor into the kernel and passing the -t parameter also attaches to the event ring buffer printing events and errors to standard output.
Event and state names as well as the ring buffer entry format are dynamically parsed from BTF.
--- tools/verification/rv/include/bpf_monitor.h | 8 + tools/verification/rv/include/utils.h | 2 + tools/verification/rv/src/bpf_monitor.c | 650 ++++++++++++++++++++ tools/verification/rv/src/rv.c | 3 + tools/verification/rv/src/utils.c | 5 +- 5 files changed, 667 insertions(+), 1 deletion(-)
tools/verification/rv/include/bpf_monitor.h +8 -0
@@ -4,11 +4,19 @@#ifdef HAVE_LIBBPF int bpf_list_monitors (char *container); +int bpf_run_monitor (char *monitor_name,int argc,char **argv);#else static inline int bpf_list_monitors (char *container) {return 0 ; } + +static inline int bpf_run_monitor (char *monitor_name,int argc,char **argv) +{ +return 0 ; +} + +void bpf_usage_print_reactors (void ) { }#endif /* HAVE_LIBBPF */ #endif
tools/verification/rv/include/utils.h +2 -0
@@ -10,11 +10,13 @@ void mon_usage(int exit_val, char *monitor_name, const char *fmt, ...);int parse_arguments (char *monitor_name,int argc,char **argv);void ikm_usage_print_reactors (void ); +void bpf_usage_print_reactors (void );struct config {bool debug;bool is_container;bool trace; +bool is_bpf;int has_id;int my_pid;char *initial_reactor;
tools/verification/rv/src/bpf_monitor.c +650 -0
669 lines not on this page · raw message
tools/verification/rv/src/rv.c +3 -0
@@ -127,6 +127,9 @@ static void rv_mon(int argc, char **argv)*/ run +=ikm_run_monitor (monitor_name, argc-1 , &argv[1 ]); +if (!run) + run +=bpf_run_monitor (monitor_name, argc-1 , &argv[1 ]); +if (!run)err_msg ("rv: monitor %s does not exist\n" , monitor_name);exit (run >0 ?EXIT_SUCCESS :EXIT_FAILURE );
tools/verification/rv/src/utils.c +4 -1
@@ -81,7 +81,10 @@ void mon_usage(int exit_val, char *monitor_name, const char *fmt, ...)for (i =0 ; usage[i]; i++)fprintf (stderr,"%s\n" , usage[i]); -ikm_usage_print_reactors (); +if (config.is_bpf) +bpf_usage_print_reactors (); +else +ikm_usage_print_reactors ();exit (exit_val); }
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 08/15] tools/rv: Implement BPF monitor loading and tracing
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider: - [High] bpf: path traversal allows loading arbitrary BPF objects - [Medium] bpf: missing validation of…
Thank you for your contribution! Sashiko AI review found 4 potential issue(s) to consider:
- [High] bpf: path traversal allows loading arbitrary BPF objects
- [Medium] bpf: missing validation of required BTF fields leads to out-of-bounds read
- [Medium] bpf: missing data_sz bounds checks in handle_event leads to out-of-bounds read
- [Medium] bpf: type punning in read_field violates strict aliasing
--
commit 91a3dbdeaaa49f37b21710db6d56a6658ad6fe6b
Author: Gabriele Monaco <[email protected]>
tools/rv: Implement BPF monitor loading and tracing
This commit implements BPF monitor loading, execution, and optional tracing functionality in the rv tool. It parses event and state names from BTF and hooks into the ring buffer for output formatting.
Quoted 3 lines
tools/verification/rv/src/bpf_monitor.c +0
-0
[ ... ]
Quoted 5 lines
for (int j = 0; j < FIELD_MAX; j++) {
if (strcmp(name, field_names[j]) == 0) {
ctx->field_metadata[j].offset = offset;
ctx->field_metadata[j].size = size;
if (j == FIELD_ID)Quoted 8 lines
config.has_id = true; break; } } } return 0; }
[Severity: Medium]
Is there a need to verify that all required fields were found after this loop?
If the BTF data does not contain a required field (like comm), its offset in ctx->field_metadata remains 0. Later, handle_event() relies on this offset unconditionally, which would point to the start of the payload and result in an out-of-bounds read.
[ ... ]
Quoted 13 lines
static inline
uint64_tread_field(uint64_t *entry, enumfield_idid,
constuint8_t*raw, const structbpf_monitor_ctx*ctx){ const struct field *field = &ctx->field_metadata[id]; switch (field->size) { case 1: return entry[id] = *(const uint8_t *)(raw + field->offset); case 2: return entry[id] = *(const uint16_t *)(raw + field->offset); case 4: return entry[id] = *(const uint32_t *)(raw + field->offset);
[Severity: Medium]
Does casting a const uint8_t * byte pointer to larger scalar types like uint32_t * violate strict aliasing rules?
The tools directory is compiled with -fstrict-aliasing enabled, so this type punning can result in undefined behavior and miscompilation.
Also, is it possible for the offset + size to exceed the data_sz provided by the ring buffer? read_field() dereferences memory based purely on BTF offsets without validating that the access fits within the actual payload size.
[ ... ]
Quoted 4 lines
static int
handle_event(void *ctx, void *data, size_t data_sz){ struct bpf_monitor_ctx *mon_ctx = ctx; const uint8_t *raw = data;
[Severity: Medium]
Is the data_sz parameter ignored in this function?
If a BPF program submits a truncated event to the ring buffer, the missing bounds checks in this function and read_field() could lead to out-of-bounds memory reads.
[ ... ]
Quoted 5 lines
comm = (const char *)(raw + mon_ctx->field_metadata[FIELD_COMM].offset);
read_field(entry, FIELD_CURR_STATE, raw, mon_ctx);
read_field(entry, FIELD_EVENT, raw, mon_ctx);
printf("%16s-%-8"PRIu64" [%.3"PRIu64"] ", comm, entry[FIELD_PID], entry[FIELD_CPU]);[Severity: Medium]
Could this printf() format specifier lead to unbounded memory reads?
Using %16s instead of %.16s allows printf to read indefinitely until it encounters a null byte. If the string is not null-terminated or was absent, this might read beyond data_sz.
[ ... ]
Quoted 9 lines
static int
find_bpf_file(const char *subdir, const char *name, char *path_out, size_t path_len){ char path[MAX_PATH]; for (int i = 0; bpf_base_paths[i][0]; i++) { size_t size = snprintf(path, sizeof(path), "%s/%s/%s.o", bpf_base_paths[i], subdir, name); if (size < MAX_PATH && access(path, R_OK) == 0) {
[Severity: High]
Can a malicious user supply a name containing path traversal characters like ../../../ to load arbitrary object files?
The user-controlled monitor_name is passed to find_bpf_file() and blindly appended to the path string. If an administrator configures sudo to allow running rv mon, an attacker could exploit this traversal to load their own BPF program and gain arbitrary kernel code execution.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=8
[email protected]
AI reviewRe: [PATCH v2 08/15] tools/rv: Implement BPF monitor loading and tracing
In reply to Gabriele MonacoTL;DR: - Tracing may end early on -EINTR (e.g. Ctrl-Z then fg), unloading the monitor - BPF monitors may not start without CONFIG_RV - Enum with exactly 64 members possibly rejected - Trace column…
Quoted 1 line
tools/rv: Implement BPF monitor loading and tracing
TL;DR:
- Tracing may end early on -EINTR (e.g. Ctrl-Z then fg), unloading the monitor
- BPF monitors may not start without CONFIG_RV
- Enum with exactly 64 members possibly rejected
- Trace column misalignment, misleading comment, unused parameter (nits)
Quoted 4 lines
tools/verification/rv/src/bpf_monitor.c +0
-0
[ ... ]
Quoted 1 line
tools/verification/rv/src/bpf_monitor.c +0
-0@@ -221,3 +279,595 @@ int bpf_list_monitors(char *container)
[ ... ]
Quoted 11 lines
tools/verification/rv/src/bpf_monitor.c +11
-0+static void bpf_print_header (void ) +{ +printf ("%16s-%-8s %5s %5s " ,"<TASK>" ,"PID" ,"[CPU]" ,"TYPE" ); +if (config.has_id) +printf (" %8s" ,"ID" ); + +printf ("%24s x %-24s -> %-24s %s\n" , +"STATE" , +"EVENT" , +"NEXT_STATE" , +"FINAL" );
[ ... ]
Quoted 10 lines
tools/verification/rv/src/bpf_monitor.c +10
-0+printf ("%16s-%-8" PRIu64" [%.3" PRIu64"] " , comm, entry[FIELD_PID ], entry[FIELD_CPU ]); +if (entry[FIELD_EVENT_TYPE ] == mon_ctx->trace_types[TRACE_TYPE_ERROR ]) { +printf ("error " ); +if (config.has_id) +printf (" %8" PRIu64"" , entry[FIELD_ID ]); +printf (" %24s x %-24s\n" , +get_state_name (mon_ctx, entry[FIELD_CURR_STATE ]), +get_event_name (mon_ctx, entry[FIELD_EVENT ])); + }else if (entry[FIELD_EVENT_TYPE ] == mon_ctx->trace_types[TRACE_TYPE_EVENT ]) { +printf ("event " );
tools/verification/rv/src/bpf_monitor.c int bpf_list_monitors(char *container) · line 509
Quoted 10 lines
tools/verification/rv/src/bpf_monitor.c +10
-0+read_field (entry,FIELD_IS_FINAL , raw, mon_ctx); +read_field (entry,FIELD_NEXT_STATE , raw, mon_ctx); + +if (config.has_id) +printf (" %8" PRIu64"" , entry[FIELD_ID ]); +printf (" %24s x %-24s -> %-24s %c\n" , +get_state_name (mon_ctx, entry[FIELD_CURR_STATE ]), +get_event_name (mon_ctx, entry[FIELD_EVENT ]), +get_state_name (mon_ctx, entry[FIELD_NEXT_STATE ]), + entry[FIELD_IS_FINAL ] ?'Y' :'N' );
Is the extra leading space before %24s in the data rows intentional?
bpf_print_header() prints the STATE column with no leading space:
printf("%24s x %-24s -> %-24s %s\n", "STATE", ...);while handle_event() prints:
printf(" %24s x %-24s -> %-24s %c\n", ...);The prefixes before that point have the same width ("comm-pid [cpu] event " versus the TYPE header, plus the 9 column ID field), so every STATE, EVENT, NEXT_STATE and FINAL value lands one column to the right of its header label and of the " | " separator row. With has_id the header " x " sits at column 71 and the data rows at column 72; without an id it is 62 versus 63.
The error line in the TRACE_TYPE_ERROR branch has the same extra space.
The in-kernel ikm_print_header() and ikm_event_handler() line up because both use "%8s " / "%8llu " followed by "%24s". Should the data rows use "%24s x ..." or the header " %24s x ...", so the columns match?
No later commit in the series (up to 3b00bc9b2e54) changes bpf_print_header() or handle_event().
[ ... ]
Quoted 2 lines
tools/verification/rv/src/bpf_monitor.c +2
-0+static int extract_enum_names (const struct btf *btf,const char *enum_kind, +char dest[][MAX_DA_NAME_LEN ],struct bpf_monitor_ctx *ctx)
[ ... ]
Quoted 9 lines
tools/verification/rv/src/bpf_monitor.c +9
-0+if (!name || count >=MAX_ENUMS ) +break ; + +/* max value must be the last */ +if (!strcmp (name, buf)) { +if (i == vlen -1 ) + arrived_at_last = true; +break ; + }
[ ... ]
tools/verification/rv/src/bpf_monitor.c int bpf_list_monitors(char *container) · line 580
Quoted 4 lines
tools/verification/rv/src/bpf_monitor.c +4
-0+if (!arrived_at_last) { +debug_msg ("bpf: malformed %ss enum, could fill %d\n" , enum_kind, count); +return -1 ; + }
Can this reject a valid enum with exactly MAX_ENUMS members? The capacity check runs before the terminator check:
if (!name || count >= MAX_ENUMS)
break;
/* max value must be the last */
if (!strcmp(name, buf)) {Take an enum with 64 real members followed by state_max_X (vlen = 65). Iterations i = 0..63 fill dest[0..63] and leave count == 64. At i == 64 the name is "state_max_X", but count >= MAX_ENUMS is already true, so the loop breaks before the strcmp() can set arrived_at_last.
extract_enum_names() then logs "malformed states enum, could fill 64" and returns -1. That propagates:
extract_enum_names() -> extract_btf_info() -> open_bpf_monitor()
open_bpf_monitor() prints "bpf: failed to enable tracing" and returns NULL, so "rv mon X -t" fails entirely.
ctx->state_names and ctx->event_names are char [MAX_ENUMS][MAX_DA_NAME_LEN], so they have room for all 64 names. Should the *_max_* name be checked before the capacity check? As written the real limit is 63 entries, with a misleading "malformed" diagnostic for a well-formed enum.
No shipped monitor (tqueue, nohz) is this large, but rvgen -b (8c5ba90eb059, later in the series) generates BPF monitors from arbitrary models. The code is unchanged at the end of the series (3b00bc9b2e54).
[ ... ]
tools/verification/rv/src/bpf_monitor.c int bpf_list_monitors(char *container) · line 755
Quoted 9 lines
tools/verification/rv/src/bpf_monitor.c +9
-0+/* +* attach_bpf_handlers - attach all BPF programs +* +* Attaches all non-struct_ops programs and stores links in the provided array. +* +* Returns fd of enable program on success, -1 on error. +*/ +static int attach_bpf_handlers (const char *monitor_name,struct bpf_object *obj, +struct bpf_link **links,int *link_count)
This isn't a bug, but the comment says this "Attaches all non-struct_ops programs", and the code never checks for struct_ops. The only program skipped is PROG_ENABLE_MON ("enable_monitor"); every other program from bpf_object__for_each_program() is passed to bpf_program__attach().
In libbpf, SEC_DEF("struct_ops+", STRUCT_OPS, 0, SEC_NONE) has no prog_attach_fn, so bpf_program__attach() returns NULL with errno set to EOPNOTSUPP for such a program. attach_bpf_handlers() would then print "bpf: error attaching program" and return -1, so the monitor would fail to start, which is the opposite of what the comment says.
The comment also does not mention that enable_monitor is skipped and its fd returned. Should the comment describe what the code does (attach everything except enable_monitor), or should the code skip struct_ops programs, for example by checking bpf_program__type(prog) == BPF_PROG_TYPE_STRUCT_OPS?
This mismatch is still present at the end of the series (3b00bc9b2e54).
Also, this isn't a bug, but the monitor_name parameter of attach_bpf_handlers() is never used in the body. The function only uses obj, links and link_count, and its error messages print prog_name, *link_count and PROG_ENABLE_MON. bpf_run_monitor() still passes it:
enable_mon_fd = attach_bpf_handlers(monitor_name, obj, links, &link_count);
Could the parameter be dropped, or used in the error messages (for example "bpf: %s: error attaching program '%s'") so failures say which monitor they belong to? It is also unused at the end of the series (3b00bc9b2e54).
[ ... ]
tools/verification/rv/src/bpf_monitor.c int bpf_list_monitors(char *container) · line 860
Quoted 13 lines
tools/verification/rv/src/bpf_monitor.c +13
-0+while (!should_stop ()) { +if (!config.trace) { +sleep (1 ); +continue ; + } + res =ring_buffer__poll (rb,100 ); +if (res == -EINTR ) +break ; +if (res <0 ) { +err_msg ("bpf: error polling ring buffer: %s\n" ,strerror (-res)); + goto cleanup; + } + }
Can this end the trace session without a stop having been requested? The loop condition already checks should_stop(), which is set by the SIGINT/SIGTERM handler stop_rv(), but any -EINTR from ring_buffer__poll() breaks out of the loop, even when the interruption did not come from those signals.
ring_buffer__poll() returns libbpf_err(-errno) when epoll_wait() fails, and ep_poll() returns -EINTR whenever signal_pending() is true. That is not one of the -ERESTART* codes, so the kernel does not restart the call. On Linux, epoll_wait() returns EINTR after a process is stopped by a job control signal and then resumed with SIGCONT (see signal(7)), and rv installs no handler for SIGTSTP or SIGCONT.
For example, with "rv mon tqueue -t", press Ctrl-Z and then run "fg":
epoll_wait() returns EINTR
-> ring_buffer__poll() returns -EINTR
-> break, with should_stop() still false
-> cleanup: bpf_link__destroy(), bpf_object__close()The monitor is unloaded and rv exits with success instead of resuming the trace. The in-kernel path (ikm_run_monitor) handles this case, because its sleep(1)/tracefs loop just re-checks should_stop(). Should -EINTR use "continue" here and let should_stop() decide? The code is unchanged at the end of the series (3b00bc9b2e54).
[ ... ]
Quoted 4 lines
tools/verification/rv/src/rv.c +0
-0
[ ... ]
tools/verification/rv/src/rv.c static void rv_mon(int argc, char **argv) · line 135
Quoted 10 lines
tools/verification/rv/src/rv.c +3
-0@@ -127,6 +127,9 @@ static void rv_mon(int argc, char **argv)*/ run +=ikm_run_monitor (monitor_name, argc-1 , &argv[1 ]); +if (!run) + run +=bpf_run_monitor (monitor_name, argc-1 , &argv[1 ]); +if (!run)err_msg ("rv: monitor %s does not exist\n" , monitor_name);exit (run >0 ?EXIT_SUCCESS :EXIT_FAILURE );
Can BPF monitors still be started on a kernel without CONFIG_RV? rv list still shows them there, but ikm_run_monitor() does not return 0 ("not found") when the in-kernel RV interface is missing. It returns -1 ("error"):
__ikm_find_monitor_name():
available_monitors = tracefs_instance_file_read(NULL, "rv/available_monitors", NULL);
if (!available_monitors)
return -1;
ikm_run_monitor():
retval = __ikm_find_monitor_name(monitor_name, full_name);
...
if (retval < 0) {
err_msg("ikm: error finding monitor %s\n", nested_name);
return -1;
}With no tracefs rv/ directory, run is -1 and "if (!run)" is false, so bpf_run_monitor() is never called. "rv mon nohz" prints "ikm: error finding monitor nohz" and exits with failure.
The listing path treats the same situation differently: rv_list() calls bpf_list_monitors() even after ikm_list_monitors() fails with "is CONFIG_RV enabled?", so the BPF monitors are listed but then cannot be run.
The BPF monitors added later in the series only attach to generic hooks:
nohz uses fentry/sched_tick, fentry/tick_nohz_restart_sched_tick and tp_btf/tick_stop, and tqueue uses tp_btf/sched_{en,de}queue_tp, which are exported unconditionally in kernel/sched/core.c. Neither needs CONFIG_RV.
Should the dispatch fall through to the BPF path when the in-kernel interface is unavailable, rather than only on run == 0? No later commit in the series (up to 3b00bc9b2e54) changes this.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Gabriele Monaco
maintainerPATCH v2 9/15 tools/rv: Copy stripped bpf_atomic.h from libarena
In reply to Gabriele MonacoAdd bpf_atomic.h including atomic read/write macros like READ_ONCE() and try_cmpxchg(). This version is a stripped down copy of the one currently present in selftests/bpf/libarena.
--- .../verification/rv/bpf_monitors/bpf_atomic.h | 105 ++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 tools/verification/rv/bpf_monitors/bpf_atomic.h
tools/verification/rv/bpf_monitors/bpf_atomic.h new file +105 -0
@@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */ +#ifndef BPF_ATOMIC_H +#define BPF_ATOMIC_H + +#include <vmlinux.h> +#include <bpf/bpf_helpers.h> + +extern bool CONFIG_X86_64 __kconfig __weak; + +/* +* __unqual_typeof(x) - Declare an unqualified scalar type, leaving +* non-scalar types unchanged, +* +* Prefer C11 _Generic for better compile-times and simpler code. Note: 'char' +* is not type-compatible with 'signed char', and we define a separate case. +* +* This is copied verbatim from kernel's include/linux/compiler_types.h, but +* with default expression (for pointers) changed from (x) to (typeof(x)0). +* +* This is because LLVM has a bug where for lvalue (x), it does not get rid of +* an extra address_space qualifier, but does in case of rvalue (typeof(x)0). +* Hence, for pointers, we need to create an rvalue expression to get the +* desired type. See https://github.com/llvm/llvm-project/issues/53400. +*/ +#define __scalar_type_to_expr_cases (type) \ + unsigned type : (unsigned type)0, signed type : (signed type)0 + +#define __unqual_typeof (x) \ + typeof(_Generic((x), \ + char: (char)0, \ + __scalar_type_to_expr_cases(char), \ + __scalar_type_to_expr_cases(short), \ + __scalar_type_to_expr_cases(int), \ + __scalar_type_to_expr_cases(long), \ + __scalar_type_to_expr_cases(long long), \ + default: (typeof(x))0)) + +/* No-op for BPF */ +#define cpu_relax () ({}) + +#define READ_ONCE (x) (*(volatile typeof(x) *)&(x)) + +#ifndef WRITE_ONCE +#define WRITE_ONCE (x, val) ((*(volatile typeof(x) *)&(x)) = (val)) +#endif + +#define cmpxchg (p, old, new) __sync_val_compare_and_swap((p), old, new) + +#define try_cmpxchg (p, pold, new) \ + ({ \ + __unqual_typeof(*(pold)) __o = *(pold); \ + __unqual_typeof(*(p)) __r = cmpxchg(p, __o, new); \ + if (__r != __o) \ + *(pold) = __r; \ + __r == __o; \ + }) + +#define try_cmpxchg_relaxed (p, pold, new) try_cmpxchg(p, pold, new) + +#define try_cmpxchg_acquire (p, pold, new) try_cmpxchg(p, pold, new) + +#define smp_mb () \ + ({ \ + volatile unsigned long __val; \ + __sync_fetch_and_add(&__val, 0); \ + }) + +#define smp_rmb () \ + ({ \ + if (!CONFIG_X86_64) \ + smp_mb(); \ + else \ + barrier(); \ + }) + +#define smp_wmb () \ + ({ \ + if (!CONFIG_X86_64) \ + smp_mb(); \ + else \ + barrier(); \ + }) + +/* Control dependency provides LOAD->STORE, provide LOAD->LOAD */ +#define smp_acquire__after_ctrl_dep () ({ smp_rmb(); }) + +#define smp_load_acquire (p) \ + ({ \ + __unqual_typeof(*(p)) __v = READ_ONCE(*(p)); \ + if (!CONFIG_X86_64) \ + smp_mb(); \ + barrier(); \ + __v; \ + }) + +#define smp_store_release (p, val) \ + ({ \ + if (!CONFIG_X86_64) \ + smp_mb(); \ + barrier(); \ + WRITE_ONCE(*(p), val); \ + }) + +#endif /* BPF_ATOMIC_H */
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 09/15] tools/rv: Copy stripped bpf_atomic.h from libarena
TL;DR: The CONFIG_X86_64 kconfig extern in bpf_atomic.h may make BPF monitors fail to load (-EINVAL) on hosts without a readable kernel config, but only in the bisect window until a later patch…
Quoted 1 line
tools/rv: Copy strippedbpf_atomic.hfrom libarena
TL;DR: The CONFIG_X86_64 kconfig extern in bpf_atomic.h may make BPF monitors fail to load (-EINVAL) on hosts without a readable kernel config, but only in the bisect window until a later patch fixes it.
Quoted 6 lines
tools/verification/rv/bpf_monitors/bpf_atomic.h new file +0
-0
tools/verification/rv/bpf_monitors/bpf_atomic.h line 9
Quoted 9 lines
tools/verification/rv/bpf_monitors/bpf_atomic.h new file +9
-0@@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-2.0 +/* Copyright (c) 2025 Meta Platforms, Inc. and affiliates. */ +#ifndef BPF_ATOMIC_H +#define BPF_ATOMIC_H + +#include <vmlinux.h> +#include <bpf/bpf_helpers.h> + +extern bool CONFIG_X86_64 __kconfig __weak;
Can this extern make every BPF monitor fail to load on a host that has no readable kernel config?
smp_load_acquire() and smp_store_release() reference CONFIG_X86_64, and include/rv/da_monitor.h uses these macros (da_monitoring(), da_monitor_start(), da_monitor_reset_state()), so each monitor object ends up with a CONFIG_ kconfig extern.
The __weak attribute does not make it optional in that case. In libbpf, bpf_object__resolve_externs() sets need_config for any extern whose name starts with "CONFIG_", and then requires the config file to be readable:
if (str_has_pfx(ext->name, "CONFIG_")) {
need_config = true;
continue;
}
...
if (need_config) {
err = bpf_object__read_kconfig_file(obj, kcfg_data);
if (err)
return -EINVAL;
}bpf_object__read_kconfig_file() returns -ENOENT when neither /boot/config-$(uname -r) nor /proc/config.gz exists.
Once f5fc86049b84 ("tools/rv: Add BPF monitors") includes this header via da_monitor_bpf.h, open_bpf_monitor() calls bpf_object__open_file(path, NULL) followed by bpf_object__load(obj). That load would fail with -EINVAL on self-built kernels without CONFIG_IKCONFIG_PROC, or in containers without /boot/config-*.
The series fixes this later in 3b66b9d4a13a ("tools/rv: Define CONFIG_X86_64 statically for BPF monitors"), which passes .kconfig = "CONFIG_X86_64=y|n" through bpf_object_open_opts. So the failure is limited to the bisect window f5fc86049b84..3b66b9d4a13a^.
Could that fix be folded in before f5fc86049b84, or could this header resolve the architecture at compile time, so that every step of the series stays loadable?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Re: [PATCH v2 09/15] tools/rv: Copy stripped bpf_atomic.h from libarena
In reply to Gabriele MonacoQuoted 3 lines · Gabriele Monaco
Add
bpf_atomic.hincluding atomic read/write macros likeREAD_ONCE()andtry_cmpxchg(). This version is a stripped down copy of the one currently present in selftests/bpf/libarena.
Instead of this, what do you think about using C11's atomic stuffs? I prefer standardized stuff when it is an option.
Nam
Gabriele Monaco
maintainerRe: [PATCH v2 09/15] tools/rv: Copy stripped bpf_atomic.h from libarena
Il 7 ottobre 2026 12:59:46 UTC, Nam Cao <[email protected]> ha scritto:
Quoted 7 lines
Quoted 3 lines · Gabriele Monaco
Add
bpf_atomic.hincluding atomic read/write macros likeREAD_ONCE()andtry_cmpxchg(). This version is a stripped down copy of the one currently present in selftests/bpf/libarena.Instead of this, what do you think about using C11's atomic stuffs? I prefer standardized stuff when it is an option.
Mmh, I'm not too familiar with them, but they wouldn't be drop-in replacements as far as I understand. I'd need to use C11 atomic types and that would diverge further from the kernel implementation.
Ideally I wouldn't like to copy libarena's implementation but I couldn't find a cleaner way to include it.
I'm going to look into that more carefully though.
Thanks,
Gabriele
Re: [PATCH v2 09/15] tools/rv: Copy stripped bpf_atomic.h from libarena
Quoted 3 lines · Gabriele Monaco
Mmh, I'm not too familiar with them, but they wouldn't be drop-in replacements as far as I understand. I'd need to use C11 atomic types and that would diverge further from the kernel implementation.
I am thinking we should migrate to BPF entirely. Keeping both in-kernel and BPF will be a bit painful.
Nam
Gabriele Monaco
maintainerRe: [PATCH v2 09/15] tools/rv: Copy stripped bpf_atomic.h from libarena
Quoted 7 lines · Nam Cao
Quoted 3 lines · Gabriele Monaco
Mmh, I'm not too familiar with them, but they wouldn't be drop-in replacements as far as I understand. I'd need to use C11 atomic types and that would diverge further from the kernel implementation.
I am thinking we should migrate to BPF entirely. Keeping both in-kernel and BPF will be a bit painful.
Yeah that's a valid point, though I'm considering it more like a longer term goal. I'd rather avoid rushing the migration until we're sure BPF is perfectly capable to handle absolutely everything and we can cover every usecase.
There's a common belief considering BPF a prototyping playground, where "real" things should eventually end up in the kernel.
Now, I don't agree with it (look at the many sched_ext policies used in production), but I'd want to assess if dropping kernel support could drive users away (e.g. industry/automotive which keeps popping out) and understand the various not purely technical reasons.
Gabriele
Steven Rostedt
maintainerRe: [PATCH v2 09/15] tools/rv: Copy stripped bpf_atomic.h from libarena
Please keep both until you know the BPF side can do everything you need.
Quoted 6 lines · On Fri, 09 Oct 2026 12:09:42 +0200 Gabriele Monaco <[email protected]> wrote:
There's a common belief considering BPF a prototyping playground, where "real" things should eventually end up in the kernel.
Now, I don't agree with it (look at the manysched_extpolicies used in production), but I'd want to assess if dropping kernel support could drive users away (e.g. industry/automotive which keeps popping out) and understand the various not purely technical reasons.
Where do you plan on storing the repository of BPF programs?
One issue I have with sched_ext is that it did exactly what many people were worried about. There's a lot of schedulers out there without much collaboration. It's the "copy one close to what I want and tweak it". When I left Google, I heard there was 20 or so sched_ext schedulers doing various things for various projects.
One of my main motivations for scheduler governors.
-- Steve
Gabriele Monaco
maintainerRe: [PATCH v2 09/15] tools/rv: Copy stripped bpf_atomic.h from libarena
Hi Steve,
Quoted 2 lines · Steven Rostedt
Please keep both until you know the BPF side can do everything you need.
I agree. Also, complex monitors like timed automata won't be as easy to migrate.
Quoted 12 lines
Quoted 7 lines · On Fri, 09 Oct 2026 12:09:42 +0200 Gabriele Monaco <[email protected]> wrote:
There's a common belief considering BPF a prototyping playground, where "real"
things should eventually end up in the kernel.
Now, I don't agree with it (look at the manysched_extpolicies used in production), but I'd want to assess if dropping kernel support could drive users away (e.g. industry/automotive which keeps popping out) and understand the various not purely technical reasons.
Quoted 1 line
Where do you plan on storing the repository of BPF programs?
That's something I would like to refine better. But I'm planning to keep "official" monitors in-tree (tools/rv) and encourage to upstream monitors nonetheless.
We could come up with a separate repository for "community" monitors, with perhaps a lower bar compared to the ones in-tree. That'd hopefully encourage collaboration where possible.
Quoted 7 lines
One issue I have with
sched_extis that it did exactly what many people were worried about. There's a lot of schedulers out there without much collaboration. It's the "copy one close to what I want and tweak it". When I left Google, I heard there was 20 or sosched_extschedulers doing various things for various projects.One of my main motivations for scheduler governors.
Yeah that's a good point, though I'm not quite sure how to prevent that. People could do mostly the same using kernel modules as well, however.
At the moment I still didn't figure out how to build monitors out-of-tree, that might encourage a bit more working in-tree.
The difference with sched_ext here is that this BPF implementation requires little to none kernel support. For all we know, people out there might already be running something like RV monitors implemented in BPF or whatever else.
Currently most of the logic is supposed to go to the shared headers, but monitors can implement some custom logic too (you already need to touch the C file anyway). I'd like to reduce reliance on custom logic as much as possible, that was already brought up by a couple of people. This way, hopefully, people would rely more on the "library" and share/request any improvement.
But again, I don't have real answers to that, and I'm open to discuss more sensible solutions.
Thanks,
Gabriele
Gabriele Monaco
maintainerPATCH v2 10/15 tools/rv: Add BPF monitors
In reply to Gabriele MonacoAdd the code for 2 initial BPF monitors, both DA (the only currently supported type):
* queue: per-task monitor stating tasks alternate enqueue and dequeue.
* nohz: per-cpu monitor stating the scheduler tick don't run when stopped and can run only after being resumed.
BPF monitors can include the in-kernel da_monitor.h, which is now adapted to share as much common code and conditionally compile what needs to be BPF or kernel specific.
Integrate BPF monitor building into main rv Makefile, if all tools are available on the system.
--- include/rv/da_monitor.h | 21 +- tools/verification/models/nohz.dot | 16 + tools/verification/models/tqueue.dot | 15 + tools/verification/rv/Makefile | 42 +- tools/verification/rv/Makefile.config | 26 ++ tools/verification/rv/Makefile.rv | 5 + tools/verification/rv/bpf_monitors/.gitignore | 2 + .../rv/bpf_monitors/da_monitor_bpf.h | 368 ++++++++++++++++++ tools/verification/rv/bpf_monitors/nohz.c | 42 ++ tools/verification/rv/bpf_monitors/nohz.h | 49 +++ tools/verification/rv/bpf_monitors/tqueue.c | 30 ++ tools/verification/rv/bpf_monitors/tqueue.h | 47 +++ 12 files changed, 655 insertions(+), 8 deletions(-) create mode 100644 tools/verification/models/nohz.dot create mode 100644 tools/verification/models/tqueue.dot create mode 100644 tools/verification/rv/bpf_monitors/.gitignore create mode 100644 tools/verification/rv/bpf_monitors/da_monitor_bpf.h create mode 100644 tools/verification/rv/bpf_monitors/nohz.c create mode 100644 tools/verification/rv/bpf_monitors/nohz.h create mode 100644 tools/verification/rv/bpf_monitors/tqueue.c create mode 100644 tools/verification/rv/bpf_monitors/tqueue.h
include/rv/da_monitor.h +16 -5
@@ -14,14 +14,19 @@#ifndef _RV_DA_MONITOR_H#define _RV_DA_MONITOR_H -#include <rv/automata.h> -#include <linux/rv.h> +#ifndef __BPF__ +/* Kernel includes */ #include <rv/kunit.h> -#include <linux/stringify.h> #include <linux/bug.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/hashtable.h> +#endif /* __BPF__ */ + +#include <linux/args.h> +#include <rv/automata.h> +#include <linux/rv.h> +#include <linux/stringify.h> /* * Per-cpu variables require a unique name although static in some
@@ -77,6 +82,9 @@ static struct rv_monitor rv_this;#define da_id_type int#endif +#ifdef __BPF__ +#include "da_monitor_bpf.h" +#else static void react (enum states curr_state,enum events event) { rv_react(&rv_this,
@@ -85,6 +93,7 @@ static void react(enum states curr_state, enum events event)model_get_event_name (event), model_get_state_name(curr_state)); } +#endif /* * da_monitor_reset_state - reset a monitor and setting it to init state
@@ -159,6 +168,7 @@ static inline bool da_monitor_handling_event(struct da_monitor *da_mon)return 1 ; } +#ifndef __BPF__#if RV_MON_TYPE ==RV_MON_GLOBAL /* * Functions to define, init and get a global monitor.
@@ -685,6 +695,7 @@ static inline void da_trace_error(struct da_monitor *da_mon, model_get_event_name(event)); }#endif /* RV_MON_TYPE */ +#endif /* __BPF__ */ /* * da_event - handle an event for the da_mon
@@ -806,7 +817,7 @@ static inline bool da_handle_start_run_event(enum events event) return __da_handle_start_run_event(da_get_monitor(), event, 0); } -#elif RV_MON_TYPE == RV_MON_PER_TASK +#elif !defined(__BPF__) && RV_MON_TYPE == RV_MON_PER_TASK/* * Handle event for per task. */
@@ -847,7 +858,7 @@ static inline bool da_handle_start_run_event(struct task_struct *tsk, return __da_handle_start_run_event(da_get_monitor(tsk), event, tsk->pid); } -#elif RV_MON_TYPE == RV_MON_PER_OBJ +#elif !defined(__BPF__) && RV_MON_TYPE == RV_MON_PER_OBJ/* * Handle event for per object. */
tools/verification/models/nohz.dot new file +16 -0
@@ -0,0 +1,16 @@ +digraph state_automaton { + {node [shape = circle] "stopped"}; + {node [shape = plaintext, style=invis, label=""] "__init_running"}; + {node [shape = doublecircle] "running"}; + {node [shape = circle] "running"}; + "__init_running" -> "running"; + "stopped" [label = "stopped"]; + "stopped" -> "running" [ label = "tick_restart" ]; + "running" [label = "running"]; + "running" -> "running" [ label = "sched_tick" ]; + "running" -> "stopped" [ label = "tick_stop" ]; + { rank = min ; + "__init_running"; + "running"; + } +}
tools/verification/models/tqueue.dot new file +15 -0
@@ -0,0 +1,15 @@ +digraph state_automaton { + {node [shape = circle] "enqueued"}; + {node [shape = plaintext, style=invis, label=""] "__init_dequeued"}; + {node [shape = doublecircle] "dequeued"}; + {node [shape = circle] "dequeued"}; + "__init_dequeued" -> "dequeued"; + "enqueued" [label = "enqueued"]; + "enqueued" -> "dequeued" [ label = "sched_dequeue" ]; + "dequeued" [label = "dequeued"]; + "dequeued" -> "enqueued" [ label = "sched_enqueue" ]; + { rank = min ; + "__init_dequeued"; + "dequeued"; + } +}
tools/verification/rv/Makefile +39 -3
74 lines not on this page · raw message
tools/verification/rv/Makefile.config +26 -0
@@ -66,6 +66,32 @@ ifeq ($(BUILD_BPF),1) $(call lib_setup,bpf) endif +# Building BPF monitors requires clang and bpftool, RV with BPF monitors +# support can still run without building monitors +ifndef BUILD_BPF_OBJS + BUILD_BPF_OBJS := $(BUILD_BPF) +endif + +ifeq ($(BUILD_BPF_OBJS),1) + $(call feature_check,clang-bpf-co-re) + ifeq ($(feature-clang-bpf-co-re), 1) + $(call detected,CONFIG_CLANG_BPF_CO_RE) + else + $(info clang is missing or does not support BPF CO-RE, cannot build BPF monitors.) + $(info Please install clang) + BUILD_BPF_OBJS := 0 + endif + + $(call feature_check,bpftool-btf) + ifeq ($(feature-bpftool-btf), 1) + $(call detected,CONFIG_BPFTOOL_BTF) + else + $(info bpftool is missing or does not support btf, cannot build BPF monitors.) + $(info Please install bpftool) + BUILD_BPF_OBJS := 0 + endif +endif + ifeq ($(STOP_ERROR),1) $(error Please, check the errors above.) endif
tools/verification/rv/Makefile.rv +5 -0
@@ -33,12 +33,17 @@ INSTALL := install MKDIR := mkdir STRIP := strip BINDIR := /usr/bin +BPF_MON_DIR := /usr/share/rv/bpf_monitors .PHONY: install install: doc_install $(Q)$(MKDIR) -p $(DESTDIR)$(BINDIR) $(call QUIET_INSTALL,rv)$(INSTALL) $(OUTPUT)rv -m 755 $(DESTDIR)$(BINDIR) $(Q)@$(STRIP) $(DESTDIR)$(BINDIR)/rv +ifneq ($(wildcard bpf_monitors/*.o),) + $(Q)$(MKDIR) -p $(DESTDIR)$(BPF_MON_DIR) + $(call QUIET_INSTALL,bpf_monitors)$(INSTALL) bpf_monitors/*.o -m 644 $(DESTDIR)$(BPF_MON_DIR) +endif .PHONY: doc doc_clean doc_install doc:
tools/verification/rv/bpf_monitors/.gitignore new file +2 -0
@@ -0,0 +1,2 @@ +*.d +vmlinux.h
tools/verification/rv/bpf_monitors/da_monitor_bpf.h new file +368 -0
368 lines not on this page · raw message
tools/verification/rv/bpf_monitors/nohz.c new file +42 -0
42 lines not on this page · raw message
tools/verification/rv/bpf_monitors/nohz.h new file +49 -0
49 lines not on this page · raw message
tools/verification/rv/bpf_monitors/tqueue.c new file +30 -0
@@ -0,0 +1,30 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" + +#define RV_MON_TYPE RV_MON_PER_TASK +#include "tqueue.h" +#include <rv/da_monitor.h> +#define PF_EXITING 0x00000004 + +SEC("tp_btf/sched_dequeue_tp") +int BPF_PROG (handle_sched_dequeue ,struct task_struct *tsk,int cpu) +{ +if (!(BPF_CORE_READ (tsk, flags) &PF_EXITING )) +da_handle_start_event (tsk, sched_dequeue_tqueue); +return 0 ; +} + +SEC("tp_btf/sched_enqueue_tp") +int BPF_PROG (handle_sched_enqueue ,struct task_struct *tsk,int cpu) +{ +da_handle_event (tsk, sched_enqueue_tqueue); +return 0 ; +} + +static struct rv_monitor rv_this = { + .enabled =0 , +}; + +char LICENSE[] SEC("license") = "GPL"; +char DESCRIPTION[] SEC(".rodata.description") = "enqueue and dequeue tasks.";
tools/verification/rv/bpf_monitors/tqueue.h new file +47 -0
47 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] bpf: PER_TASK map leak via premature sched_process_exit cleanup --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] bpf: PER_TASK map leak via premature sched_process_exit cleanup --
commit 9e1db08be07757261ff0e098cd3dda05c445d860
Author: Gabriele Monaco <[email protected]>
tools/rv: Add BPF monitors
This commit adds the code for two initial BPF monitors (queue and nohz) and adapts the in-kernel da_monitor.h to share code and conditionally compile BPF or kernel-specific components. It also integrates BPF monitor building into the main rv Makefile.
Quoted 5 lines
tools/verification/rv/bpf_monitors/da_monitor_bpf.h new file +0
-0
[ ... ]
Quoted 15 lines
tools/verification/rv/bpf_monitors/da_monitor_bpf.h new file +15
-0+#if RV_MON_TYPE ==RV_MON_PER_TASK +/* +* BPF Per-Task monitor - uses BPF hash map indexed by PID +* +* Just a special case of per-object monitor with API consistent with in-kernel +* monitors (no need to pass the id). +*/ + +#define da_get_monitor (tsk) da_get_monitor_bpf(BPF_CORE_READ(tsk, pid), tsk) +#define da_handle_event (tsk, event) \ + da_handle_event_bpf(BPF_CORE_READ(tsk, pid), tsk, event) +#define da_handle_start_event (tsk, event) \ + da_handle_start_event_bpf(BPF_CORE_READ(tsk, pid), tsk, event) +#define da_handle_start_run_event (tsk, event) \ + da_handle_start_run_event_bpf(BPF_CORE_READ(tsk, pid), tsk, event)
tools/verification/rv/bpf_monitors/da_monitor_bpf.h line 157
Quoted 10 lines
tools/verification/rv/bpf_monitors/da_monitor_bpf.h new file +10
-0+ +typedef struct task_struct *monitor_target_bpf ; +static inline void da_destroy_storage (da_id_type id); + +SEC("tp_btf/sched_process_exit") +int BPF_PROG (handle_obj_cleanup ,struct task_struct *p,bool group_dead) +{ +da_destroy_storage (p->pid); +return 0 ; +}
[Severity: Medium]
Could this lead to a map leak if trace events occur during task teardown after sched_process_exit?
If an active PER_TASK monitor traces an event that occurs in do_exit() after sched_process_exit has already executed (for example, sched_dequeue, page faults, or other events in exit_mm() or schedule()), the event handler will call da_handle_start_event_bpf(). This function recreates the map element via da_create_storage().
Since handle_obj_cleanup has already run for this task, the newly recreated map element will never be deleted. Over time, this could exhaust the BPF map, and a future task reusing the same PID could inherit this stale automaton state.
Would it be safer to attach this cleanup routine to sched_process_free instead, ensuring the storage is only destroyed when the task struct is actually being freed?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=10
[email protected]
AI reviewRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
In reply to Gabriele MonacoTL;DR: - Possible rv build breakage: requires host kernel BTF, old libbpf/clang may lack likely() or -mcpu=v3 - Intentionally broken nohz monitor gets installed, changelog omits this - O= builds…
Quoted 1 line
tools/rv: Add BPF monitors
TL;DR:
- Possible rv build breakage: requires host kernel BTF, old libbpf/clang may lack likely() or -mcpu=v3
- Intentionally broken nohz monitor gets installed, changelog omits this
- O= builds write into source tree; install wildcard evaluated too early
Quoted 9 lines
tools/rv: Add BPF monitorsAdd the code for 2 initial BPF monitors, both DA (the only currently supported type):
* queue: per-task monitor stating tasks alternate enqueue and dequeue.
* nohz: per-cpu monitor stating the scheduler tick don't run when stopped and can run only after being resumed.
Quoted 8 lines
BPF monitors can include the in-kernel
da_monitor.h, which is now adapted to share as much common code and conditionally compile what needs to be BPF or kernel specific.Integrate BPF monitor building into main rv
Makefile, if all tools are available on the system.Signed-off-by Gabriele Monaco <[email protected]>
The changelog describes nohz as a monitor for a valid property, but nohz.c says the opposite:
tools/verification/rv/bpf_monitors/nohz.c:
/*
* This monitor is broken on purpose to test errors, sched_tick can run with
* stopped ticks for one last time (deferred tick reprogram).
...
*/
Should the changelog say that nohz is an intentionally broken test monitor?
The new install rule in Makefile.rv copies every bpf_monitors/*.o, so 'rv list' would show nohz to users as a normal monitor that is known to report false violations. A later patch in this series (f5a3c821fa88 "tools/rv: Add reactors support to BPF monitors") adds a panic reactor, so 'rv mon nohz -r panic' would panic on a known false positive.
Should nohz be kept out of the installed set or clearly marked as a test monitor?
Also, the first monitor is called 'queue' in the message but 'tqueue' in the code (MONITOR_NAME tqueue, tqueue.dot, tqueue.c).
Quoted 4 lines
include/rv/da_monitor.h +0
-0
[ ... ]
include/rv/da_monitor.h static struct rv_monitor rv_this; · line 88
Quoted 8 lines
include/rv/da_monitor.h +3
-0@@ -77,6 +82,9 @@ static struct rv_monitor rv_this;#define da_id_type int#endif +#ifdef __BPF__ +#include "da_monitor_bpf.h" +#else static void react (enum states curr_state,enum events event)
Can the BPF build find likely() and unlikely()?
The helpers in da_monitor.h that are now shared with BPF use them, for example in da_monitor_enabled():
if (unlikely(!rv_monitoring_on()))
return 0;The same applies to da_monitor_handling_event(), da_event() and the __da_handle_start*_event() helpers, plus the per-task and per-obj helpers in da_monitor_bpf.h.
Nothing in the BPF include path defines these macros. They are not in da_monitor_bpf.h or bpf_atomic.h, and vmlinux.h only has types. BPF_INCLUDES doesn't point at tools/lib, so <bpf/bpf_helpers.h> comes from the system libbpf, and libbpf only gained likely()/unlikely() in commit dafae1ae2ad3 ("libbpf: Add likely/unlikely macros and use them in selftests").
With libbpf 1.5 or older headers, compiling bpf_monitors/*.c fails with 'call to undeclared function unlikely'. The libbpf feature test only checks that libbpf links (bpf_prog_load), so BUILD_BPF_OBJS stays 1 and a plain 'make' of rv breaks.
Could da_monitor_bpf.h provide '#ifndef likely' fallbacks, or could Makefile.config check the libbpf version before enabling BUILD_BPF_OBJS?
No later patch in the series addresses this.
[ ... ]
Quoted 4 lines
tools/verification/rv/Makefile +0
-0
[ ... ]
Quoted 5 lines
tools/verification/rv/Makefile +1
-0@@ -68,19 +72,51 @@ static: $(RV_IN) $(eval LDFLAGS += -static) $(QUIET_LINK)$(CC) $(LDFLAGS) -o $(RV)-static $(RV_IN) $(EXTLIBS) +BPF_DIR := bpf_monitors
tools/verification/rv/Makefile static: $(RV_IN) · line 85
Quoted 10 lines
tools/verification/rv/Makefile +10
-0+BPF_SOURCES := $(wildcard $(BPF_DIR)/*.c) +BPF_OBJECTS := $(BPF_SOURCES:.c=.o) +VMLINUX_H := $(BPF_DIR)/vmlinux.h + +BPF_INCLUDES := -I$(srctree)/include/uapi +BPF_INCLUDES += -I$(srctree)/include +BPF_INCLUDES += -I$(BPF_DIR) + +BPF_CFLAGS := -g -O2 -target bpf -MMD -MP $(BPF_INCLUDES) +BPF_CFLAGS += -Wall -Wno-unused-function -Wno-missing-declarations
Do the BPF monitors need -mcpu=v3 here?
The shared da_monitor.h code that is now built for BPF calls try_cmpxchg() from da_event():
if (likely(try_cmpxchg(&da_mon->curr_state, &curr_state, next_state))) {bpf_atomic.h implements try_cmpxchg() with __sync_val_compare_and_swap() on the 32-bit 'unsigned int curr_state' of struct da_monitor. Documentation/bpf/clang-notes.rst says:
Clang can generate atomic instructions by default when -mcpu=v3 is enabled. If a lower version for -mcpu is set, the only atomic instruction Clang can generate is BPF_ADD *without* BPF_FETCH.
A clang whose default BPF CPU is older than v3 (LLVM before 20 defaulted to the v1 'generic' CPU) therefore cannot compile nohz.c or tqueue.c. Both reach da_event() through da_handle_start_event()/da_handle_event() -> __da_handle_event_common().
Those clang versions still pass the clang-bpf-co-re feature test, so BUILD_BPF_OBJS stays 1, 'all: bpf' is added, and a plain 'make' of tools/verification/rv fails where it succeeded before this patch.
Other in-tree BPF tools pass the flag explicitly, for example tools/sched_ext/Makefile uses '-O2 -mcpu=v3'. Could -mcpu=v3 be added to BPF_CFLAGS?
No later patch in the series changes this.
tools/verification/rv/Makefile static: $(RV_IN) · line 91
Quoted 6 lines
tools/verification/rv/Makefile +6
-0+ +VMLINUX := ../../../vmlinux +VMLINUX_BTF ?= $(if $(wildcard $(VMLINUX)) , $(VMLINUX), /sys/kernel/btf/vmlinux) + +$(VMLINUX_H): $(VMLINUX_BTF) + $(QUIET_GEN)$(SYSTEM_BPFTOOL) btf dump file $< format c > $@
Does the default rv build now depend on BTF from either the in-tree vmlinux or the build host's running kernel, with that BTF also needing to contain the RV types?
Makefile.config doesn't check either. The bpftool-btf feature test only runs 'bpftool btf help' and clang-bpf-co-re only checks the compiler, so BUILD_BPF_OBJS stays 1 and 'all: bpf' is added whenever the tools are installed.
Failure cases for 'make -C tools/verification/rv':
- No ../../../vmlinux and no /sys/kernel/btf/vmlinux (for example a chroot or container build, or a host kernel without CONFIG_DEBUG_INFO_BTF): make stops with "No rule to make target '/sys/kernel/btf/vmlinux', needed by 'bpf_monitors/vmlinux.h'".
- The BTF source is a kernel without CONFIG_RV: struct rv_monitor, struct da_monitor and union rv_task_monitor are missing from vmlinux.h, so 'static struct rv_monitor rv_this;' in da_monitor.h and the map value types in da_monitor_bpf.h fail to compile.
- The in-tree vmlinux was built without BTF: bpftool fails, but '> $@' has already created bpf_monitors/vmlinux.h. There is no .DELETE_ON_ERROR, so the empty header stays newer than vmlinux and later make runs keep failing until 'make clean'.
Before this patch, building rv did not depend on the build host's kernel at all. This also seems to contradict the commit message ("if all tools are available on the system") and the Makefile.config comment that RV can run without the monitors.
Should the BTF input (and possibly the RV types in it) be checked, falling back to BUILD_BPF_OBJS=0 the way the missing clang/bpftool cases already are?
No later patch in the series addresses this.
tools/verification/rv/Makefile static: $(RV_IN) · line 96
Quoted 5 lines
tools/verification/rv/Makefile +5
-0+ +$(BPF_DIR)/%.o: $(BPF_DIR)/%.c $(VMLINUX_H) + $(QUIET_CLANG)$(CLANG) $(BPF_CFLAGS) -c $< -o $@ + $(Q)$(LLVM_STRIP) -g $@ + $(Q)$(LLVM_OBJCOPY) --remove-section=.rel.rodata $@
Should these rules honour OUTPUT like the rest of this Makefile does (RV := $(OUTPUT)rv)?
With 'make O=/some/dir' or 'make -C tools O=... rv', the rv binary and its objects go to $(OUTPUT), but bpf_monitors/vmlinux.h, *.o and *.d are still written into the source tree. The build now writes into srctree and fails on a read-only source tree.
The objects also end up where rv cannot find them. bpf_fill_base_paths() in src/bpf_monitor.c overwrites the "." search entry with dirname(/proc/self/exe), i.e. $(OUTPUT), so rv looks for $(OUTPUT)/bpf_monitors, which doesn't exist. Freshly built monitors are not found in an O= build until they are installed.
Could the BPF objects and vmlinux.h be placed under $(OUTPUT)bpf_monitors/, with the install rule updated to match?
[ ... ]
Quoted 4 lines
tools/verification/rv/Makefile.rv +0
-0
[ ... ]
Quoted 1 line
tools/verification/rv/Makefile.rv +0
-0@@ -33,12 +33,17 @@ INSTALL := install
[ ... ]
tools/verification/rv/Makefile.rv INSTALL := install · line 46
Quoted 8 lines
install:
doc_installtools/verification/rv/Makefile.rv +4
-0$(Q)$(MKDIR) -p $(DESTDIR)$(BINDIR) $(call QUIET_INSTALL,rv)$(INSTALL) $(OUTPUT)rv -m 755 $(DESTDIR)$(BINDIR) $(Q)@$(STRIP) $(DESTDIR)$(BINDIR)/rv +ifneq ($(wildcard bpf_monitors/*.o),) + $(Q)$(MKDIR) -p $(DESTDIR)$(BPF_MON_DIR) + $(call QUIET_INSTALL,bpf_monitors)$(INSTALL) bpf_monitors/*.o -m 644 $(DESTDIR)$(BPF_MON_DIR) +endif
Is this ifneq/$(wildcard) check evaluated too early?
It runs when Makefile.rv is parsed (it is included from Makefile), not when the install recipe runs. In a single invocation such as 'make all install' (or 'make bpf install') on a clean tree, the wildcard is empty at parse time, so the BPF install lines are dropped from the recipe. The rv binary is installed but the monitors that were just built are silently skipped.
Would a shell-level test inside the recipe, for example 'if ls bpf_monitors/*.o >/dev/null 2>&1; then ...', be more robust?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
In reply to Gabriele MonacoOn Thu, Oct 01, 2026 at 05:20 PM Gabriele Monaco <[email protected]> wrote:
Overall looks much better.
Some of the code reimplements bpftool, but it's user space. It can be cleaned up later.
tools/verification/rv/Makefile static: $(RV_IN) · line 96
Quoted 4 lines
+$(BPF_DIR)/%.o: $(BPF_DIR)/%.c $(VMLINUX_H)
tools/verification/rv/Makefile +3
-0+ $(QUIET_CLANG)$(CLANG) $(BPF_CFLAGS) -c $< -o $@ + $(Q)$(LLVM_STRIP) -g $@ + $(Q)$(LLVM_OBJCOPY) --remove-section=.rel.rodata $@
What is this for?
Released libbpf ignores it with "skipping relo section" message. Removing the section only hides that some pointer in .rodata is left without relocation. What is it?
libbpf in bpf-next needs .rel.rodata to resolve pointers to functions. See commit b223044a68d5 ("libbpf: Resolve pointers to functions in read-only data").
tools/verification/rv/bpf_monitors/da_monitor_bpf.h line 179
Quoted 6 lines
tools/verification/rv/bpf_monitors/da_monitor_bpf.h new file +6
-0+struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 10240); + __type(key, da_id_type); + __type(value, struct da_monitor_storage_bpf); +} rv_mon_map SEC(".maps");
Why hash by pid?
Use BPF_MAP_TYPE_TASK_STORAGE for per-task monitors.
Once there are 10240 tasks bpf_map_update_elem() in da_create_storage() fails, the error is ignored, and the rest of the tasks are silently not monitored.
Task storage is freed with the task. No need for handle_obj_cleanup, id, target and PF_EXITING.
pw-bot: cr
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 5 lines · Alexei Starovoitov
On Thu, Oct 01, 2026 at 05:20 PM Gabriele Monaco <[email protected]> wrote:
Overall looks much better.
Some of the code reimplements bpftool, but it's user space. It can be cleaned up later.
Thanks for going through these.
Indeed I tried to reduce the code reimplementing these things but probably I can do better.
Quoted 11 lines
tools/verification/rv/Makefile static: $(RV_IN) · line 96
Quoted 4 lines
+$(BPF_DIR)/%.o: $(BPF_DIR)/%.c $(VMLINUX_H)
tools/verification/rv/Makefile +3
-0+ $(QUIET_CLANG)$(CLANG) $(BPF_CFLAGS) -c $< -o $@ + $(Q)$(LLVM_STRIP) -g $@ + $(Q)$(LLVM_OBJCOPY) --remove-section=.rel.rodata $@What is this for?
Released libbpf ignores it with "skipping relo section" message. Removing the section only hides that some pointer in .rodata is left without relocation. What is it? libbpf in bpf-next needs .rel.rodata to resolve pointers to functions. See commitb223044a68d5("libbpf: Resolve pointers to functions in read-only data").
Yeah indeed I used this to silence the warning. Apparently right now the warning is gone (no relocation section even if I don't trim it), but I went back to the initial version and it was about a bunch of .rodata.str1.1
I'm going to test a bit more but I can probably remove this.
Quoted 7 lines
tools/verification/rv/bpf_monitors/da_monitor_bpf.h line 179
Quoted 6 lines
tools/verification/rv/bpf_monitors/da_monitor_bpf.h new file +6
-0+struct { + __uint(type, BPF_MAP_TYPE_HASH); + __uint(max_entries, 10240); + __type(key, da_id_type); + __type(value, struct da_monitor_storage_bpf); +} rv_mon_map SEC(".maps");
Quoted 7 lines
Why hash by pid?
UseBPF_MAP_TYPE_TASK_STORAGEfor per-task monitors.
Once there are 10240 tasksbpf_map_update_elem()inda_create_storage()fails, the error is ignored, and the rest of the tasks are silently not monitored.
Task storage is freed with the task. No need forhandle_obj_cleanup, id, target andPF_EXITING.
Great, I wasn't aware of it and looks much neater. Will use that.
I couldn't catch you yesterday at the conference, but I can summarise here what I really wanted to ask you:
Reactors in this patch use bpf_printk(), which is in fact a trace_printk() instead of a real printk, is there a technical limitation forbidding us to create a kfunc using some flavour of printk_deferred()? Or am I missing an existing one? (this need was brought up by John, Cc'd here)
Not needed in this patch but potentially required for more complex monitors. In kernel, when timers are required, we allow monitors to use hrtimers (precise but heavy), or the timer_wheel (lightweight but less precise).
I'm not aware of any wrapper of the wheel in BPF, but I think a few kfuncs for these could be useful, in general, also for other programs needing a lot of timer instances or simply light timeouts.
What do you think?
Thanks,
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 4 lines · Gabriele Monaco
Reactors in this patch use
bpf_printk(), which is in fact atrace_printk()instead of a real printk, is there a technical limitation forbidding us to create a kfunc using some flavour ofprintk_deferred()? Or am I missing an existing one? (this need was brought up by John, Cc'd here)
No technical limitation, and there is no such kfunc today. printk_deferred() is a lockless store into the ring buffer plus irq_work. It's ok in any context where tracing progs run.
The closest we have is bpf_stream_vprintk(). That's stdout/stderr of the prog. User space has to read it.
rv tool is around for as long as the monitor is loaded, so it can read the stream and log it anywhere like /dev/kmsg.
If the message has to reach the console when user space cannot run then the kfunc makes sense, but using bpf_stream is imo much cleaner.
Quoted 7 lines
Not needed in this patch but potentially required for more complex monitors. In kernel, when timers are required, we allow monitors to use hrtimers (precise but heavy), or the
timer_wheel(lightweight but less precise).
I'm not aware of any wrapper of the wheel in BPF, but I think a few kfuncs for these could be useful, in general, also for other programs needing a lot of timer instances or simply light timeouts.
What do you think?
I don't think it's needed.bpf_timer is hrtimer only, but hrtimer vs wheel is not where the cost is. bpf_timer_start() cannot call hrtimer_start() directly. bpf_async_schedule_op() does kmalloc_nolock()
and irq_work_queue() instead.
I don't think timer wheel will help.
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 6 lines · Alexei Starovoitov
Quoted 4 lines · Gabriele Monaco
Reactors in this patch use
bpf_printk(), which is in fact atrace_printk()instead of a real printk, is there a technical limitation forbidding us to create a kfunc using some flavour ofprintk_deferred()? Or am I missing an existing one? (this need was brought up by John, Cc'd here)
Quoted 9 lines
No technical limitation, and there is no such kfunc today.
printk_deferred()is a lockless store into the ring buffer plusirq_work. It's ok in any context where tracing progs run.
The closest we have isbpf_stream_vprintk(). That's stdout/stderr of the prog. User space has to read it.
rv tool is around for as long as the monitor is loaded, so it can read the stream and log it anywhere like/dev/kmsg.
If the message has to reach the console when user space cannot run then the kfunc makes sense, but usingbpf_streamis imo much cleaner.
I am still not clear how the rv tool will replace the existing in-kernel implementation. Right now violations call printk(), which conveniently show up in kernel logs and consoles. More importantly, there are the rtapp violation events, which makes it very easy to use ftrace and perf features to record traces, take actions, generate statistics, and dump backtraces on violations.
Is it planned to pull all this out of the kernel but then somehow the rv tool allows ftrace, perf, and console to continue to work with violations? (For example, by somehow defining kprobes for violations and writing violation information to /dev/kmsg?) Or is the rv tool supposed to provide its own DIY variant of these features?
John Ogness
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Il 16 ottobre 2026 19:20:33 UTC, John Ogness <[email protected]> ha scritto:
Quoted 7 lines
I am still not clear how the rv tool will replace the existing in-kernel implementation. Right now violations call
printk(), which conveniently show up in kernel logs and consoles. More importantly, there are the rtapp violation events, which makes it very easy to use ftrace and perf features to record traces, take actions, generate statistics, and dump backtraces on violations.
The plan is to keep everything you'd now do with perf/ftrace as plain stdout of the RV tool. Right now you can see the same ftrace output using rv mon <monitor> -t for in-kernel monitors (only deterministic automata).
We are missing stack traces (which I'd optionally add only on errors) and perhaps other events (e.g. the -e in either tool if you aren't only interested in errors/events of the monitor).
Anything else you may want to do passes through reactors (e.g. printk/panic or others). See more later.
Quoted 5 lines
Is it planned to pull all this out of the kernel but then somehow the rv tool allows ftrace, perf, and console to continue to work with violations? (For example, by somehow defining kprobes for violations and writing violation information to
/dev/kmsg?) Or is the rv tool supposed to provide its own DIY variant of these features?
My plan isn't particularly strict right now. I'm aiming to allow BPF monitors in the user space tool as an exploratory effort. I don't think you would easily interact with ftrace/perf from those though.
If that's a requirement, you could probably call a kfunc from BPF and attach a kprobe there. I would implement that from a reactor (violations only).
For a pure printk reactor, I drafted an implementation that calls directly printk_deferred(), Alexei is suggesting to write to /dev/kmsg from user space what BPF passes.
Since you were the one suggesting having a real printk, would your use-case favour either solution? I'd expect some different latency if the log passes from BPF to /dev/kmsg , but I'm not sure that's an issue for you.
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 11 lines · Gabriele Monaco
Quoted 6 lines
I am still not clear how the rv tool will replace the existing in-kernel implementation. Right now violations call
printk(), which conveniently show up in kernel logs and consoles. More importantly, there are the rtapp violation events, which makes it very easy to use ftrace and perf features to record traces, take actions, generate statistics, and dump backtraces on violations.The plan is to keep everything you'd now do with perf/ftrace as plain stdout of the RV tool. Right now you can see the same ftrace output using rv mon <monitor> -t for in-kernel monitors (only deterministic automata).
IMHO it would be a pity to lose support for ftrace/perf. I use these tools extensively for my daily work evaluating real-time systems. Having the rtapp RVmon integrated allows me to easily and naturally extend my workflow to include rtapp violations. Plain stdout is hardly a replacement for trace recordings that can be imported into existing visualization and analysis tools.
Quoted 3 lines
We are missing stack traces (which I'd optionally add only on errors) and perhaps other events (e.g. the -e in either tool if you aren't only interested in errors/events of the monitor).
I don't see the point of reinventing tools that already do the job well. I do not mind if developers want to create their own tools that provide some small subset of existing features. But I am concerned about removing the in-kernel RV support for ftrace and perf.
Quoted 6 lines
Quoted 5 lines
Is it planned to pull all this out of the kernel but then somehow the rv tool allows ftrace, perf, and console to continue to work with violations? (For example, by somehow defining kprobes for violations and writing violation information to
/dev/kmsg?) Or is the rv tool supposed to provide its own DIY variant of these features?
Quoted 7 lines
My plan isn't particularly strict right now. I'm aiming to allow BPF monitors in the user space tool as an exploratory effort. I don't think you would easily interact with ftrace/perf from those though.
If that's a requirement, you could probably call a kfunc from BPF and attach a kprobe there. I would implement that from a reactor (violations only).
That sounds like it could work. As long as there are kprobes in the call stack of violations, I am happy.
Quoted 6 lines
For a pure printk reactor, I drafted an implementation that calls directly
printk_deferred(), Alexei is suggesting to write to/dev/kmsgfrom user space what BPF passes. Since you were the one suggesting having a real printk, would your use-case favour either solution? I'd expect some different latency if the log passes from BPF to/dev/kmsg, but I'm not sure that's an issue for you.
A delayed kernel record is better than none. Although I really do not see why it cannot simply call printk_deferred() directly. It is safe and lockless. And it has the advantage of appropriate timestamping when compared to any other printk's that may be happening at that time.
If we are already adding kfuncs for panics and violations, why the resistance to printks?
John
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 2 lines · John Ogness
That sounds like it could work. As long as there are kprobes in the call stack of violations, I am happy.
No need for a kfunc to get that.bpf_printk() in the reactor is a regular bpf_trace:bpf_trace_printk event, fired from the prog where the violation is detected. ftrace triggers and perf can attach to it.
Quoted 7 lines
A delayed kernel record is better than none. Although I really do not see why it cannot simply call
printk_deferred()directly. It is safe and lockless. And it has the advantage of appropriate timestamping when compared to any other printk's that may be happening at that time.If we are already adding kfuncs for panics and violations, why the resistance to printks?
printk kfunc wouldn't be limited to rv. Any tracing prog would be able to write to dmesg with no rate limit and then you, Petr and others will start yelling that bpf is abusing printk and dos-ing the rest of the kernel.
Hence let's avoid this can of worms.
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 7 lines · Alexei Starovoitov
Quoted 2 lines
That sounds like it could work. As long as there are kprobes in the call stack of violations, I am happy.
No need for a kfunc to get that.
bpf_printk()in the reactor is a regular bpf_trace:bpf_trace_printk event, fired from the prog where the violation is detected. ftrace triggers and perf can attach to it.
It would be nice if it could be filtered so that only RV violation bpf_printk's would trigger. I do not think it is possible for a filter to do primitive pattern matching on @bpf_string. Or am I wrong?
Quoted 5 lines
Quoted 5 lines
A delayed kernel record is better than none. Although I really do not see why it cannot simply call
printk_deferred()directly. It is safe and lockless. And it has the advantage of appropriate timestamping when compared to any other printk's that may be happening at that time.
Quoted 7 lines
Quoted 2 lines
If we are already adding kfuncs for panics and violations, why the resistance to printks?
printk kfunc wouldn't be limited to rv. Any tracing prog would be able to write to dmesg with no rate limit and then you, Petr and others will start yelling that bpf is abusing printk and dos-ing the rest of the kernel.
With the "new" ringbuffer and nbcon implementations, it no longer dos-es the kernel, so I have no problem with bpf programs calling printk_deferred(). And besides, userspace can already blast the ringbuffer and consoles via /dev/kmsg.
John
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 3 lines · John Ogness
It would be nice if it could be filtered so that only RV violation bpf_printk's would trigger. I do not think it is possible for a filter to do primitive pattern matching on @bpf_string. Or am I wrong?
not an ftrace expert, but it should be possible. bpf_string is a dynamic string field and filters take globs on those.
Quoted 4 lines
With the "new" ringbuffer and nbcon implementations, it no longer dos-es the kernel, so I have no problem with bpf programs calling
printk_deferred(). And besides, userspace can already blast the ringbuffer and consoles via/dev/kmsg.
well, /dev/kmsg is ratelimited unless printk.devkmsg=on, but the kfunc wouldn't be.
I still feel that bpf_stream + user space that writes into /dev/kmsg is a better design.
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 7 lines · Alexei Starovoitov
Quoted 3 lines · John Ogness
It would be nice if it could be filtered so that only RV violation bpf_printk's would trigger. I do not think it is possible for a filter to do primitive pattern matching on @bpf_string. Or am I wrong?
not an ftrace expert, but it should be possible.
bpf_stringis a dynamic string field and filters take globs on those.
Yes, indeed this works. Thanks for mentioning the globs.
Quoted 9 lines
Quoted 4 lines
With the "new" ringbuffer and nbcon implementations, it no longer dos-es the kernel, so I have no problem with bpf programs calling
printk_deferred(). And besides, userspace can already blast the ringbuffer and consoles via/dev/kmsg.well,
/dev/kmsgis ratelimited unless printk.devkmsg=on, but the kfunc wouldn't be.
I still feel thatbpf_stream+ user space that writes into/dev/kmsgis a better design.
My issue with the /dev/kmsg design is bogus timestamps. But let's just drop my suggestion to allow eBPF programs to call printk(). Since the RV move to eBPF will require new user workflows anyway, the users will need to learn these new packages, tools, and output sources. The important thing (for me) is RV violations can still be used effectively with ftrace/perf, which they can (using globs in bpf_trace:bpf_trace_printk filters).
@gmonaco: There should be clean glob-friendly RV bpf_trace_printk strings so that filters can be easily and reliably set up.
John
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 7 lines · John Ogness
My issue with the
/dev/kmsgdesign is bogus timestamps. But let's just drop my suggestion to allow eBPF programs to callprintk(). Since the RV move to eBPF will require new user workflows anyway, the users will need to learn these new packages, tools, and output sources. The important thing (for me) is RV violations can still be used effectively with ftrace/perf, which they can (using globs in bpf_trace:bpf_trace_printk filters).
Alright, I'll focus on trace_printk for now. As I said, it's rather trivial to add another reactor later.
Quoted 2 lines
@gmonaco: There should be clean glob-friendly RV
bpf_trace_printkstrings so that filters can be easily and reliably set up.
If I leave the LTL header unmodified, you'd get something like:
rv: sleep: <comm>[<pid>] violation detected
It should be glob-friendly enough, but I'll try it out.
I wonder if string matching brings additional overhead (trace_printk itself does, if I recall correctly), but that's probably rather minor.
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 8 lines · Gabriele Monaco
Quoted 2 lines
@gmonaco: There should be clean glob-friendly RV
bpf_trace_printkstrings so that filters can be easily and reliably set up.If I leave the LTL header unmodified, you'd get something like:
rv: sleep: <comm>[<pid>] violation detected
It should be glob-friendly enough, but I'll try it out.
If transition-events will also be included (should be optional for performance reasons), a better format may be:
rv: violation: sleep: <comm>[<pid>] <violation text>
rv: event: sleep: <comm>[<pid>] <event text>
Quoted 2 lines
I wonder if string matching brings additional overhead (
trace_printkitself does, if I recall correctly), but that's probably rather minor.
For production environments, I expect that trace_printk's are only occurring for violations, in which case the cost of a string compare will probably be irrelevant.
Are these trace_printk's available without getting the scary kernel warning when kernel code uses trace_printk()? We do want RV support to be enabled in production kernels.
John
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 11 lines · John Ogness
For production environments, I expect that trace_printk's are only occurring for violations, in which case the cost of a string compare will probably be irrelevant.
Are these trace_printk's available without getting the scary kernel warning when kernel code uses
trace_printk()? We do want RV support to be enabled in production kernels.John
Since commit ac5a72ea5c89 ("bpf: Use dedicated bpf_trace_printk event instead of trace_printk()"), bpf_trace_printk() does not use trace_printk(). Rather, it is recorded as a separate ftrace event that has to be enabled, in /sys/kernel/tracing/events/bpf_trace/bpf_trace_printk, for each instance that wants to trace it, and using it does not print any warnings into dmesg.
The BPF documentation says otherwise [1]:
"bpf_trace_printk() is slow, and should only be used for debugging purposes. For this reason, a notice block (spanning several lines) is printed to kernel logs and states that the helper should not be used "for production use" the first time this helper is used (or more precisely, when trace_printk() buffers are allocated). For passing values to user space, perf events should be preferred."
[1] https://docs.ebpf.io/linux/helper-function/bpf_trace_printk/
but that is clearly outdated.
Tomas
Steven Rostedt
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
In reply to John OgnessQuoted 3 lines · On Mon, 19 Oct 2026 11:33:56 +0206 John Ogness <[email protected]>…
Are these trace_printk's available without getting the scary kernel warning when kernel code uses
trace_printk()? We do want RV support to be enabled in production kernels.
Note that if internal tooling uses their own trace instance, there's a trace_array_printk() that takes the instance as a parameter and acts just like trace_printk(). The difference is that it cannot be used for the top level instance and it doesn't cause any scary kernel messages.
-- Steve
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
In reply to Gabriele MonacoQuoted 4 lines · Gabriele Monaco
Alright, I'll focus on
trace_printkfor now. As I said, it's rather trivial to add another reactor later.
One disadvantage of using bpf_trace_printk() for RV violation reporting is that the event will be caught by every instance that enables bpf_trace_printk() and does not explicitly filter rv out.
I can imagine an RV-specific trace event for that, however, it would require a separate kfunc to generate it, and ideally also distinct labeling of a BPF program eligible to call that kfunc. The "rv" userspace tool could then iterate over these labels so the user knows which violation events can be expected to occur on the system.
Tomas
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 9 lines
Since commit
ac5a72ea5c89("bpf: Use dedicatedbpf_trace_printkevent instead oftrace_printk()"),bpf_trace_printk()does not usetrace_printk(). Rather, it is recorded as a separate ftrace event that has to be enabled, in/sys/kernel/tracing/events/bpf_trace/bpf_trace_printk, for each instance that wants to trace it, and using it does not print any warnings into dmesg.The BPF documentation says otherwise [1]:
Thanks Tomas! I noticed the banner was not displayed and I was puzzled. You saved me an LLM iteration that would have probably be puzzled by the comment too..
Quoted 3 lines
One disadvantage of using
bpf_trace_printk()for RV violation reporting is that the event will be caught by every instance that enablesbpf_trace_printk()and does not explicitly filter rv out.
Yes, that should somewhat be mitigated by the glob filter, though events are still generated.
Quoted 5 lines
I can imagine an RV-specific trace event for that, however, it would require a separate kfunc to generate it, and ideally also distinct labeling of a BPF program eligible to call that kfunc. The "rv" userspace tool could then iterate over these labels so the user knows which violation events can be expected to occur on the system.
That'd work too. It's what I initially envisioned but I'm not sure a kfunc producing a tracepoint is something BPF folks would really like (and technically any other unrelated BPF program could call that, unless there's some access control mechanism I'm not aware of).
Not sure how much it matters in practice against the glob filter, it probably really depends on the other bpf_printk users (and a mildly better usability).
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 8 lines · Gabriele Monaco
Quoted 4 lines
One disadvantage of using
bpf_trace_printk()for RV violation reporting is that the event will be caught by every instance that enablesbpf_trace_printk()and does not explicitly filter rv out.Yes, that should somewhat be mitigated by the glob filter, though events are still generated.
Do I understand it correctly that the idea is to modify existing tracefs instances when enabling an RV monitor to filter our RV-related bpf_trace_printk events?
Quoted 6 lines
Quoted 5 lines
I can imagine an RV-specific trace event for that, however, it would require a separate kfunc to generate it, and ideally also distinct labeling of a BPF program eligible to call that kfunc. The "rv" userspace tool could then iterate over these labels so the user knows which violation events can be expected to occur on the system.
Quoted 8 lines
That'd work too. It's what I initially envisioned but I'm not sure a kfunc producing a tracepoint is something BPF folks would really like (and technically any other unrelated BPF program could call that, unless there's some access control mechanism I'm not aware of).
Not sure how much it matters in practice against the glob filter, it probably really depends on the other
bpf_printkusers (and a mildly better usability).
bpf_trace_printk is already a BPF helper producing a tracepoint, this would be equivalent. Of course, that does not mean we want it, but it is something we already have in at least one instance. I know of at least one quirk: you can have a BPF program attached to a tracepoint that will call bpf_trace_printk(), and a tracefs instance tracing both bpf_trace_printk() and the original tracepoint. That leads to a new tracepoint triggering while another tracepoint is already in progress. I don't know how it is currently handled; from what I recall when testing RTLA's BPF actions, the bpf_trace_printk() event might get dropped by the tracefs instance, so I had to use a different way to signal to userspace in BPF actions test.
As I said, to prevent unrelated BPF programs from calling the new tracepoint, you'd need to recognize and track RV BPF programs as a special type of program, similarly to what your original RFC did. I'm not sure if that's what we want, but I see some advantages. In addition to better filtering of reactor events, you could separate reactors from the monitors entirely: you could trigger the tracepoint unconditionally, and attach reactors as tracepoint triggers to the new tracepoint.
All of that adds complexity, though, and requires separate discussion, so it's probably not something relevant for the initial implementation. I just wanted to mention it so that it doesn't get lost.
Tomas
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 6 lines · Tomas Glozar
Quoted 5 lines · Gabriele Monaco
Quoted 4 lines
One disadvantage of using
bpf_trace_printk()for RV violation reporting is that the event will be caught by every instance that enablesbpf_trace_printk()and does not explicitly filter rv out.
Quoted 7 lines
Quoted 3 lines
Yes, that should somewhat be mitigated by the glob filter, though events are still generated.
Do I understand it correctly that the idea is to modify existing tracefs instances when enabling an RV monitor to filter our RV-related
bpf_trace_printkevents?
Not quite. The initial issue is that the current iteration of RV BPF monitor don't cooperate well with trace-cmd/perf. Alexei suggested we use bpf_printk and filter out the desired events with plain ftrace glob filters (from trace- cmd/perf).
I believe this would be usually equivalent to having a dedicated tracepoint for RV BPF monitors.
E.g. you'd do (roughly):
trace-cmd -e bpf_prink --filter 'bpf_string ~ "rv: sleep: * violation"
instead of (with a new kfunc)
trace-cmd -e rv:error_bpf --filter 'monitor = "sleep"'
Now, I didn't try either way and don't know what implications there are either way (you seem to know better about this).
Quoted 12 lines
Quoted 12 lines
Quoted 5 lines
I can imagine an RV-specific trace event for that, however, it would require a separate kfunc to generate it, and ideally also distinct labeling of a BPF program eligible to call that kfunc. The "rv" userspace tool could then iterate over these labels so the user knows which violation events can be expected to occur on the system.
That'd work too. It's what I initially envisioned but I'm not sure a kfunc producing a tracepoint is something BPF folks would really like (and technically
any other unrelated BPF program could call that, unless there's some access control mechanism I'm not aware of).
Quoted 8 lines
Quoted 5 lines
Not sure how much it matters in practice against the glob filter, it probably
really depends on the otherbpf_printkusers (and a mildly better usability).
bpf_trace_printkis already a BPF helper producing a tracepoint, this would be equivalent.
Fair point.
Quoted 11 lines
Of course, that does not mean we want it, but it
is something we already have in at least one instance. I know of at least one quirk: you can have a BPF program attached to a tracepoint that will callbpf_trace_printk(), and a tracefs instance tracing bothbpf_trace_printk()and the original tracepoint. That leads to a new tracepoint triggering while another tracepoint is already in progress. I don't know how it is currently handled; from what I recall when testing RTLA's BPF actions, thebpf_trace_printk()event might get dropped by the tracefs instance, so I had to use a different way to signal to userspace in BPF actions test.
Quoted 4 lines
As I said, to prevent unrelated BPF programs from calling the new tracepoint, you'd need to recognize and track RV BPF programs as a special type of program, similarly to what your original RFC did. I'm not sure if that's what we want, but I see some advantages.
Yeah, this last step is probably something we don't want.
Although it may not be such a bad thing: if we require enough privileges to trigger this tracepoint, then the worst we get is root trying to mess up with monitoring, where it could easily mess up with everything else already. But it definitely needs more thinking.
Quoted 4 lines
In addition to better filtering of reactor events, you could separate reactors from the monitors entirely: you could trigger the tracepoint unconditionally, and attach reactors as tracepoint triggers to the new tracepoint.
Something like this was already brought up actually and isn't a bad idea, it has its strengths and issues but would somewhat work in-kernel as well. But as you said, that's a bigger reactor refactoring and beyond the scope of this submission.
Thanks,
Gabriele
Quoted 7 lines
All of that adds complexity, though, and requires separate discussion, so it's probably not something relevant for the initial implementation. I just wanted to mention it so that it doesn't get lost.
Tomas
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 13 lines · Gabriele Monaco
Quoted 4 lines
Do I understand it correctly that the idea is to modify existing tracefs instances when enabling an RV monitor to filter our RV-related
bpf_trace_printkevents?Not quite. The initial issue is that the current iteration of RV BPF monitor don't cooperate well with trace-cmd/perf. Alexei suggested we use
bpf_printkand filter out the desired events with plain ftrace glob filters (from trace- cmd/perf).I believe this would be usually equivalent to having a dedicated tracepoint for RV BPF monitors.
Quoted 8 lines
E.g. you'd do (roughly):
trace-cmd -e bpf_prink --filter 'bpf_string ~ "rv: sleep: * violation"instead of (with a new kfunc)
trace-cmd -e rv:error_bpf --filter 'monitor = "sleep"'
I was talking about preventing other (non-RV) consumers of bpf_trace_printk from seeing the RV prints. Eg. if I create a tracefs instance and enable bpf_trace_printk, intending to see my own debug prints, I will also see debug prints for RV, unless I explicitly filter them out. I get that on the RV side, these are mostly equivalent.
Tomas
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 6 lines · Tomas Glozar
I was talking about preventing other (non-RV) consumers of
bpf_trace_printkfrom seeing the RV prints. Eg. if I create a tracefs instance and enablebpf_trace_printk, intending to see my own debug prints, I will also see debug prints for RV, unless I explicitly filter them out. I get that on the RV side, these are mostly equivalent.
I haven't used BPF before, but is that not an RV-specific problem? If user has two BPF programs running that both do bpf_trace_printk, obviously they get mixed prints. They can either filter out other prints, or stop running the other one.
Additionally an RV message only appears when something is wrong. So when there is an RV print, there is a bigger problem to worry about.
Nam
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
In reply to Tomas GlozarQuoted 3 lines · Tomas Glozar
Do I understand it correctly that the idea is to modify existing tracefs instances when enabling an RV monitor to filter our RV-related
bpf_trace_printkevents?
Not necessarily. But does the ordering matter? If I run:
$ sudo trace-cmd record -e bpf_trace:bpf_trace_printk \
-f 'bpf_string ~ "rv: violation: *"'it does not matter if the instance is running before or after starting the monitor.
Quoted 14 lines
Quoted 6 lines
Quoted 5 lines
I can imagine an RV-specific trace event for that, however, it would require a separate kfunc to generate it, and ideally also distinct labeling of a BPF program eligible to call that kfunc. The "rv" userspace tool could then iterate over these labels so the user knows which violation events can be expected to occur on the system.
Quoted 7 lines
That'd work too. It's what I initially envisioned but I'm not sure a kfunc producing a tracepoint is something BPF folks would really like (and technically any other unrelated BPF program could call that, unless there's some access control mechanism I'm not aware of).
Not sure how much it matters in practice against the glob filter, it probably really depends on the other
bpf_printkusers (and a mildly better usability).
Quoted 11 lines
bpf_trace_printkis already a BPF helper producing a tracepoint, this would be equivalent. Of course, that does not mean we want it, but it is something we already have in at least one instance. I know of at least one quirk: you can have a BPF program attached to a tracepoint that will callbpf_trace_printk(), and a tracefs instance tracing bothbpf_trace_printk()and the original tracepoint. That leads to a new tracepoint triggering while another tracepoint is already in progress. I don't know how it is currently handled; from what I recall when testing RTLA's BPF actions, thebpf_trace_printk()event might get dropped by the tracefs instance, so I had to use a different way to signal to userspace in BPF actions test.
This is interesting because it is very likely that the RV monitor is attaching to and generating the violation from the same tracepoints that I may be additionally tracing. For example, the sleep RV monitor attaches to sched_waking, which I would also use while investigating my broken real-time system.
However, I just ran a test with a simple eBPF program that attaches to a tracepoint and calls bpf_trace_printk(). I started trace-cmd to trace both the attach tracepoint and also bpf_trace_printk using a glob. After starting trace-cmd, I loaded/attached the eBPF program. The running trace-cmd was able to capture both events (with about 15us difference in timestamp).
Quoted 8 lines
As I said, to prevent unrelated BPF programs from calling the new tracepoint, you'd need to recognize and track RV BPF programs as a special type of program, similarly to what your original RFC did. I'm not sure if that's what we want, but I see some advantages. In addition to better filtering of reactor events, you could separate reactors from the monitors entirely: you could trigger the tracepoint unconditionally, and attach reactors as tracepoint triggers to the new tracepoint.
Thank you for making this suggestion. This is the direction I would prefer we take.
Quoted 4 lines
All of that adds complexity, though, and requires separate discussion, so it's probably not something relevant for the initial implementation. I just wanted to mention it so that it doesn't get lost.
Since relocating RV to userspace requires an enormous amount of effort and coordination (mainlining, packaging, distributions, documentation), I do not think it makes sense to have an "initial implementation" that is already not what we want in the long term.
John
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 5 lines · John Ogness
Quoted 3 lines · Tomas Glozar
Do I understand it correctly that the idea is to modify existing tracefs instances when enabling an RV monitor to filter our RV-related
bpf_trace_printkevents?
Quoted 7 lines
Not necessarily. But does the ordering matter? If I run:
$ sudo trace-cmd record -e bpf_trace:bpf_trace_printk \ -f 'bpf_string ~ "rv: violation: *"'it does not matter if the instance is running before or after starting the monitor.
I'm not sure if that was a question, but I don't think it would matter either way. If RV generates it's own events, these exist even before the monitor runs (just like bpf_printk) so it doesn't really matter when ftrace attaches to them.
Quoted 14 lines
Quoted 14 lines
Quoted 14 lines
Quoted 6 lines
I can imagine an RV-specific trace event for that, however, it would require a separate kfunc to generate it, and ideally also distinct labeling of a BPF program eligible to call that kfunc. The "rv" userspace tool could then iterate over these labels so the user knows which violation events can be expected to occur on the system.
That'd work too. It's what I initially envisioned but I'm not sure a kfunc producing a tracepoint is something BPF folks would really like (and technically
any other unrelated BPF program could call that, unless there's some access
control mechanism I'm not aware of).
Quoted 7 lines
Quoted 7 lines
Quoted 4 lines
Not sure how much it matters in practice against the glob filter, it probably
really depends on the otherbpf_printkusers (and a mildly better usability).
bpf_trace_printkis already a BPF helper producing a tracepoint, this would be equivalent.
By the way, there are other occurrences in the kernel, apparently used only for testing in include/trace/events/bpf_test_run.h
Quoted 11 lines
Quoted 10 lines
Of course, that does not mean we want it, but it
is something we already have in at least one instance. I know of at least one quirk: you can have a BPF program attached to a tracepoint that will callbpf_trace_printk(), and a tracefs instance tracing bothbpf_trace_printk()and the original tracepoint. That leads to a new tracepoint triggering while another tracepoint is already in progress. I don't know how it is currently handled; from what I recall when testing RTLA's BPF actions, thebpf_trace_printk()event might get dropped by the tracefs instance, so I had to use a different way to signal to userspace in BPF actions test.
Quoted 5 lines
This is interesting because it is very likely that the RV monitor is attaching to and generating the violation from the same tracepoints that I may be additionally tracing. For example, the sleep RV monitor attaches to
sched_waking, which I would also use while investigating my broken real-time system.
Yes, that's actually what standard RV has always been doing, I've never noticed dropped tracepoints.
I thought bpf_printk used some shared buffers or some other things on top of that but it doesn't seem to have anything but a tracepoint string.
Quoted 25 lines
However, I just ran a test with a simple eBPF program that attaches to a tracepoint and calls
bpf_trace_printk(). I started trace-cmd to trace both the attach tracepoint and alsobpf_trace_printkusing a glob. After starting trace-cmd, I loaded/attached the eBPF program. The running trace-cmd was able to capture both events (with about 15us difference in timestamp).Quoted 8 lines
As I said, to prevent unrelated BPF programs from calling the new tracepoint, you'd need to recognize and track RV BPF programs as a special type of program, similarly to what your original RFC did. I'm not sure if that's what we want, but I see some advantages. In addition to better filtering of reactor events, you could separate reactors from the monitors entirely: you could trigger the tracepoint unconditionally, and attach reactors as tracepoint triggers to the new tracepoint.
Thank you for making this suggestion. This is the direction I would prefer we take.
Quoted 4 lines
All of that adds complexity, though, and requires separate discussion, so it's probably not something relevant for the initial implementation. I just wanted to mention it so that it doesn't get lost.
Quoted 4 lines
Since relocating RV to userspace requires an enormous amount of effort and coordination (mainlining, packaging, distributions, documentation), I do not think it makes sense to have an "initial implementation" that is already not what we want in the long term.
Fair enough, I feel to be cautious at redefining what reactors are right now, though. Currently they are nothing but a function call to the set-up action. It's trivial to verify where the code goes without adding the tracing subsystem as a dependency in the path (typically important in some safety critical cases). Sure, handlers are called by the same tracing subsystem nonetheless, so it may not add much value.
Let's leave reactors aside for a moment. What I am coming to terms with, instead, is that the current ringbuffer to userspace design isn't what we want. In kernel monitors communicate their status through tracepoints, perfectly integrating to tracing tools, BPF monitors use a custom buffer.
Generating a tracepoint here is probably the way to go. bpf_printk does generate one, but as Tomas pointed out, hijacking that for everything (think of monitor events) might be a bit much.
Nonetheless, we want RV BPF handlers to generate tracepoints, then attaching actions on error tracepoints (whether we call that reactors or not) can be done later.
Summarising, we have 2 potential designs.
1. bpf_printk only:
bpf_printk("event: monitor: curr_state x event -> next_state") bpf_printk("error: monitor: event not expected in curr_state")
2. new kfunc(s) calling a tracepoint:
trace_event_da_bpf("monitor", "curr_state", "event", "next_state") trace_error_da_bpf("monitor", "curr_state", "event")
1. is simpler and works mostly out of the box, depending on how powerful glob filters are, it can reach the same functionality as 2. Might risk to overload the shared bpf_printk event and perhaps have a higher filtering overhead.
2. is closest to the current in-kernel implementation and offers flexibility to easily filter the type of event (useful for DA, e.g. I want a backtrace only when going from state A to B). But it requires a series of kfuncs (e.g. error and event for each monitor class).
In both cases a malicious actor could call the kfunc and make us believe there was a reaction (they cannot mess with the model though). If we own the kfuncs we can at least limit the availability (tracing-only and CAP_SYS_BOOT). This, unless we register BPF monitors in the kernel like in V1.
I'm going to test each design once I get again to work on this.
Thoughts?
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 6 lines · Gabriele Monaco
Fair enough, I feel to be cautious at redefining what reactors are right now, though. Currently they are nothing but a function call to the set-up action. It's trivial to verify where the code goes without adding the tracing subsystem as a dependency in the path (typically important in some safety critical cases). Sure, handlers are called by the same tracing subsystem nonetheless, so it may not add much value.
I am thinking about dropping reactors entirely and only use bpf_printk. I have never been a fan of the panic reactor, crashing the system because of an RV violation is a bit much. And the printk reactor would be replaced by bpf_printk, just that the messages would be in tracing ring buffer instead of kernel log.
Or do you already have potential future reactors in mind?
Quoted 30 lines
Let's leave reactors aside for a moment. What I am coming to terms with, instead, is that the current ringbuffer to userspace design isn't what we want. In kernel monitors communicate their status through tracepoints, perfectly integrating to tracing tools, BPF monitors use a custom buffer.
Generating a tracepoint here is probably the way to go.
bpf_printkdoes generate one, but as Tomas pointed out, hijacking that for everything (think of monitor events) might be a bit much.
Nonetheless, we want RV BPF handlers to generate tracepoints, then attaching actions on error tracepoints (whether we call that reactors or not) can be done later.Summarising, we have 2 potential designs.
1.
bpf_printkonly:
bpf_printk("event: monitor: curr_state x event -> next_state")bpf_printk("error: monitor: event not expected in curr_state")2. new kfunc(s) calling a tracepoint:
trace_event_da_bpf("monitor", "curr_state", "event", "next_state")trace_error_da_bpf("monitor", "curr_state", "event")1. is simpler and works mostly out of the box, depending on how powerful glob filters are, it can reach the same functionality as 2. Might risk to overload the shared
bpf_printkevent and perhaps have a higher filtering overhead.
2. is closest to the current in-kernel implementation and offers flexibility to easily filter the type of event (useful for DA, e.g. I want a backtrace only when going from state A to B). But it requires a series of kfuncs (e.g. error and event for each monitor class).
Quoted 8 lines
In both cases a malicious actor could call the kfunc and make us believe there was a reaction (they cannot mess with the model though). If we own the kfuncs we can at least limit the availability (tracing-only and
CAP_SYS_BOOT). This, unless we register BPF monitors in the kernel like in V1.I'm going to test each design once I get again to work on this.
Thoughts?
I vote 1, much simpler (but maybe I just haven't quite got the issue). I feel a bit ensure about adding RV kfuncs and would only go that route if there is no other way.
Nam
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 12 lines · Nam Cao
Quoted 10 lines · Gabriele Monaco
Fair enough, I feel to be cautious at redefining what reactors are right now,
though. Currently they are nothing but a function call to the set-up action. It's trivial to verify where the code goes without adding the tracing subsystem
as a dependency in the path (typically important in some safety critical cases).
Sure, handlers are called by the same tracing subsystem nonetheless, so it may
not add much value.
Quoted 5 lines
I am thinking about dropping reactors entirely and only use
bpf_printk. I have never been a fan of the panic reactor, crashing the system because of an RV violation is a bit much. And the printk reactor would be replaced bybpf_printk, just that the messages would be in tracing ring buffer instead of kernel log.
The panic reactor comes from the functional safety use case, imagine a system with redundancy where the linux system is compromised by a violation, the only safe state is to shut it down (with all vmcores and stack traces panic gives you) and continue in emergency mode.
Right now that's still a potential use-case, no one that I know is using RV in that context for a few other reasons.
I wouldn't completely drop reactors. That is, we can avoid implementing them in BPF, but I wouldn't take design choices making them impossible in the future (nothing occurred so far).
Quoted 3 lines
Or do you already have potential future reactors in mind?
Well, I have a lot of ideas, not many requests so far ;)
I think of reactors whenever people want to integrate exotic things to RV.
Actions tied to the error tracepoints (what Tomas suggested, and I think you or ThomasW also mentioned in the past) would probably work in many use-cases.
This doesn't affect the design, we'd still need something making tracepoints.
Quoted 45 lines
Quoted 45 lines
Let's leave reactors aside for a moment. What I am coming to terms with, instead, is that the current ringbuffer to userspace design isn't what we want.
In kernel monitors communicate their status through tracepoints, perfectly integrating to tracing tools, BPF monitors use a custom buffer.Generating a tracepoint here is probably the way to go.
bpf_printkdoes generate
one, but as Tomas pointed out, hijacking that for everything (think of monitor
events) might be a bit much.
Nonetheless, we want RV BPF handlers to generate tracepoints, then attaching actions on error tracepoints (whether we call that reactors or not) can be done
later.Summarising, we have 2 potential designs.
1.
bpf_printkonly:
bpf_printk("event: monitor: curr_state x event -> next_state")bpf_printk("error: monitor: event not expected in curr_state")2. new kfunc(s) calling a tracepoint:
trace_event_da_bpf("monitor", "curr_state", "event", "next_state")trace_error_da_bpf("monitor", "curr_state", "event")1. is simpler and works mostly out of the box, depending on how powerful glob
filters are, it can reach the same functionality as 2. Might risk to overload
the sharedbpf_printkevent and perhaps have a higher filtering overhead.
2. is closest to the current in-kernel implementation and offers flexibility to
easily filter the type of event (useful for DA, e.g. I want a backtrace only when going from state A to B). But it requires a series of kfuncs (e.g. error
and event for each monitor class).In both cases a malicious actor could call the kfunc and make us believe there
was a reaction (they cannot mess with the model though). If we own the kfuncs we
can at least limit the availability (tracing-only andCAP_SYS_BOOT). This, unless we register BPF monitors in the kernel like in V1.
Quoted 7 lines
Quoted 3 lines
I'm going to test each design once I get again to work on this.
Thoughts?
I vote 1, much simpler (but maybe I just haven't quite got the issue). I feel a bit ensure about adding RV kfuncs and would only go that route if there is no other way.
We can go down that route and see how it behaves.
Thanks,
Gabriele
Steven Rostedt
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 5 lines · On Wed, 21 Oct 2026 13:54:04 +0200 Gabriele Monaco <[email protected]> wrote:
Quoted 3 lines
I vote 1, much simpler (but maybe I just haven't quite got the issue). I feel a bit ensure about adding RV kfuncs and would only go that route if there is no other way.
We can go down that route and see how it behaves.
BTW, I'm curious if it isn't possible to keep both in-kernel and BPF monitors? That is, for those cases that do not change often and has a well known model, to simply keep those as modules and hard coded.
But this entire thread started with people that wanted BPF type of monitors for more flexibility. I would argue that is an entirely separate use case. For them, it should be a fully BPF solution, with a few hooks into the RV infrastructure.
It currently is a big unknown if the BPF solution can handle all the use cases of the current module method. My suggestion is to not try to do so. Keep the module method for the more static use cases that do not need dynamic changes. And create a purely BPF method for those that need BPF.
This thread is sounding like there's different requirements between the BPF and module methods. If that's the case, let's keep them separate.
I agree with Alexei's first comment about not adding BPF to the module method. But that doesn't mean we need to eliminate the module method completely in order to use BPF. Instead, just create a new BPF pure method.
Perhaps in the future the BPF method may make the module method obsolete, but I don't want users of the module method having to do all these workarounds just to satisfy the BPF method while it is in development.
-- Steve
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 3 lines · Steven Rostedt
BTW, I'm curious if it isn't possible to keep both in-kernel and BPF monitors? That is, for those cases that do not change often and has a well known model, to simply keep those as modules and hard coded.
In my opinion it is possible and I'm designing every change with that coexistence in mind.
I would say we could only drop in-kernel if BPF does such a great job to cover every single technical and non-technical requirement or use-case, AND if it makes maintaining the whole thing easier.
But I'd like both to be fully ready upstream before taking that decision, though I'm getting more and more sceptical.
Quoted 13 lines
But this entire thread started with people that wanted BPF type of monitors for more flexibility. I would argue that is an entirely separate use case. For them, it should be a fully BPF solution, with a few hooks into the RV infrastructure.
It currently is a big unknown if the BPF solution can handle all the use cases of the current module method. My suggestion is to not try to do so. Keep the module method for the more static use cases that do not need dynamic changes. And create a purely BPF method for those that need BPF.
This thread is sounding like there's different requirements between the BPF and module methods. If that's the case, let's keep them separate.
Quoted 7 lines
I agree with Alexei's first comment about not adding BPF to the module method. But that doesn't mean we need to eliminate the module method completely in order to use BPF. Instead, just create a new BPF pure method.
Perhaps in the future the BPF method may make the module method obsolete, but I don't want users of the module method having to do all these workarounds just to satisfy the BPF method while it is in development.
Agree, from the initial survey I had it seems some folks still prefer in-kernel monitors with current infrastructure and cannot migrate (e.g. cannot build BPF in their kernels).
Right now we're trying to understand what are the non-negotiables also BPF must have and it seems we need some sort of tracepoints (via bpf_printk or something more convoluted).
That makes it converge even closer to the in-kernel monitors usage, although it still isn't a drop in replacement.
Reactors will stay, just probably not in BPF for now.
But thanks for chipping in, I fully agree.
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 10 lines · Gabriele Monaco
Quoted 3 lines
BTW, I'm curious if it isn't possible to keep both in-kernel and BPF monitors? That is, for those cases that do not change often and has a well known model, to simply keep those as modules and hard coded.
In my opinion it is possible and I'm designing every change with that coexistence in mind.
I would say we could only drop in-kernel if BPF does such a great job to cover every single technical and non-technical requirement or use-case, AND if it makes maintaining the whole thing easier.
I am wondering if coexistence should be the goal. For example, the monitor classes (DA, LTL, HTA) are only implemented in the kernel and provide kfuncs for the state transition functions to be available to BPF monitors. I would expect that this would allow BPF monitors to have the full functionality as in-kernel monitors, since the events, errors, and reactors would all trigger from the monitor class code.
John
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 12 lines · John Ogness
Quoted 10 lines · Gabriele Monaco
Quoted 3 lines
BTW, I'm curious if it isn't possible to keep both in-kernel and BPF monitors? That is, for those cases that do not change often and has a well known model, to simply keep those as modules and hard coded.
In my opinion it is possible and I'm designing every change with that coexistence in mind.
I would say we could only drop in-kernel if BPF does such a great job to cover every single technical and non-technical requirement or use-case, AND if it makes maintaining the whole thing easier.
Quoted 6 lines
I am wondering if coexistence should be the goal. For example, the monitor classes (DA, LTL, HTA) are only implemented in the kernel and provide kfuncs for the state transition functions to be available to BPF monitors. I would expect that this would allow BPF monitors to have the full functionality as in-kernel monitors, since the events, errors, and reactors would all trigger from the monitor class code.
Well, this would be yet another hybrid requiring BPF monitors registration in the kernel like I proposed in the RFC [1], which was the main point of contention (that fully shared reactors and sysfs interface, by the way).
For this I would argue, though, that such monitors would be BPF just on paper, we wouldn't be able to use many advantages BPF provides (e.g. BPF maps).
The current implementation already shares the header with in-kernel monitors, so the actual logic is shared. What isn't shared is the storage type and some glue around it.
I used BPF maps because they offer some nice flexibility especially around per- task and per-obj monitors. On top of using more battle tested code. I would like to keep that.
Besides, we'd need to be extra careful on controlling the callers. Right now handlers are static, so it's easier to make sure no rogue caller messes up with monitoring.
What else definitely isn't shared, which is the main point of this whole conversation, is trace events.
Those could be kfuncs. And no matter what you do, BPF monitors will need to share the trace events (unlike in-kernel that have separate events per monitor).
In short, I don't think this would be easy to achieve and wouldn't earn us that much. (Plus I'd lose the hardly earned Alexei's blessing ;) )
What do you think?
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 10 lines · Gabriele Monaco
Quoted 6 lines
I am wondering if coexistence should be the goal. For example, the monitor classes (DA, LTL, HTA) are only implemented in the kernel and provide kfuncs for the state transition functions to be available to BPF monitors. I would expect that this would allow BPF monitors to have the full functionality as in-kernel monitors, since the events, errors, and reactors would all trigger from the monitor class code.
Well, this would be yet another hybrid requiring BPF monitors registration in the kernel like I proposed in the RFC [1], which was the main point of contention (that fully shared reactors and sysfs interface, by the way).
I think there is a difference, because the registration could be via kfunc interface rather than requiring kernel patches. Similarly, the kernel is able to load drivers that it does not know about it advance.
Quoted 3 lines
For this I would argue, though, that such monitors would be BPF just on paper, we wouldn't be able to use many advantages BPF provides (e.g. BPF maps).
It seems to me that your main motivation of BPF is to move the RV-machinery into BPF. For example, moving include/rv/ltl_monitor.h into BPF. But that code should not require the flexibility that BPF offers. It is the monitors themselves that I think benefit from BPF. For example, kernel/trace/rv/monitors/wakeup/wakeup.c
I do not understand why you would call it BPF on paper, when the semantics of the states and transitions is all coded in BPF. Everything that makes two monitors using the same monitor class different from each other. Only the generic state machine (with its tracepoints for events and errors) and calling of reactors is in the kernel.
Quoted 2 lines
The current implementation already shares the header with in-kernel monitors, so the actual logic is shared.
When you say "shared" you really mean "copied". If it was "shared" (in the kernel) then the whole tracepoint/reactor topic would nearly solve itself.
Quoted 3 lines
Besides, we'd need to be extra careful on controlling the callers. Right now handlers are static, so it's easier to make sure no rogue caller messes up with monitoring.
That problem is orthogonal. But I expect kfunc flags, capabilities, and/or signed BPF objects will be the direction to take.
The reason for my suggestion of a "true" hybrid approach is because I feel like you were trying to completely relocate RV to BPF, and now due to the tracepoint/reactor requirements, we're trying to find some hacks to somehow make it work good enough.
I was suggesting to take a step back and consider an approach where there are in-kernel pieces to leverage the benefits of in-kernel (generic state machine, tracepoints, reactors) and BPF pieces to leverage the benefits of BPF (freedom to define the semantics of states and transitions for any domain-specific monitor).
John
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 8 lines · John Ogness
Quoted 7 lines · Gabriele Monaco
Quoted 6 lines
I am wondering if coexistence should be the goal. For example, the monitor classes (DA, LTL, HTA) are only implemented in the kernel and provide kfuncs for the state transition functions to be available to BPF monitors. I would expect that this would allow BPF monitors to have the full functionality as in-kernel monitors, since the events, errors, and reactors would all trigger from the monitor class code.
Quoted 7 lines
Quoted 3 lines
Well, this would be yet another hybrid requiring BPF monitors registration in the kernel like I proposed in the RFC [1], which was the main point of contention (that fully shared reactors and sysfs interface, by the way).
I think there is a difference, because the registration could be via kfunc interface rather than requiring kernel patches. Similarly, the kernel is able to load drivers that it does not know about it advance.
Adding kfuncs requires a kernel patch nonetheless.
We avoid a STRUCT_OPS and craft our own way to register BPF monitors, but I don't see a practical difference.
Quoted 10 lines
Quoted 3 lines
For this I would argue, though, that such monitors would be BPF just on paper, we wouldn't be able to use many advantages BPF provides (e.g. BPF maps).
It seems to me that your main motivation of BPF is to move the RV-machinery into BPF. For example, moving
include/rv/ltl_monitor.hinto BPF. But that code should not require the flexibility that BPF offers. It is the monitors themselves that I think benefit from BPF. For example,kernel/trace/rv/monitors/wakeup/wakeup.c
Quoted 5 lines
I do not understand why you would call it BPF on paper, when the semantics of the states and transitions is all coded in BPF. Everything that makes two monitors using the same monitor class different from each other. Only the generic state machine (with its tracepoints for events and errors) and calling of reactors is in the kernel.
Alright, that applies slightly differently to LTL, which has actual functions inside the monitor header. For DA monitors the monitor header contains enums and a "function" field which is essentially a matrix.
Functions like ltl_atom_update() , ltl_validate(), etc., the actual monitor class logic is shared in the ltl header. Those are the things that I'd also have in BPF (and share when possible, see more later).
I say BPF on paper because the monitor state and everything it stores is in the kernel.
BPF maps offer some flexibility and stability that is actually useful, I crafted the per-obj thing myself and I'm sure there are more bugs than a simple BPF hashmap.
per-task monitors use a static field inside a task_struct, we have a limited number of those and obviously the size is fixed. This is great for use-cases where verifying the code matters (i.e. can't use malloc), but a dynamic approach as the one BPF offers rather simply can be useful for monitors that need to store something else. The hack used in [1] could be simplified drastically using a BPF map.
Quoted 6 lines
Quoted 2 lines
The current implementation already shares the header with in-kernel monitors, so the actual logic is shared.
When you say "shared" you really mean "copied". If it was "shared" (in the kernel) then the whole tracepoint/reactor topic would nearly solve itself.
Half and half, I say shared because I include the exact same header, not a copy of it. Then some things down the path cannot be represented in BPF (tracepoints) so I re-define these.
The logic that translates the DA function[curr_state][event] to an actual transition is shared.
Quoted 12 lines
Quoted 3 lines
Besides, we'd need to be extra careful on controlling the callers. Right now handlers are static, so it's easier to make sure no rogue caller messes up with monitoring.
That problem is orthogonal. But I expect kfunc flags, capabilities, and/or signed BPF objects will be the direction to take.
The reason for my suggestion of a "true" hybrid approach is because I feel like you were trying to completely relocate RV to BPF, and now due to the tracepoint/reactor requirements, we're trying to find some hacks to somehow make it work good enough.
Quoted 5 lines
I was suggesting to take a step back and consider an approach where there are in-kernel pieces to leverage the benefits of in-kernel (generic state machine, tracepoints, reactors) and BPF pieces to leverage the benefits of BPF (freedom to define the semantics of states and transitions for any domain-specific monitor).
I'm going to consider what this implies when I get back working on this, but it still feels cleaner to me creating kfuncs for tracing only, if we consider bpf_printk a hack.
Exporting all handlers functions is probably going to require a significant redesign of the current RV internals.
Handlers have access to the monitor headers (everything is static/inlined), kfuncs wouldn't.
Thanks,
Gabriele
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 4 lines · Gabriele Monaco
Exporting all handlers functions is probably going to require a significant redesign of the current RV internals.
Handlers have access to the monitor headers (everything is static/inlined), kfuncs wouldn't.
I gave it some more thought, while you could generalise the DA monitor definition structure (imposing size limits and taking up that space anyway or doing some /smart/ things the BPF verifier probably wouldn't enjoy) then pass that to the handlers, I cannot think how to have a kfunc call the LTL functions defined in BPF. You'd probably need a helper macro that is essentially doing what the "shared" functions do now.
I could fire up an LLM and get some /original/ ways to work around that, but all I can think of is essentially rewriting RV from scratch.
Again, the easiest thing to do is kfunc only what goes out (tracepoints and eventually reactors) and keep the rest in BPF.
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
In reply to Gabriele MonacoQuoted 23 lines · Gabriele Monaco
Well, this would be yet another hybrid requiring BPF monitors registration in the kernel like I proposed in the RFC [1], which was the main point of contention (that fully shared reactors and sysfs interface, by the way).
For this I would argue, though, that such monitors would be BPF just on paper, we wouldn't be able to use many advantages BPF provides (e.g. BPF maps).
The current implementation already shares the header with in-kernel monitors, so the actual logic is shared. What isn't shared is the storage type and some glue around it.
I used BPF maps because they offer some nice flexibility especially around per- task and per-obj monitors. On top of using more battle tested code. I would like to keep that.Besides, we'd need to be extra careful on controlling the callers. Right now handlers are static, so it's easier to make sure no rogue caller messes up with monitoring.
What else definitely isn't shared, which is the main point of this whole conversation, is trace events.
Those could be kfuncs. And no matter what you do, BPF monitors will need to share the trace events (unlike in-kernel that have separate events per monitor).
Quoted 4 lines
In short, I don't think this would be easy to achieve and wouldn't earn us that much. (Plus I'd lose the hardly earned Alexei's blessing ;) )
What do you think?
What about we refactor the in-kernel monitors' trace events into a single one. I am picturing two functions for ALL classes and ALL monitors:
void rv_error(const char *monitor_name, const char *message);
void rv_event(const char *monitor_name, const char *message);which trigger the tracepoints. And we make those kfuncs. This allows sharing trace events between in-kernel monitors and BPF monitors.
Then everything else (kernel reactors, users, perhaps even eBPF reactors in the future) hook into those tracepoints.
Nam
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 4 lines · Nam Cao
What about we refactor the in-kernel monitors' trace events into a single one. I am picturing two functions for ALL classes and ALL monitors:
Quoted 8 lines
void
rv_error(const char *monitor_name, const char *message); voidrv_event(const char *monitor_name, const char *message);which trigger the tracepoints. And we make those kfuncs. This allows sharing trace events between in-kernel monitors and BPF monitors.
Then everything else (kernel reactors, users, perhaps even eBPF reactors in the future) hook into those tracepoints.
That could work, though we'd lose some ergonomics around filtering events, not so much in the unified tracepoint thing but in what fields events have. We would need to parse a string (so I wonder if globs can express constraints like matching whole words or we'd need to arrange the format to accommodate glob limitations).
On the other hand if we still want to keep fields, we are going to need event/error pairs for both DA and LTL and a way to match monitors with their class (needed if you want to surgically enable the right events for your monitors).
Both can work and what you propose is clearly simpler to implement, I can have a look.
Thanks,
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 5 lines · Gabriele Monaco
That could work, though we'd lose some ergonomics around filtering events, not so much in the unified tracepoint thing but in what fields events have. We would need to parse a string (so I wonder if globs can express constraints like matching whole words or we'd need to arrange the format to accommodate glob limitations).
Yes. But the transition event thingy (not sure what we are naming that) is only for debugging RV, and the error event should not appear often. So I think some parsing overhead is not much of an issue.
Nam
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 9 lines · Nam Cao
Quoted 7 lines · Gabriele Monaco
That could work, though we'd lose some ergonomics around filtering events, not
so much in the unified tracepoint thing but in what fields events have. We would
need to parse a string (so I wonder if globs can express constraints like matching whole words or we'd need to arrange the format to accommodate glob limitations).
Quoted 3 lines
Yes. But the transition event thingy (not sure what we are naming that) is only for debugging RV, and the error event should not appear often. So I think some parsing overhead is not much of an issue.
It isn't quite the performance overhead, it's that instead of doing
--filter 'current == "foo" && event == "bar"'
I'm going to need to do something like
--filter 'current ~ "* foo x*" && event ~ "*x bar ->*"'
So you need to remember the format.
You wouldn't need to do that if you know you don't have overlapping names though.
It isn't a big issue most of the time, but less ergonomic for us. As John said, debugging models is still a use case. LTL puts some gibberish in these events but they are useful for DA.
But probably the simplified code all around is worth this mild complication. Anyway I'd rather try this first for BPF and then introduce it for in-kernel ones.
Deprecating per-monitor tracepoints is yet another large change I'd rather keep in a separate series.
Thanks,
Gabriele
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
In reply to John OgnessQuoted 13 lines · John Ogness
Quoted 11 lines · Gabriele Monaco
Quoted 6 lines
I am still not clear how the rv tool will replace the existing in-kernel implementation. Right now violations call
printk(), which conveniently show up in kernel logs and consoles. More importantly, there are the rtapp violation events, which makes it very easy to use ftrace and perf features to record traces, take actions, generate statistics, and dump backtraces on violations.The plan is to keep everything you'd now do with perf/ftrace as plain stdout of the RV tool. Right now you can see the same ftrace output using rv mon <monitor> -t for in-kernel monitors (only deterministic automata).
Quoted 6 lines
IMHO it would be a pity to lose support for ftrace/perf. I use these tools extensively for my daily work evaluating real-time systems. Having the rtapp RVmon integrated allows me to easily and naturally extend my workflow to include rtapp violations. Plain stdout is hardly a replacement for trace recordings that can be imported into existing visualization and analysis tools.
Yeah that's a good point. And the trace-printk can only improve this to some extent. Thought that alone can get you stack traces for free.
I think no matter what we choose now, having extensible reactors allows to easily add new violation actions down the road, if we see it necessary.
Quoted 8 lines
Quoted 3 lines
We are missing stack traces (which I'd optionally add only on errors) and perhaps other events (e.g. the -e in either tool if you aren't only interested in errors/events of the monitor).
I don't see the point of reinventing tools that already do the job well. I do not mind if developers want to create their own tools that provide some small subset of existing features. But I am concerned about removing the in-kernel RV support for ftrace and perf.
That's valid too. We'd need at least the rv tool to start/stop monitors in addition to ftrace/perf. Kind of what you already do now with sysfs.
I'm trying to keep this use-case in mind though.
I assume you aren't interested in the "event" events (transitions in the model), those are useful when developing models, at least in DA. And those do not trigger a reaction (stdout only for now).
Thanks,
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 4 lines · Gabriele Monaco
Quoted 4 lines
Quoted 3 lines
We are missing stack traces (which I'd optionally add only on errors) and perhaps other events (e.g. the -e in either tool if you aren't only interested in errors/events of the monitor).
Quoted 8 lines
Quoted 4 lines
I don't see the point of reinventing tools that already do the job well. I do not mind if developers want to create their own tools that provide some small subset of existing features. But I am concerned about removing the in-kernel RV support for ftrace and perf.
That's valid too. We'd need at least the rv tool to start/stop monitors in addition to ftrace/perf. Kind of what you already do now with sysfs.
I do not expect the rv tool to start/stop ftrace/perf. Nor would I consider that useful. When I am using ftrace/perf, I am interested in additionally related events. The rv tool can not know what what else I need and I do not want the rv tool to become a wrapper for ftrace/perf.
I would use the rv tool only to start the monitor. It would be enough if the tool would report the bpf_trace:bpf_trace_printk globs that are needed for the various possible violations. Then, with the monitor started, I would start ftrace/perf for my own investigations (also capturing any violation events).
If you want the rv tool to provide some basic stdout data from the monitors, I am fine with that. That is certainly useful to easily see if a violation occurred.
But for serious investigations, I really just need the tool to start/stop the monitor and tell me how to grab the violation events.
Quoted 1 line
I'm trying to keep this use-case in mind though.
Thank you.
Quoted 3 lines
I assume you aren't interested in the "event" events (transitions in the model), those are useful when developing models, at least in DA. And those do not trigger a reaction (stdout only for now).
As an RV-monitor _user_ I am not interested in RV state transitions. I do not know if RV-monitor _developers_ might need that. I would think it would be useful when debugging RV-monitor false-positives or missed violations.
@namcao: Maybe you could chime in if you want the transitions as events.
John
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 10 lines · John Ogness
Quoted 9 lines · Gabriele Monaco
Quoted 8 lines
Quoted 3 lines
We are missing stack traces (which I'd optionally add only on errors) and perhaps other events (e.g. the -e in either tool if you aren't only interested in errors/events of the monitor).
I don't see the point of reinventing tools that already do the job well. I do not mind if developers want to create their own tools that provide some small subset of existing features. But I am concerned about removing the in-kernel RV support for ftrace and perf.
Quoted 8 lines
Quoted 3 lines
That's valid too. We'd need at least the rv tool to start/stop monitors in addition to ftrace/perf. Kind of what you already do now with sysfs.
I do not expect the rv tool to start/stop ftrace/perf. Nor would I consider that useful. When I am using ftrace/perf, I am interested in additionally related events. The rv tool can not know what what else I need and I do not want the rv tool to become a wrapper for ftrace/perf.
Yeah of course, I meant more that you need to call both tools (start the monitor /and/ the tracing).
At most I'd have a -e flag in rv (just like rtla has, mirroring trace-cmd functionality).
But you're right, it's best if the other tools can do that first.
Quoted 7 lines
I would use the rv tool only to start the monitor. It would be enough if the tool would report the bpf_trace:bpf_trace_printk globs that are needed for the various possible violations. Then, with the monitor started, I would start ftrace/perf for my own investigations (also capturing any violation events).
That's an interesting idea actually.
Thanks,
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
In reply to John OgnessQuoted 1 line · John Ogness
@namcao: Maybe you could chime in if you want the transitions as events.
No. Those are only useful for debugging RV itself and do not need to be upstream.
Nam
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 5 lines · Nam Cao
Quoted 1 line · John Ogness
@namcao: Maybe you could chime in if you want the transitions as events.
No. Those are only useful for debugging RV itself and do not need to be upstream.
Sure, but debugging RV itself _is_ a use case. Especially when RV moves to eBPF and lots of people will start writing their own RV monitors.
John
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 9 lines · John Ogness
Quoted 5 lines · Nam Cao
Quoted 1 line · John Ogness
@namcao: Maybe you could chime in if you want the transitions as events.
No. Those are only useful for debugging RV itself and do not need to be upstream.
Sure, but debugging RV itself _is_ a use case. Especially when RV moves to eBPF and lots of people will start writing their own RV monitors.
Right.
I wouldn't enable those by default though, it's way too much noises. As it's for debugging the model, we can have some sort of compile-time switch to turn it on.
Nam
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 8 lines · Nam Cao
Quoted 7 lines · John Ogness
Quoted 5 lines · Nam Cao
Quoted 1 line · John Ogness
@namcao: Maybe you could chime in if you want the transitions as events.
No. Those are only useful for debugging RV itself and do not need to be upstream.
Quoted 8 lines
Quoted 2 lines
Sure, but debugging RV itself _is_ a use case. Especially when RV moves to eBPF and lots of people will start writing their own RV monitors.
Right.
I wouldn't enable those by default though, it's way too much noises. As it's for debugging the model, we can have some sort of compile-time switch to turn it on.
That's almost what's happening already, in-kernel use tracepoints, gated by static branches. Those are the closest thing you can get to a dynamic compile- time switch (assuming such a thing can exist), it's patching the code.
BPF gets even closer to the concept, we use a volatile const flag, which is constant for the JIT runtime but volatile for the compiler (not compiled out when generating byte code). Before loading we set the value we want in the object and the JIT compiler wipes away the unused branches.
But technicalities aside, we probably want tracepoints for events too, so bpf_printk or whatever else.
Gabriele
Re: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 8 lines · Gabriele Monaco
Quoted 3 lines · Nam Cao
I wouldn't enable those by default though, it's way too much noises. As it's for debugging the model, we can have some sort of compile-time switch to turn it on.
That's almost what's happening already, in-kernel use tracepoints, gated by static branches. Those are the closest thing you can get to a dynamic compile- time switch (assuming such a thing can exist), it's patching the code.
I was talking about how people are going to enable transition events, not how kernel enables them. Do we expose some user API for people to enable at run-time (and kernel can use run-time patching or whatever), or people enable them while compiling their BPF programs. I think the latter should suffice.
Nam
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
Quoted 11 lines · Nam Cao
Quoted 9 lines · Gabriele Monaco
Quoted 3 lines · Nam Cao
I wouldn't enable those by default though, it's way too much noises. As it's for debugging the model, we can have some sort of compile-time switch to turn it on.
That's almost what's happening already, in-kernel use tracepoints, gated by static branches. Those are the closest thing you can get to a dynamic compile-
time switch (assuming such a thing can exist), it's patching the code.
Quoted 5 lines
I was talking about how people are going to enable transition events, not how kernel enables them. Do we expose some user API for people to enable at run-time (and kernel can use run-time patching or whatever), or people enable them while compiling their BPF programs. I think the latter should suffice.
Everything BPF-related will need to go through the userspace tool. From loading monitors to enabling things, but it shouldn't require any recompilation.
Right now I use only the -t flag (enable tracing and print to stdout), we'd need some flag to only enable tracing.
After that you should be able to use ftrace as normal.
Gabriele
Gabriele Monaco
maintainerRe: [PATCH v2 10/15] tools/rv: Add BPF monitors
In reply to Alexei StarovoitovIl 16 ottobre 2026 18:32:44 UTC, Alexei Starovoitov <[email protected]> ha scritto:
Quoted 6 lines · Gabriele Monaco
Quoted 4 lines
Reactors in this patch use
bpf_printk(), which is in fact atrace_printk()instead of a real printk, is there a technical limitation forbidding us to create a kfunc using some flavour ofprintk_deferred()? Or am I missing an existing one? (this need was brought up by John, Cc'd here)
Quoted 10 lines
No technical limitation, and there is no such kfunc today.
printk_deferred()is a lockless store into the ring buffer plusirq_work. It's ok in any context where tracing progs run.
The closest we have isbpf_stream_vprintk(). That's stdout/stderr of the prog. User space has to read it.
rv tool is around for as long as the monitor is loaded, so it can read the stream and log it anywhere like/dev/kmsg.
If the message has to reach the console when user space cannot run then the kfunc makes sense, but usingbpf_streamis imo much cleaner.
Thanks for the answer, I'd expect a mildly higher overhead in doing that, but since it's only on violations we can probably accept it.
I'm going to have a look at that. User space should be able to run for at least most models, I'd say, but I'm not sure how fast it can pick up.
Quoted 8 lines
Quoted 7 lines
Not needed in this patch but potentially required for more complex monitors. In kernel, when timers are required, we allow monitors to use hrtimers (precise but heavy), or the
timer_wheel(lightweight but less precise).
I'm not aware of any wrapper of the wheel in BPF, but I think a few kfuncs for these could be useful, in general, also for other programs needing a lot of timer instances or simply light timeouts.
What do you think?
Quoted 7 lines
I don't think it's needed.
bpf_timeris hrtimer only, but hrtimer vs wheel is not where the cost is.bpf_timer_start()cannot callhrtimer_start()directly.bpf_async_schedule_op()doeskmalloc_nolock()
andirq_work_queue()instead.
I don't think timer wheel will help.
Alright, I'm going to keep that in mind once I get to work with timed automata.
Thanks,
Gabriele
Gabriele Monaco
maintainerPATCH v2 11/15 tools/rv: Define CONFIG_X86_64 statically for BPF monitors
In reply to Gabriele MonacoBPF atomic macros require CONFIG_X86_64 to determine barrier instructions. Reading this from the system Kconfig can fail if the configuration is missing or in an unexpected location, causing the loading phase to fail.
Since the rv tool is compiled for the target architecture, the architecture is known at compile-time. Define the CONFIG_X86_64 value statically via the libbpf open options to bypass Kconfig dependency and ensure reliable loading.
--- tools/verification/rv/src/bpf_monitor.c | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-)
tools/verification/rv/src/bpf_monitor.c +10 -1
@@ -719,7 +719,16 @@ static struct bpf_object *open_bpf_monitor(const char *path, struct bpf_monitor_struct bpf_object *obj =NULL ;int res; - obj =bpf_object__open_file (path,NULL ); +LIBBPF_OPTS (bpf_object_open_opts, opts, +/* Define statically as arch is known, Kconfig may not be available */ +#ifdef __x86_64__ + .kconfig ="CONFIG_X86_64=y\n" , +#else + .kconfig = "CONFIG_X86_64=n\n", +#endif + ); + + obj =bpf_object__open_file (path, &opts);if (!obj) {err_msg ("bpf: error opening object: %s\n" ,strerror (errno));return NULL ;
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 11/15] tools/rv: Define CONFIG_X86_64 statically for BPF monitors
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Low] rv: build failure from #ifdef inside LIBBPF_OPTS macro --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Low] rv: build failure from #ifdef inside LIBBPF_OPTS macro
--
commit a53c9f566aefb8c15a1d5a3745ce6829be8b1a7a
Author: Gabriele Monaco <[email protected]>
tools/rv: Define CONFIG_X86_64 statically for BPF monitors
This commit statically defines the CONFIG_X86_64 value via libbpf open options to bypass system Kconfig dependencies. This ensures reliable loading for the rv tool by defining the architecture at compile time.
Quoted 7 lines
tools/verification/rv/src/bpf_monitor.c +0
-0@@ -719,7 +719,16 @@ static struct bpf_object *open_bpf_monitor(const char *path, struct bpf_monitor_struct bpf_object *obj =NULL ;int res;
tools/verification/rv/src/bpf_monitor.c static struct bpf_object *open_bpf_monitor(const char *path, struct bpf_monitor_ · line 729
Quoted 10 lines
tools/verification/rv/src/bpf_monitor.c +8
-1- obj =bpf_object__open_file (path,NULL ); +LIBBPF_OPTS (bpf_object_open_opts, opts, +/* Define statically as arch is known, Kconfig may not be available */ +#ifdef __x86_64__ + .kconfig ="CONFIG_X86_64=y\n" , +#else + .kconfig = "CONFIG_X86_64=n\n", +#endif + );
[Severity: Low]
Does this #ifdef block inside the LIBBPF_OPTS macro invocation cause a build failure?
Embedding preprocessor directives inside macro arguments invokes undefined behavior according to the C99 standard. Clang explicitly rejects this pattern (-Wembedded-directive), which leads to a build failure when compiling tools/rv with Clang.
Quoted 5 lines
tools/verification/rv/src/bpf_monitor.c +2
-0+ + obj =bpf_object__open_file (path, &opts);if (!obj) {err_msg ("bpf: error opening object: %s\n" ,strerror (errno));return NULL ;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=11
Gabriele Monaco
maintainerPATCH v2 12/15 tools/rv: Add reactors support to BPF monitors
In reply to Gabriele MonacoThe BPF implementation of RV monitors cannot use standard reactors in the kernel and currently reactions are skipped.
Add rv_react() to build the printk format using BPF macros and pass that to a BPF function with a single message parameter, since BPF doesn't support variable arguments.
This function is defined as weak, so the rv tool can link a different implementation on top at load time.
Implement a printk reactor that is simply reimplementing this function passing the message to bpf_printk().
--- include/rv/da_monitor.h | 4 +- tools/verification/rv/Makefile | 12 ++- tools/verification/rv/Makefile.rv | 5 + .../rv/bpf_monitors/da_monitor_bpf.h | 12 ++- tools/verification/rv/bpf_reactors/.gitignore | 2 + tools/verification/rv/bpf_reactors/panic.c | 15 +++ tools/verification/rv/bpf_reactors/printk.c | 13 +++ tools/verification/rv/src/bpf_monitor.c | 102 +++++++++++++++++- 8 files changed, 157 insertions(+), 8 deletions(-) create mode 100644 tools/verification/rv/bpf_reactors/.gitignore create mode 100644 tools/verification/rv/bpf_reactors/panic.c create mode 100644 tools/verification/rv/bpf_reactors/printk.c
include/rv/da_monitor.h +2 -2
@@ -84,7 +84,8 @@ static struct rv_monitor rv_this;#ifdef __BPF__#include "da_monitor_bpf.h" -#else +#endif +static void react (enum states curr_state,enum events event) { rv_react(&rv_this,
@@ -93,7 +94,6 @@ static void react(enum states curr_state, enum events event)model_get_event_name (event), model_get_state_name(curr_state)); } -#endif /* * da_monitor_reset_state - reset a monitor and setting it to init state
tools/verification/rv/Makefile +10 -2
@@ -73,8 +73,11 @@ static: $(RV_IN) $(QUIET_LINK)$(CC) $(LDFLAGS) -o $(RV)-static $(RV_IN) $(EXTLIBS) BPF_DIR := bpf_monitors +BPF_REACT_DIR := bpf_reactors BPF_SOURCES := $(wildcard $(BPF_DIR)/*.c) BPF_OBJECTS := $(BPF_SOURCES:.c=.o) +BPF_REACT_SOURCES := $(wildcard $(BPF_REACT_DIR)/*.c) +BPF_REACT_OBJECTS := $(BPF_REACT_SOURCES:.c=.o) VMLINUX_H := $(BPF_DIR)/vmlinux.h BPF_INCLUDES := -I$(srctree)/include/uapi
@@ -95,9 +98,14 @@ $(BPF_DIR)/%.o: $(BPF_DIR)/%.c $(VMLINUX_H) $(Q)$(LLVM_STRIP) -g $@ $(Q)$(LLVM_OBJCOPY) --remove-section=.rel.rodata $@ --include $(BPF_SOURCES:.c=.d) +$(BPF_REACT_DIR)/%.o: $(BPF_REACT_DIR)/%.c $(VMLINUX_H) + $(QUIET_CLANG)$(CLANG) $(BPF_CFLAGS) -c $< -o $@ + $(Q)$(LLVM_STRIP) -g $@ + $(Q)$(LLVM_OBJCOPY) --remove-section=.rel.rodata $@ + +-include $(BPF_SOURCES:.c=.d) $(BPF_REACT_SOURCES:.c=.d) -bpf: $(BPF_OBJECTS) +bpf: $(BPF_OBJECTS) $(BPF_REACT_OBJECTS) rv.%: fixdep FORCE make -f $(srctree)/tools/build/Makefile.build dir=. $@
tools/verification/rv/Makefile.rv +5 -0
@@ -34,6 +34,7 @@ MKDIR := mkdir STRIP := strip BINDIR := /usr/bin BPF_MON_DIR := /usr/share/rv/bpf_monitors +BPF_REACT_DIR := /usr/share/rv/bpf_reactors .PHONY: install install: doc_install
@@ -44,6 +45,10 @@ ifneq ($(wildcard bpf_monitors/*.o),) $(Q)$(MKDIR) -p $(DESTDIR)$(BPF_MON_DIR) $(call QUIET_INSTALL,bpf_monitors)$(INSTALL) bpf_monitors/*.o -m 644 $(DESTDIR)$(BPF_MON_DIR) endif +ifneq ($(wildcard bpf_reactors/*.o),) + $(Q)$(MKDIR) -p $(DESTDIR)$(BPF_REACT_DIR) + $(call QUIET_INSTALL,bpf_reactors)$(INSTALL) bpf_reactors/*.o -m 644 $(DESTDIR)$(BPF_REACT_DIR) +endif .PHONY: doc doc_clean doc_install doc:
tools/verification/rv/bpf_monitors/da_monitor_bpf.h +9 -3
@@ -17,7 +17,6 @@#include "bpf_atomic.h" /* BPF monitors don't support these */ -#define rv_react (...) do {} while (0)#define trace_rv_retries_error (...) do {} while (0)#define pr_warn (fmt, ...) bpf_printk(fmt, ##__VA_ARGS__)#define rv_monitoring_on () 1
@@ -75,8 +74,15 @@ static const struct rv_trace_entry __used *_btf_trace;static inline void da_monitor_reset (struct da_monitor *da_mon); -/* BPF monitors do not use reactors */ -static inline void react (enum states curr_state,enum events event) { } +__noinline __weak void bpf_rv_react(char *msg) { } + +#define rv_react (mon, fmt, ...) \ + ({ \ + char ___msg[256]; \ + \ + if (BPF_SNPRINTF(___msg, sizeof(___msg), fmt, ##__VA_ARGS__) > 0) \ + bpf_rv_react(___msg); \ + })/* * BPF monitor implementations
tools/verification/rv/bpf_reactors/.gitignore new file +2 -0
@@ -0,0 +1,2 @@ +*.d +vmlinux.h
tools/verification/rv/bpf_reactors/panic.c new file +15 -0
@@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" +#include <bpf/bpf_helpers.h> + +void bpf_rv_react (char *msg) +{ +struct pt_regs regs = {0 }; + +crash_kexec (®s); +} + +char LICENSE[] SEC("license") = "GPL"; +static char DESCRIPTION[] SEC(".rodata.description") = +"panic the system if an exception is found." ;
tools/verification/rv/bpf_reactors/printk.c new file +13 -0
@@ -0,0 +1,13 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" +#include <bpf/bpf_helpers.h> + +void bpf_rv_react (char *msg) +{ +bpf_printk ("%s" , msg); +} + +char LICENSE[] SEC("license") = "GPL"; +static char DESCRIPTION[] SEC(".rodata.description") = +"prints the exception msg to the trace buffer." ;
tools/verification/rv/src/bpf_monitor.c +101 -1
157 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 12/15] tools/rv: Add reactors support to BPF monitors
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] bpf: panic reactor BPF program rejected due to PTR_TO_STACK argument - [Medium] rv: NULL pointer…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] bpf: panic reactor BPF program rejected due to PTR_TO_STACK argument
- [Medium] rv: NULL pointer dereference in list_reactor_action on missing BTF --
commit fed00056d145e6ae07ec2d9b2b99084fea10c012
Author: Gabriele Monaco <[email protected]>
tools/rv: Add reactors support to BPF monitors
The commit adds reactors support to BPF monitors in the rv tool. It implements rv_react to format and pass messages to a BPF function, which can be overridden at load time by dynamically linking reactor object files like panic.o and printk.o.
Quoted 6 lines
tools/verification/rv/bpf_reactors/panic.c new file +0
-0
tools/verification/rv/bpf_reactors/panic.c line 10
Quoted 10 lines
tools/verification/rv/bpf_reactors/panic.c new file +10
-0@@ -0,0 +1,15 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" +#include <bpf/bpf_helpers.h> + +void bpf_rv_react (char *msg) +{ +struct pt_regs regs = {0 }; + +crash_kexec (®s);
[Severity: Medium]
Will the BPF verifier reject this program? The ®s argument evaluates to a PTR_TO_STACK register type, but crash_kexec expects a tracked PTR_TO_BTF_ID.
The verifier's check_kfunc_args strictly requires KF_ARG_PTR_TO_BTF_ID for regular struct pointers unless explicitly tagged, so it may reject PTR_TO_STACK.
Quoted 1 line
tools/verification/rv/bpf_reactors/panic.c new file +1
-0+}
[ ... ]
tools/verification/rv/src/bpf_monitor.c static struct ring_buffer *bpf_setup_ring_buffer(struct bpf_object *obj, · line 686
Quoted 13 lines
tools/verification/rv/src/bpf_monitor.c +5
-0@@ -676,12 +679,31 @@ static struct ring_buffer *bpf_setup_ring_buffer(struct bpf_object *obj,return rb; } +static void list_reactor_action (const char *name,struct bpf_object *obj) +{ +const struct btf *btf =bpf_object__btf (obj); + +if (btf__find_by_name_kind (btf,BPF_REACTOR ,BTF_KIND_FUNC ) >=0 )
[Severity: Medium]
Can this cause a NULL pointer dereference? If the object file lacks BTF information (e.g., if it was stripped or compiled without -g), bpf_object__btf() returns NULL.
btf__find_by_name_kind() then directly dereferences this NULL pointer in libbpf's btf__type_cnt() without validation.
Quoted 2 lines
tools/verification/rv/src/bpf_monitor.c +2
-0+fprintf (stderr,"%s " , name); +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
[email protected]
AI reviewRe: [PATCH v2 12/15] tools/rv: Add reactors support to BPF monitors
In reply to Gabriele MonacoTL;DR: - bpf_reactors install dir variable clashes, so make install may fail or misplace reactors - void global bpf_rv_react() may break monitor loading on older kernels - bpf_linker__new_fd() may…
Quoted 1 line
tools/rv: Add reactors support to BPF monitors
TL;DR:
- bpf_reactors install dir variable clashes, so make install may fail or misplace reactors
- void global bpf_rv_react() may break monitor loading on older kernels
- bpf_linker__new_fd() may break builds on libbpf before 1.6
- unused DESCRIPTION nit
Quoted 10 lines
tools/verification/rv/Makefile +1
-0@@ -73,8 +73,11 @@ static: $(RV_IN) $(QUIET_LINK)$(CC) $(LDFLAGS) -o $(RV)-static $(RV_IN) $(EXTLIBS) BPF_DIR := bpf_monitors +BPF_REACT_DIR := bpf_reactors BPF_SOURCES := $(wildcard $(BPF_DIR)/*.c)
[ ... ]
Quoted 13 lines
tools/verification/rv/Makefile.rv +1
-0@@ -34,6 +34,7 @@ MKDIR := mkdir STRIP := strip BINDIR := /usr/bin BPF_MON_DIR := /usr/share/rv/bpf_monitors +BPF_REACT_DIR := /usr/share/rv/bpf_reactors .PHONY: install install: doc_install
tools/verification/rv/Makefile.rv ifneq ($(wildcard bpf_monitors/*.o),) · line 51
Quoted 7 lines
tools/verification/rv/Makefile.rv +4
-0@@ -44,6 +45,10 @@ ifneq ($(wildcard bpf_monitors/*.o),) $(Q)$(MKDIR) -p $(DESTDIR)$(BPF_MON_DIR) $(call QUIET_INSTALL,bpf_monitors)$(INSTALL) bpf_monitors/*.o -m 644 $(DESTDIR)$(BPF_MON_DIR) endif +ifneq ($(wildcard bpf_reactors/*.o),) + $(Q)$(MKDIR) -p $(DESTDIR)$(BPF_REACT_DIR) + $(call QUIET_INSTALL,bpf_reactors)$(INSTALL) bpf_reactors/*.o -m 644 $(DESTDIR)$(BPF_REACT_DIR) +endif
Is BPF_REACT_DIR defined twice with different meanings? Makefile.rv sets it to the install destination (/usr/share/rv/bpf_reactors), but Makefile includes Makefile.rv first and then redefines it as the source directory:
include Makefile.rv
...
BPF_REACT_DIR := bpf_reactors
make expands recipe lines after the whole makefile has been parsed, so the install recipe sees the last value, "bpf_reactors". The monitors are not affected because they use two different names (BPF_DIR for the source, BPF_MON_DIR for the destination).
Once the reactors are built (the default whenever clang and bpftool are found), the wildcard check is true and make install runs:
mkdir -p bpf_reactors
install bpf_reactors/*.o -m 644 bpf_reactors
With an empty DESTDIR this copies each file onto itself, which GNU install rejects with "are the same file", so make install fails. With DESTDIR=/tmp/pkg the reactors land in /tmp/pkgbpf_reactors instead of /tmp/pkg/usr/share/rv/bpf_reactors. Either way the installed rv cannot find reactors under the /usr/share/rv base path that bpf_monitor.c searches.
Would renaming one of the variables (for example BPF_REACT_INST_DIR, matching the BPF_DIR/BPF_MON_DIR split) fix this? I didn't see a later patch in this series that changes Makefile or Makefile.rv.
Quoted 4 lines
tools/verification/rv/bpf_monitors/da_monitor_bpf.h +0
-0
[ ... ]
Quoted 5 lines
tools/verification/rv/bpf_monitors/da_monitor_bpf.h +0
-1@@ -75,8 +74,15 @@ static const struct rv_trace_entry __used *_btf_trace;static inline void da_monitor_reset (struct da_monitor *da_mon); -/* BPF monitors do not use reactors */
tools/verification/rv/bpf_monitors/da_monitor_bpf.h static const struct rv_trace_entry __used *_btf_trace; · line 85
Quoted 10 lines
tools/verification/rv/bpf_monitors/da_monitor_bpf.h +9
-1-static inline void react (enum states curr_state,enum events event) { } +__noinline __weak void bpf_rv_react(char *msg) { } + +#define rv_react (mon, fmt, ...) \ + ({ \ + char ___msg[256]; \ + \ + if (BPF_SNPRINTF(___msg, sizeof(___msg), fmt, ##__VA_ARGS__) > 0) \ + bpf_rv_react(___msg); \ + })
Can this break loading of every BPF monitor on older kernels?
bpf_rv_react() is a non-static (weak) function, so clang gives it BTF_FUNC_GLOBAL linkage and the verifier checks it as a global subprog. Every BPF monitor now calls it on the da_event() -> react() path, even with no reactor or with -r nop.
Global subprogs returning void have only been accepted since commit 8446ded1e1a0 ("bpf: Allow void global functions in the verifier"). Before that commit, btf_prepare_func_args() rejects them with:
Global function bpf_rv_react() doesn't return scalar. Only those are supported.
So after this patch, monitors that only use long-standing attach points (nohz, for example) fail to load on kernels older than that commit. Before this patch they had no global subprog and did not have that requirement.
Would declaring the hook as "int bpf_rv_react(char *msg)", returning 0 in the weak default and in the printk and panic reactors, keep the monitors loadable on those kernels?
Quoted 5 lines
tools/verification/rv/bpf_reactors/panic.c new file +0
-0
[ ... ]
Quoted 8 lines
tools/verification/rv/bpf_reactors/panic.c new file +3
-0+char LICENSE[] SEC("license") = "GPL"; +static char DESCRIPTION[] SEC(".rodata.description") = +"panic the system if an exception is found." ;tools/verification/rv/bpf_reactors/printk.c new file +0
-0
[ ... ]
tools/verification/rv/bpf_reactors/printk.c line 13
Quoted 3 lines
tools/verification/rv/bpf_reactors/printk.c new file +3
-0+char LICENSE[] SEC("license") = "GPL"; +static char DESCRIPTION[] SEC(".rodata.description") = +"prints the exception msg to the trace buffer." ;
Is the static DESCRIPTION in these two reactors ever used?
The monitors define DESCRIPTION as a non-static global (nohz.c, tqueue.c), but here it has internal linkage and no "used" attribute. That triggers -Wunused-variable under the -Wall in BPF_CFLAGS, and the optimizer can drop it at -O2, so the reactor objects may end up with no .rodata.description section.
Nothing in the series reads a reactor description either, since list_reactor_action() in bpf_monitor.c prints only the name. Should the variable be dropped, or made non-static like the monitors' if reactor descriptions are meant to be listed?
Quoted 4 lines
tools/verification/rv/src/bpf_monitor.c +0
-0
[ ... ]
Quoted 21 lines
tools/verification/rv/src/bpf_monitor.c +17
-0@@ -795,6 +818,65 @@ static int attach_bpf_handlers(const char *monitor_name, struct bpf_object *obj,return enable_mon_fd; } +static int find_bpf_reactor (const char *reactor_name,char *path_out,size_t path_len) +{ +return find_bpf_file ("bpf_reactors" , reactor_name, path_out, path_len); +} + +/* +* link_bpf_reactor - link the reactor function to the monitor +* +* Reactors are objects defining the BPF_REACTOR function, link that over the +* weak definition present in the monitor and return a file descriptor to the +* final linked object in memory. +* +* Returns memfd of final object on success, -1 on error. +*/ +static int link_bpf_reactor (const char *monitor_path,const char *reactor_path) +{ +struct bpf_linker *linker =NULL ;
tools/verification/rv/src/bpf_monitor.c static int attach_bpf_handlers(const char *monitor_name, struct bpf_object *obj, · line 847
Quoted 10 lines
tools/verification/rv/src/bpf_monitor.c +10
-0+int memfd =-1 ; +int err =0 ; + + memfd =memfd_create ("linked_bpf" ,0 ); +if (memfd <0 ) { +err_msg ("bpf: failed to create memfd: %s\n" ,strerror (errno)); +return -1 ; + } + + linker =bpf_linker__new_fd (memfd,NULL );
Does this raise the minimum libbpf version needed to build rv?
bpf_linker__new_fd() was added in libbpf 1.6 (it is in the LIBBPF_1.6.0 block of libbpf.map). rv builds against the system libbpf through pkg-config, and the only libbpf gate is the feature test, which only requires LIBBPF_MAJOR_VERSION >= 1:
#if !defined(LIBBPF_MAJOR_VERSION) || (LIBBPF_MAJOR_VERSION < 1) #error At least libbpf 1.0 is required for Linux tools.
Before this patch, the newest libbpf API used by bpf_monitor.c was bpf_map_get_info_by_fd() (LIBBPF_1.2.0). With libbpf 1.2 to 1.5 installed (for example Ubuntu 24.04 ships 1.3, RHEL 9 ships 1.3/1.4, Debian 13 and Fedora 42 ship 1.5), feature-libbpf still passes, so HAVE_LIBBPF is set and bpf_monitor.c is compiled.
The build then fails: GCC 14 and later reject the implicit declaration of bpf_linker__new_fd(), and older compilers stop at link time with an undefined reference. On those systems 'make -C tools/verification/rv' used to build rv with BPF monitor support and now fails outright, instead of falling back to the "building without BPF monitor support" path.
Could this use bpf_linker__new() (LIBBPF_0.4.0) on a path such as "/proc/self/fd/<memfd>" or a temporary file, or add a libbpf >= 1.6 version check to Makefile.config, the way libtraceevent and libtracefs are already handled there? I didn't see a later patch in this series that touches tools/verification/rv/src/, the rv Makefiles or tools/build/feature/.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Gabriele Monaco
maintainerPATCH v2 13/15 verification/rvgen: Add support for BPF monitors
In reply to Gabriele MonacoAdd the -b flag to rvgen monitor to generate a bpf monitor. By default the code is generated in a folder with the same name as the model just like in-kernel monitors, although only the source and header are meaningful here. Passing -a moves the sources to tools/verification/rv/bpf_monitors/ where they can be built directly.
Currently BPF monitors are only supported for DA.
--- tools/verification/rvgen/__main__.py | 15 ++++++++--- tools/verification/rvgen/rvgen/dot2c.py | 15 ++++++++--- tools/verification/rvgen/rvgen/dot2k.py | 22 +++++++++++++--- tools/verification/rvgen/rvgen/generator.py | 26 ++++++++++++++----- .../rvgen/rvgen/templates/dot2k/main_bpf.c | 21 +++++++++++++++ 5 files changed, 80 insertions(+), 19 deletions(-) create mode 100644 tools/verification/rvgen/rvgen/templates/dot2k/main_bpf.c
tools/verification/rvgen/__main__.py +11 -4
@@ -39,6 +39,8 @@ if __name__ == '__main__': help="Monitor specification file") monitor_parser.add_argument('-t', "--monitor_type", dest="monitor_type", required=True, help=f"Available options: {', '.join(Monitor.monitor_types.keys())}") + monitor_parser.add_argument('-b', "--bpf", dest="bpf", action="store_true", + required=False, help="Generate a BPF monitor") container_parser = subparsers.add_parser("container", parents=[parent_parser]) container_parser.add_argument('-n', "--model_name", dest="model_name", required=True)
@@ -50,6 +52,9 @@ if __name__ == '__main__': params = parser.parse_args() + if params.subcmd == "monitor" and params.bpf and params.monitor_class != "da": + parser.error("BPF monitors (-b/--bpf) are only supported for deterministic automaton (-c da)") + try: if params.subcmd == "monitor": print(f"Opening and parsing the specification file {params.spec}")
@@ -80,7 +85,9 @@ if __name__ == '__main__': print("Almost done, checklist") if params.subcmd == "monitor": print(f" - Edit the {monitor.name}/{monitor.name}.c to add the instrumentation") - print(monitor.fill_tracepoint_tooltip()) - print(monitor.fill_makefile_tooltip()) - print(monitor.fill_kconfig_tooltip()) - print(monitor.fill_monitor_tooltip()) + if not params.bpf: + print(monitor.fill_tracepoint_tooltip()) + if not params.subcmd == "monitor" or not params.bpf: + print(monitor.fill_makefile_tooltip()) + print(monitor.fill_kconfig_tooltip()) + print(monitor.fill_monitor_tooltip())
tools/verification/rvgen/rvgen/dot2c.py +11 -4
@@ -111,10 +111,17 @@ class Dot2c(Automata): min_type = self.get_minimun_type() buff = [] buff.append(f"struct {self.struct_automaton_def} {{") - buff.append(f"\tchar *state_names[state_max{self.enum_suffix}];") - buff.append(f"\tchar *event_names[event_max{self.enum_suffix}];") - if self.is_hybrid_automata(): - buff.append(f"\tchar *env_names[env_max{self.enum_suffix}];") + if self.bpf: + # BPF struggles with non-fixed string pointers + buff.append(f"\tchar state_names[state_max{self.enum_suffix}][32];") + buff.append(f"\tchar event_names[event_max{self.enum_suffix}][32];") + if self.is_hybrid_automata(): + buff.append(f"\tchar env_names[env_max{self.enum_suffix}][32];") + else: + buff.append(f"\tchar *state_names[state_max{self.enum_suffix}];") + buff.append(f"\tchar *event_names[event_max{self.enum_suffix}];") + if self.is_hybrid_automata(): + buff.append(f"\tchar *env_names[env_max{self.enum_suffix}];") buff.append(f"\t{min_type} function[state_max{self.enum_suffix}][event_max{self.enum_suffix}];") buff.append(f"\t{min_type} initial_state;") buff.append(f"\tbool final_states[state_max{self.enum_suffix}];")
tools/verification/rvgen/rvgen/dot2k.py +18 -4
@@ -30,14 +30,19 @@ class dot2k(Monitor, Dot2c): buff = [ self.monitor_type.upper() ] buff += self._fill_timer_type() if self.monitor_type == "per_obj": - buff.append("typedef /* XXX: define the target type */ *monitor_target;") + pad = "_bpf" if self.bpf else "" + buff.append(f"typedef /* XXX: define the target type */ *monitor_target{pad};") return "\n".join(buff) def fill_tracepoint_handlers_skel(self) -> str: buff = [] buff += self._fill_hybrid_definitions() for event in self.events: - buff.append(f"static void handle_{event}(void *data, /* XXX: fill header */)") + if self.bpf: + buff.append("SEC(/* XXX: tracepoint or other probe */)") + buff.append(f"int BPF_PROG(handle_{event}, /* XXX: fill header */)") + else: + buff.append(f"static void handle_{event}(void *data, /* XXX: fill header */)") buff.append("{") handle = "handle_event" if self.is_start_event(event):
@@ -50,19 +55,28 @@ class dot2k(Monitor, Dot2c): buff.append("\tstruct task_struct *p = /* XXX: how do I get p? */;") buff.append(f"\tda_{handle}(p, {event}{self.enum_suffix});") elif self.monitor_type == "per_obj": + pad = "_bpf" if self.bpf else "" buff.append("\tint id = /* XXX: how do I get the id? */;") - buff.append("\tmonitor_target t = /* XXX: how do I get t? */;") + buff.append(f"\tmonitor_target{pad} t = /* XXX: how do I get t? */;") buff.append(f"\tda_{handle}(id, t, {event}{self.enum_suffix});") else: buff.append(f"\tda_{handle}({event}{self.enum_suffix});") + if self.bpf: + buff.append("\treturn 0;") buff.append("}") buff.append("") if self.monitor_type == "per_obj": buff.append("/* XXX: obj is being destroyed, remove if not required (e.g. obj is static) */") - buff.append(f"static void handle_{self.cleanup_marker}(void *data, /* XXX: fill header */)") + if self.bpf: + buff.append("SEC(/* XXX: tracepoint or other probe */)") + buff.append(f"int BPF_PROG(handle_{self.cleanup_marker}, /* XXX: fill header */)") + else: + buff.append(f"static void handle_{self.cleanup_marker}(void *data, /* XXX: fill header */)") buff.append("{") buff.append("\tint id = /* XXX: how do I get the id? */;") buff.append("\tda_destroy_storage(id);") + if self.bpf: + buff.append("\treturn 0;") buff.append("}") buff.append("") return '\n'.join(buff)
tools/verification/rvgen/rvgen/generator.py +19 -7
@@ -11,18 +11,22 @@ from pathlib import Path class RVGenerator: rv_dir = "kernel/trace/rv" + rv_tool_dir = "../../../tools/verification/rv/bpf_monitors/" def __init__(self, extra_params={}): self.name = extra_params.get("model_name") self.parent = extra_params.get("parent") + self.bpf = extra_params.get("bpf") self.abs_template_dir = \ Path(__file__).resolve().parent / "templates" / self.template_dir - self.main_c = self._read_template_file("main.c") + self.main_c = self._read_template_file("main.c" if not self.bpf + else "main_bpf.c") self.kconfig = self._read_template_file("Kconfig") self.description = extra_params.get("description", self.name) or "auto-generated" self.auto_patch = extra_params.get("auto_patch") if self.auto_patch: self._fill_rv_kernel_dir() + self.rv_tool_dir = (Path(self.rv_dir) / self.rv_tool_dir).resolve() def _fill_rv_kernel_dir(self): # find the kernel tree root relative to this file's location
@@ -191,6 +195,9 @@ obj-$(CONFIG_RV_MON_{name_up}) += monitors/{name}/{name}.o def __create_directory(self): path = Path(self.name) if self.auto_patch: + if self.bpf: + # no directory for BPF monitors + return path = Path(self.rv_dir) / "monitors" / path path.mkdir(exist_ok=True)
@@ -202,6 +209,8 @@ obj-$(CONFIG_RV_MON_{name_up}) += monitors/{name}/{name}.o path = Path(self.name) / file_name if self.auto_patch: path = Path(self.rv_dir) / "monitors" / self.name / file_name + if self.bpf: + path = Path(self.rv_tool_dir) / file_name self.__write_file(path, content) def print_files(self):
@@ -216,8 +225,9 @@ obj-$(CONFIG_RV_MON_{name_up}) += monitors/{name}/{name}.o path = f"{self.name}.h" self._create_file(path, model_h) - kconfig = self.fill_kconfig() - self._create_file("Kconfig", kconfig) + if not self.bpf: + kconfig = self.fill_kconfig() + self._create_file("Kconfig", kconfig) class Monitor(RVGenerator):
@@ -225,7 +235,8 @@ class Monitor(RVGenerator): def __init__(self, extra_params={}): super().__init__(extra_params) - self.trace_h = self._read_template_file("trace.h") + if not self.bpf: + self.trace_h = self._read_template_file("trace.h") def fill_trace_h(self): trace_h = self.trace_h
@@ -245,6 +256,7 @@ class Monitor(RVGenerator): def print_files(self): super().print_files() - trace_h = self.fill_trace_h() - path = f"{self.name}_trace.h" - self._create_file(path, trace_h) + if not self.bpf: + trace_h = self.fill_trace_h() + path = f"{self.name}_trace.h" + self._create_file(path, trace_h)
tools/verification/rvgen/rvgen/templates/dot2k/main_bpf.c new file +21 -0
@@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" + +#define RV_MON_TYPE RV_MON_%%MONITOR_TYPE%% +#include "%%MODEL_NAME%%.h" +#include <rv/da_monitor.h> + +/* +* This is the instrumentation part of the monitor. +* +* This is the section where manual work is required. Here the kernel events +* are translated into model's event. +*/ +%%TRACEPOINT_HANDLERS_SKEL%% +static struct rv_monitor rv_this = { + .enabled =0 , +}; + +char LICENSE[] SEC("license") = "GPL"; +char DESCRIPTION[] SEC(".rodata.description") = "%%DESCRIPTION%%";
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 13/15] verification/rvgen: Add support for BPF monitors
TL;DR: In rvgen, with -b and -a, the printed messages and checklist point to a nonexistent {monitor.name}/ directory and never say the sources went to bpf_monitors/. Should they print that location?
Quoted 1 line
verification/rvgen: Add support for BPF monitors
TL;DR: In rvgen, with -b and -a, the printed messages and checklist point to a nonexistent {monitor.name}/ directory and never say the sources went to bpf_monitors/. Should they print that location?
Quoted 3 lines
tools/verification/rvgen/__main__.py +0
-0
[ ... ]
Quoted 4 lines
tools/verification/rvgen/__main__.py +0
-0@@ -80,7 +85,9 @@ if __name__ == '__main__': print("Almost done, checklist") if params.subcmd == "monitor": print(f" - Edit the {monitor.name}/{monitor.name}.c to add the instrumentation")
tools/verification/rvgen/__main__.py if __name__ == '__main__': · line 93
Quoted 10 lines
tools/verification/rvgen/__main__.py +6
-4- print(monitor.fill_tracepoint_tooltip()) - print(monitor.fill_makefile_tooltip()) - print(monitor.fill_kconfig_tooltip()) - print(monitor.fill_monitor_tooltip()) + if not params.bpf: + print(monitor.fill_tracepoint_tooltip()) + if not params.subcmd == "monitor" or not params.bpf: + print(monitor.fill_makefile_tooltip()) + print(monitor.fill_kconfig_tooltip()) + print(monitor.fill_monitor_tooltip())
With -b and -a, does this checklist point to a path that is never created?
RVGenerator.__create_directory() returns early for this case:
if self.auto_patch:
if self.bpf:
# no directory for BPF monitors
return
and RVGenerator._create_file() writes the files to self.rv_tool_dir, which resolves to tools/verification/rv/bpf_monitors/<name>.c in the kernel tree:
if self.bpf:
path = Path(self.rv_tool_dir) / file_name
But __main__ still prints "Writing the monitor into the directory {monitor.name}" and "Edit the {monitor.name}/{monitor.name}.c to add the instrumentation", and no {monitor.name}/ directory exists anywhere.
Since fill_monitor_tooltip() is now skipped for BPF monitors, which on the in-kernel -a path prints "Monitor created in {rv_dir}/monitors/{name}", nothing in the output tells the user where the generated sources were written. Should the BPF -a case print the bpf_monitors/ location instead?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Gabriele Monaco
maintainerPATCH v2 14/15 tools/rv: Add selftest for rv bpf monitors
In reply to Gabriele MonacoAdd selftest cases for the rv userspace tool BPF monitors, test BPF monitors listing and functionality, including traces and reactors.
--- tools/verification/rv/tests/rv_list.t | 6 ++- tools/verification/rv/tests/rv_mon.t | 61 ++++++++++++++++++++++++++- 2 files changed, 65 insertions(+), 2 deletions(-)
tools/verification/rv/tests/rv_list.t +5 -1
@@ -6,6 +6,8 @@ test_begin set_timeout 30s RVDIR=/sys/kernel/tracing/rv/ +# only works when running in the kernel tree +RVTOOL=$(dirname "$RV") # Help and basic tests check "verify help page" \
@@ -17,13 +19,15 @@ check "verify list subcommand help" \ all_nested=$(grep : $RVDIR/available_monitors | cut -d: -f2 | paste -s | sed 's/\t/\\|/g') all_non_nested=$(grep -v : $RVDIR/available_monitors | cut -d: -f2 | paste -s | sed 's/\t/\\|/g') sched_monitors=$(grep sched: $RVDIR/available_monitors | cut -d: -f2 | paste -s | sed 's/\t/\\|/g') +all_bpf=$(find "$RVTOOL/bpf_monitors" -name "*.o" -exec basename \{} .o \; | paste -s | sed 's/\t/\\|/g') description_state="[[:space:]]\+[[:print:]]\+\[\(OFF\|ON\)\]" line_nested=" - \($all_nested\)${description_state}" line_non_nested="\($all_non_nested\)${description_state}" +line_bpf="\($all_bpf\)${description_state}" # List monitors and containers check "list all monitors" \ - "$RV list" 0 "" "" "^\($line_nested\|$line_non_nested\)$" + "$RV list" 0 "" "" "^\($line_nested\|$line_non_nested\|$line_bpf\)$" check_if_exists "list container" \ "$RV list sched" "$RVDIR/monitors/sched" \
tools/verification/rv/tests/rv_mon.t +60 -1
95 lines not on this page · raw message
Signature · 1 line
2.55.0
[email protected]
AI reviewRe: [PATCH v2 14/15] tools/rv: Add selftest for rv bpf monitors
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Medium] selftests/rv: catch-all regex bypasses exact monitor name validation if BPF uncompiled…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Medium] selftests/rv: catch-all regex bypasses exact monitor name validation if BPF uncompiled
- [Medium] selftests/rv: spurious failure due to missing check for BPF monitor presence --
commit 47b33f7df8aa5888f987d177930041a5edcca5ec
Author: Gabriele Monaco <[email protected]>
tools/rv: Add selftest for rv bpf monitors
This commit adds selftest cases for the rv userspace tool BPF monitors. It tests BPF monitor listing, functionality, traces, and reactors.
Quoted 8 lines
tools/verification/rv/tests/rv_list.t +0
-0@@ -17,13 +19,15 @@ check "verify list subcommand help" \ all_nested=$(grep : $RVDIR/available_monitors | cut -d: -f2 | paste -s | sed 's/\t/\\|/g') all_non_nested=$(grep -v : $RVDIR/available_monitors | cut -d: -f2 | paste -s | sed 's/\t/\\|/g') sched_monitors=$(grep sched: $RVDIR/available_monitors | cut -d: -f2 | paste -s | sed 's/\t/\\|/g')
tools/verification/rv/tests/rv_list.t check "verify list subcommand help" \ · line 30
Quoted 10 lines
tools/verification/rv/tests/rv_list.t +3
-1+all_bpf=$(find "$RVTOOL/bpf_monitors" -name "*.o" -exec basename \{} .o \; | paste -s | sed 's/\t/\\|/g') description_state="[[:space:]]\+[[:print:]]\+\[\(OFF\|ON\)\]" line_nested=" - \($all_nested\)${description_state}" line_non_nested="\($all_non_nested\)${description_state}" +line_bpf="\($all_bpf\)${description_state}" # List monitors and containers check "list all monitors" \ - "$RV list" 0 "" "" "^\($line_nested\|$line_non_nested\)$" + "$RV list" 0 "" "" "^\($line_nested\|$line_non_nested\|$line_bpf\)$"
[Severity: Medium]
If the BPF monitors are not compiled, all_bpf will be empty, making line_bpf evaluate to "\(\)[[:space:]]\+[[:print:]]\+\[\(OFF\|ON\)\]".
When this is combined in the catch-all regex "^(...) $", does this accidentally allow any line starting with a space to pass validation instead of strictly enforcing the monitor names?
Quoted 5 lines
tools/verification/rv/tests/rv_mon.t +0
-0
tools/verification/rv/tests/rv_mon.t if [ -d $RVDIR/monitors/wwnr ]; then · line 32
Quoted 9 lines
tools/verification/rv/tests/rv_mon.t +6
-0@@ -23,13 +24,34 @@ if [ -d $RVDIR/monitors/wwnr ]; then check "invalid reactor name" \ "$RV mon wwnr -r invalid" 1 "failed to set invalid reactor, is it available?" +check "invalid BPF reactor name" \ + "$RV mon nohz -r invalid" 1 "failed to set invalid reactor, is it available?" + +check "invalid BPF reactor name check available" \ + "$RV mon nohz -r invalid" 1 "available BPF reactors: nop [a-z]\+" \ + "available reactors:"
[Severity: Medium]
Since this check for the nohz BPF monitor is guarded only by the presence of the wwnr in-kernel monitor, can it cause spurious failures if the BPF monitors were not built but wwnr is present?
If nohz.o is missing, the command will fail with "monitor nohz does not exist" rather than the expected invalid reactor error.
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=14
[email protected]
AI reviewRe: [PATCH v2 14/15] tools/rv: Add selftest for rv bpf monitors
In reply to Gabriele MonacoTL;DR: Selftest issue: the two back-to-back tqueue runs in rv_mon.t may fail with "already enabled" because the previous run's BPF maps aren't freed yet; a sleep like the nohz tests use may be needed.
Quoted 1 line
tools/rv: Add selftest for rv bpf monitors
TL;DR: Selftest issue: the two back-to-back tqueue runs in rv_mon.t may fail with "already enabled" because the previous run's BPF maps aren't freed yet; a sleep like the nohz tests use may be needed.
Quoted 3 lines
tools/verification/rv/tests/rv_mon.t +0
-0
[ ... ]
tools/verification/rv/tests/rv_mon.t check_if_exists "run per-cpu monitor tracing also self" \ · line 144
Quoted 12 lines
tools/verification/rv/tests/rv_mon.t +8
-0@@ -92,4 +134,21 @@ check_if_exists "run per-cpu monitor tracing also self" \ "$RV mon sco -t -s" "$RVDIR/monitors/sched/sco" \ "$trace_cpu_self" "" "\($header\|$trace_cpu\)" +check_if_exists "run per-task BPF monitor with tracing" \ + "$RV mon tqueue -t" "$RVTOOL/bpf_monitors/tqueue.o" \ + "$header" "$trace_task_self" "\($header\|$trace_task\)" + +check_if_exists "run per-task BPF monitor tracing also self" \ + "$RV mon tqueue -t -s" "$RVTOOL/bpf_monitors/tqueue.o" \ + "$trace_task_self" "" "\($header\|$trace_task\)" +
Can this second tqueue run fail with "monitor tqueue (BPF) is already enabled"?
Earlier in this patch the two consecutive nohz runs are separated by a delay, because the previous run's maps are not necessarily cleaned up yet:
tools/verification/rv/tests/rv_mon.t check_if_exists "run an explicitly nested monitor with a reactor" \ · line 99
Quoted 2 lines
tools/verification/rv/tests/rv_mon.t +2
-0+# Give some time for maps from previous run to be cleaned up +[ -n "$TEST_COUNT" ] && sleep 1
The two tqueue runs here are also back to back, with no delay between "$RV mon tqueue -t" and "$RV mon tqueue -t -s".
bpf_read_enable() decides a monitor is already enabled by walking the map IDs looking for an rv_mon_tqueue map. After the first rv exits, that map stays visible until the deferred frees finish:
bpf_link_free()
bpf_link_is_tracepoint()
call_tracepoint_unregister_atomic() <- SRCU grace period
bpf_prog_put()
bpf_prog_put_deferred()
__bpf_prog_put_noref(prog, true)
call_rcu()
bpf_prog_free()
schedule_work(bpf_prog_free_deferred)
bpf_free_used_maps()
bpf_map_put()
bpf_map_free_id()Until bpf_map_free_id() runs, bpf_map_get_fd_by_id() still succeeds. If the second rv reaches bpf_read_enable() in that window, it prints "bpf:
monitor tqueue (BPF) is already enabled" and exits with 1, while check_if_exists expects 0.
tqueue is a tp_btf monitor, so this chain includes a tracepoint SRCU grace period on top of what the fentry based nohz case has to wait for. Would a similar sleep between these two tqueue runs be needed?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/36944413541
Gabriele Monaco
maintainerPATCH v2 15/15 verification/rvgen: Add selftest for rvgen -b
In reply to Gabriele MonacoAdd selftest cases for BPF monitors generation.
--- .../tests/golden/da_bpf_cpu/da_bpf_cpu.c | 35 +++++++++++++ .../tests/golden/da_bpf_cpu/da_bpf_cpu.h | 47 ++++++++++++++++++ .../tests/golden/da_bpf_obj/da_bpf_obj.c | 49 +++++++++++++++++++ .../tests/golden/da_bpf_obj/da_bpf_obj.h | 47 ++++++++++++++++++ .../verification/rvgen/tests/rvgen_monitor.t | 11 +++++ 5 files changed, 189 insertions(+) create mode 100644 tools/verification/rvgen/tests/golden/da_bpf_cpu/da_bpf_cpu.c create mode 100644 tools/verification/rvgen/tests/golden/da_bpf_cpu/da_bpf_cpu.h create mode 100644 tools/verification/rvgen/tests/golden/da_bpf_obj/da_bpf_obj.c create mode 100644 tools/verification/rvgen/tests/golden/da_bpf_obj/da_bpf_obj.h
tools/verification/rvgen/tests/golden/da_bpf_cpu/da_bpf_cpu.c new file +35 -0
@@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0 + +#include "vmlinux.h" + +#define RV_MON_TYPE RV_MON_PER_CPU +#include "da_bpf_cpu.h" +#include <rv/da_monitor.h> + +/* +* This is the instrumentation part of the monitor. +* +* This is the section where manual work is required. Here the kernel events +* are translated into model's event. +*/ +SEC(/* XXX: tracepoint or other probe */) +int BPF_PROG(handle_event_1, /* XXX: fill header */) +{ +da_handle_event (event_1_da_bpf_cpu); +return 0 ; +} + +SEC(/* XXX: tracepoint or other probe */) +int BPF_PROG(handle_event_2, /* XXX: fill header */) +{ +/* XXX: validate that this event always leads to the initial state */ +da_handle_start_event (event_2_da_bpf_cpu); +return 0 ; +} + +static struct rv_monitor rv_this = { + .enabled =0 , +}; + +char LICENSE[] SEC("license") = "GPL"; +char DESCRIPTION[] SEC(".rodata.description") = "auto-generated";
tools/verification/rvgen/tests/golden/da_bpf_cpu/da_bpf_cpu.h new file +47 -0
47 lines not on this page · raw message
tools/verification/rvgen/tests/golden/da_bpf_obj/da_bpf_obj.c new file +49 -0
49 lines not on this page · raw message
tools/verification/rvgen/tests/golden/da_bpf_obj/da_bpf_obj.h new file +47 -0
47 lines not on this page · raw message
tools/verification/rvgen/tests/rvgen_monitor.t +11 -0
@@ -47,6 +47,17 @@ check_and_compare_folder "LTL per_task with parent and description (default name "$RVGEN monitor -c ltl -s tests/specs/test_ltl.ltl -t per_task -p ltl_parent -D 'Simple description'" \ "test_ltl" "LTL_MON_EVENTS_ID" +# BPF monitor test +check_and_compare_folder "DA BPF per_cpu" \ + "$RVGEN monitor -b -c da -s tests/specs/test_da.dot -t per_cpu -n da_bpf_cpu" \ + "da_bpf_cpu" "Edit the da_bpf_cpu/da_bpf_cpu.c to add the instrumentation" \ + "Edit kernel/trace/rv/Makefile" + +check_and_compare_folder "DA BPF per_obj" \ + "$RVGEN monitor -b -c da -s tests/specs/test_da.dot -t per_obj -n da_bpf_obj" \ + "da_bpf_obj" "Edit the da_bpf_obj/da_bpf_obj.c to add the instrumentation" \ + "Edit kernel/trace/rv/Kconfig" + # Error handling tests check "missing required spec argument" \ "$RVGEN monitor -c da -t per_cpu" 2 \
Signature · 1 line
2.55.0