Commit Graph
100 Commits
Author SHA1 Message Date
Masami Hiramatsu (Google) c15120853e tracing/uprobes: Fix memory leak of tail in __trace_uprobe_create()
When generating a default event name in __trace_uprobe_create(), tail is
allocated with kstrdup() without __free(kfree). If the subsequent
kmalloc() for buf fails, the function returns -ENOMEM immediately and
leaks tail.

Declare tail with __free(kfree) so it is automatically freed on all
exit paths.

Link: https://lore.kernel.org/all/179455856197.403392.16569431894958507645.stgit@devnote2/

Reported-by: Sashiko <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Fixes: 97e8230f89 ("tracing: uprobe-event: Allocate string buffers from heap")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 23:06:31 +09:00
Masami Hiramatsu (Google) 0941144ebe tracing/probes: Reject array count on non-dereference string sources
The runtime array loop (FETCH_OP_LP_ARRAY) for string types requires a
preceding memory dereference instruction so it can advance the pointer
address on each iteration. Non-dereference string sources such as $comm,
immediate strings, and eprobe event fields cannot be indexed as pointer
arrays, but finalize_fetch_insn() still accepts an array count on them
and emits an invalid FETCH_OP_LP_ARRAY sequence.

Reject string array counts when the preceding operation is not a memory
dereference.

Link: https://lore.kernel.org/all/179455855309.403392.4197028577158545202.stgit@devnote2/

Fixes: 40b53b7718 ("tracing: probeevent: Add array type support")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 23:06:23 +09:00
Masami Hiramatsu (Google) 2721573e6c tracing/probes: Fix user-space dereference string array store type
When finalizing a string array argument (e.g. +0u(%reg):string[N]),
finalize_fetch_insn() advances the instruction pointer to a new slot
for the store operation before checking whether the preceding operation
was FETCH_OP_UDEREF. As a result, user-space dereference string arrays
with type "string" emit FETCH_OP_ST_STRING (kernel memory read) instead
of FETCH_OP_ST_USTRING.

Check for FETCH_OP_UDEREF before advancing the instruction pointer.

Link: https://lore.kernel.org/all/179455854396.403392.18073771811100192405.stgit@devnote2/

Fixes: e65f7ae7f4 ("tracing/probe: Support user-space dereference")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 23:05:56 +09:00
Masami Hiramatsu (Google) 92d9fa0ed6 tracing/eprobe: Disallow attaching eprobes to fprobe events
Event probes (eprobes) are not allowed to attach to other dynamic probe
events (kprobes, uprobes, and eprobes) to avoid recursive probe chains
and lifecycle dependencies. However, when fprobe events were introduced,
TRACE_EVENT_FL_FPROBE was omitted from the exclusion mask in
find_and_get_event(), allowing eprobes to attach to fprobe and tprobe
events.

Exclude TRACE_EVENT_FL_FPROBE events in find_and_get_event().

Link: https://lore.kernel.org/all/179455853457.403392.14549390017750529531.stgit@devnote2/

Fixes: 334e5519c3 ("tracing/probes: Add fprobe events for tracing function entry and exit.")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 23:05:46 +09:00
Masami Hiramatsu (Google) a0f836eea4 tracing/eprobe: Fix 1-byte signed field fetch in get_event_field()
Because the kernel is built with -funsigned-char, plain 'char' is
unsigned on all architectures. Reading 1-byte signed trace event fields
via *(char *)addr in get_event_field() therefore zero-extends instead of
sign-extending negative s8 values.

Use explicit fixed-width integer types (s8/u8, s16/u16, s32/u32) when
reading event fields.

Link: https://lore.kernel.org/all/179455852542.403392.15666310371702309464.stgit@devnote2/

Fixes: 7491e2c442 ("tracing: Add a probe that attaches to trace events")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 23:05:30 +09:00
Masami Hiramatsu (Google) c1e2c63e65 tracing/probes: Fix missing BTF kind checks in char pointer/array helpers
In struct btf_type, the type ID and byte size share a union, and only
BTF_KIND_INT types are followed by a 32-bit integer encoding word.
Because btf_type_is_char_ptr() and btf_type_is_char_array() do not
verify that the outer type is BTF_KIND_PTR or that the resolved element
type is a non-NULL BTF_KIND_INT before inspecting it, non-pointer BTF
types can have their byte size misinterpreted as a BTF type ID, and
arrays of non-integer types read out-of-bounds or misinterpret trailing
BTF metadata as BTF_INT_* encoding bits.

Validate the BTF type kinds and NULL pointers before reading inner type
metadata in both helpers.

Link: https://lore.kernel.org/all/179455851632.403392.258264246782960594.stgit@devnote2/

Fixes: 27973e5c64 ("tracing/probes: Add string type check with BTF")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 23:04:56 +09:00
Masami Hiramatsu (Google) 9b6e9d6a11 tracing/probes: Fix BTF bitfield parsing and out-of-bounds buffer write
BTF bitfield parsing in trace_probe.c assumes a 64-bit (8-byte) container
when computing FETCH_OP_MOD_BF shift amounts and basesize, whereas the
preceding store instruction only allocates and writes the field's fetch
type size (which may be 1, 2, or 4 bytes when kflag=1). At runtime,
fetch_apply_bitfield() performs an 8-byte read-modify-write on the
smaller ring buffer slot, corrupting adjacent ring buffer data or writing
past the end of the event record.

In addition, signed bitfields with bit widths other than 8/16/32/64 fail
to resolve a fetch type, bitfields whose width is a multiple of 8 inside
a larger integer or spanning a byte boundary fail to emit FETCH_OP_MOD_BF
or select a container wide enough for bitoffs + bitsize, kflag=0 bitfield
offsets >= 8 bits are not folded into the byte offset, and big-endian
architectures use the little-endian left-shift formula in
parse_btf_bitfield().

Compute the bitfield byte and bit offsets consistently during field
lookup, select the smallest unsigned fetch type that covers the bit
offset and bit width, and calculate the FETCH_OP_MOD_BF parameters from
the selected fetch type size for both big- and little-endian bitfields.

Link: https://lore.kernel.org/all/179455850711.403392.10512730891220678403.stgit@devnote2/

Fixes: c440adfbe3 ("tracing/probes: Support BTF based data structure field access")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 23:04:48 +09:00
Masami Hiramatsu (Google) 72d3a5cb0c tracing/probes: Enable newly appended probe when target event is enabled
Unlike kprobe events, fprobe and uprobe events only register their
underlying probes when the trace event is enabled. When a new probe is
appended to an existing multiprobe fprobe or uprobe event that is
already enabled, the appended probe is linked into the event's probe
list without being registered.

As a result, the newly appended probe never fires until the event is
disabled and re-enabled. Moreover, disabling an fprobe event calls
unregister_fprobe() on the unregistered fprobe, and opening or closing a
perf event on an enabled uprobe event dereferences a NULL tu->uprobe in
uprobe_apply().

Register and enable the newly appended fprobe or uprobe immediately when
the target event is already enabled.

Link: https://lore.kernel.org/all/179455849798.403392.135678786198324285.stgit@devnote2/

Fixes: 41af3cf587 ("tracing/uprobe: Add multi-probe per uprobe event support")
Fixes: 2db832ec90 ("tracing: fprobe-events: Register fprobe-events only when it is enabled")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 23:04:40 +09:00
Masami Hiramatsu (Google) f1d9b7a3fe tracing/probes: Check enabled and busy state before unlinking sibling probes
When a multiprobe event is enabled or referenced (for example, by an
eprobe, trigger, or open tracefs file) and a user attempts to delete the
event or one of its probes via dynamic_events, checking
trace_probe_has_sibling() before the enabled and busy checks allows the
first probe to be unlinked and freed while the event is still active,
only returning -EBUSY on the last sibling probe. For uprobe events,
unlinking and freeing an enabled sibling probe without unregistering its
uprobe_consumer also causes a use-after-free.

Ensure all four probe types (kprobe, fprobe, uprobe, and eprobe) verify
that the event is neither enabled nor busy before unlinking any sibling
probe.

Link: https://lore.kernel.org/all/179455848898.403392.17675270675769076596.stgit@devnote2/

Fixes: ca89bc071d ("tracing/kprobe: Add multi-probe per event support")
Fixes: 41af3cf587 ("tracing/uprobe: Add multi-probe per uprobe event support")
Fixes: 7491e2c442 ("tracing: Add a probe that attaches to trace events")
Fixes: 334e5519c3 ("tracing/probes: Add fprobe events for tracing function entry and exit.")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 23:04:31 +09:00
Masami Hiramatsu (Google) c55722233c kprobes: Re-optimize blocked sibling probe when cooling finishes
When an optimized kprobe is disabled (for example, to arm a new kprobe
in its jump-optimized instruction range), its jump is replaced with a
breakpoint (or disarmed) and the probe is placed on the cooling list
until the Tasks RCU grace period completes. While the disabled probe is
still on the cooling list, any sibling probe whose jump range covers
this probe's address cannot be optimized because can_optimize() sees the
not-yet-disarmed probe via get_kprobe().

In optprobe_finalize_generation(), when a disabled probe on cooling_list
finishes cooling and transitions to safely disarmed (list_del_init()),
check whether an optimized sibling probe covers op->kp.addr via
get_optimized_kprobe() and re-queue it for optimization, matching the
freeing_list path in do_free_cleaned_kprobes().

Link: https://lore.kernel.org/all/179440643954.328088.8524265330405527243.stgit@devnote2/

Fixes: 06e0d3b89d ("kprobes: Make optprobe optimizer multi-generational and asynchronous")
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 17:33:04 +09:00
Masami Hiramatsu (Google) 081f8fba97 kprobes: Do not overwrite jump instruction when re-arming unoptimizing probe
When an optimized probe is temporarily disarmed or disabled,
unoptimize_kprobe() places it on the unoptimizing list, but leaves
the relative jump in text until the optimizer thread runs.
__disarm_kprobe() explicitly skips arch_disarm_kprobe() when
kprobe_queued_unopt(p) is true.

However, if __arm_kprobe() is called before the unoptimization pass
executes, it unconditionally calls arch_arm_kprobe(p), writing a
breakpoint instruction over the first byte of the jump while leaving the
trailing bytes intact. optimize_kprobe(p) then dequeues the probe from
the unoptimizing queue, leaving the jump opcode overwritten with a
breakpoint in text while KPROBE_FLAG_OPTIMIZED remains set.

Skip calling arch_arm_kprobe() in __arm_kprobe() when
kprobe_queued_unopt(p) is true, keeping the existing relative jump intact
while unoptimization is cancelled. If optimize_kprobe() cannot optimize
the probe (e.g. due to a post_handler or disabled optimization), force
unoptimization immediately.

Link: https://lore.kernel.org/all/179440642973.328088.10282643330198602134.stgit@devnote2/

Fixes: 06e0d3b89d ("kprobes: Make optprobe optimizer multi-generational and asynchronous")
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 17:32:56 +09:00
Masami Hiramatsu (Google) c8c1e40968 kprobes: Fix UAF and queue cooling probes on forced unoptimization
When unoptimize_kprobe() is called with force = true on an actively
optimized probe (whose op->list is empty), force_unoptimize_kprobe()
replaces the relative jump with a breakpoint, but leaves op->list empty
without queueing op to cur->cooling_list.

Because op->list remains empty, kprobe_disarmed() returns true
prematurely as soon as the probe is disabled. When unregister_kprobes()
runs, __unregister_kprobe_top() unhashes the probe immediately, and
unregister_kprobes() frees op and the optinsn slot after synchronize_rcu()
without waiting for Tasks RCU. Any task preempted inside the optinsn slot
then encounters a use-after-free when resuming execution.

Queue forcibly unoptimized probes onto cur->cooling_list and include
gen->cooling_list in optprobe_has_queued_probes() so that the generation
is dispatched and flushed properly. In do_unoptimize_kprobes(), collect
newly unoptimized probes into a separate local list so that probes
already placed on freeing_list are not processed a second time.

Link: https://lore.kernel.org/all/179440642050.328088.13914468408589377897.stgit@devnote2/

Fixes: 06e0d3b89d ("kprobes: Make optprobe optimizer multi-generational and asynchronous")
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 17:32:47 +09:00
Masami Hiramatsu (Google) f60f98881b kprobes: Switch ftrace ops when adding probe with post_handler
When an ftrace-based kprobe is registered without a post_handler, it is
armed using kprobe_ftrace_ops. If a second probe with a post_handler is
subsequently registered at the same address, register_aggr_kprobe() sets
ap->post_handler to aggr_post_handler, but leaves the probe armed using
kprobe_ftrace_ops.

When the probe is later disarmed or disabled, disarm_kprobe_ftrace()
checks whether p->post_handler is non-NULL and attempts to disarm from
kprobe_ipmodify_ops. This fails with -ENOENT, decrements
kprobe_ipmodify_enabled below zero, leaves the probe armed on
kprobe_ftrace_ops, and aborts unregistration, leading to a use-after-free
if the probe module is unloaded.

Switch the armed probe from kprobe_ftrace_ops to kprobe_ipmodify_ops in
register_aggr_kprobe() outside of text_mutex and cpus_read_lock to avoid
lockdep and deadlock issues when modifying ftrace code. Defer adding the
new probe onto ap->list until the ftrace ops switch completes so that the
new probe's handlers are not published prematurely while ap is still on
kprobe_ftrace_ops, and mark ap disabled if rollback re-arming fails.
Also restore ftrace ops registration and counter if ftrace_set_filter_ip()
fails in __disarm_kprobe_ftrace().

Link: https://lore.kernel.org/all/179440641120.328088.15542754095040659094.stgit@devnote2/

Fixes: 5dd7caf0bd ("kprobes: Skip clearing aggrprobe's post_handler in kprobe-on-ftrace case")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-13 17:32:41 +09:00
Masami Hiramatsu (Google) 76a224e04a docs: trace: Warn against using printk() in probe handlers
Probe handlers (kprobes, kretprobes, and fprobes) execute in atomic or
non-preemptible contexts. Because handlers do not run in NMI context
(especially when jump-optimized or ftrace-based), calling printk()
directly can attempt to synchronously acquire console driver locks or
scheduler locks (via console_unlock()), risking a deadlock if the probed
or interrupted context already holds those locks.

Document this restriction in both kprobes.rst and fprobe.rst, and
recommend using trace_printk() instead to safely log messages to the
ftrace buffer.

Link: https://lore.kernel.org/all/179360348516.115681.16358304979974648339.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-06 12:22:40 +09:00
Masami Hiramatsu (Google) df87101f81 samples/fprobe: Use trace_printk() and trace_dump_stack()
Fprobe entry and exit callbacks execute in atomic context with
preemption disabled under ftrace recursion protection. Calling
printk() directly inside handlers can lead to deadlocks if console
or scheduler locks are already held by the probed or interrupted context.

Drop the use_trace module parameter and always use trace_printk()
for handler logging. In addition, replace stack_trace_print() (which
uses printk()) with trace_dump_stack(0) to output backtraces safely
to the ftrace buffer. Also update the module header comment to
reference /sys/kernel/tracing/trace.

Additionally, update CONFIG_SAMPLE_FPROBE in samples/Kconfig to
depend on EVENT_TRACING so that the tracing subsystem is enabled
when building the sample.

Link: https://lore.kernel.org/all/179360347512.115681.7201999490892291449.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-06 12:22:31 +09:00
Masami Hiramatsu (Google) 07038c33e7 samples/kprobes: Use trace_printk() in probe handlers
Probe handlers execute in atomic/non-preemptible contexts. Furthermore,
unless hit via an unoptimized breakpoint on certain architectures,
they do not run with in_nmi() set (e.g. jump-optimized kprobes,
ftrace-based kprobes, or kretprobe return handlers). Calling printk()
from probe handlers can directly attempt to acquire console and
scheduler locks (via console_unlock()), risking a deadlock if the
probed context or interrupted code already holds one of those locks.

Replace printk() (pr_info) in handler_pre(), handler_post(), and
ret_handler() with trace_printk(), and update the comments to direct
users to /sys/kernel/tracing/trace. Also update the stack backtrace
comment in kprobe_example to reference trace_dump_stack(0).

Also fix a minor format string typo ("p->addr," -> "p->addr =") in the
S390 pre and post handlers while touching those lines.

Additionally, update CONFIG_SAMPLE_KPROBES in samples/Kconfig to
depend on EVENT_TRACING so that the tracing subsystem is enabled
when building the samples.

Link: https://lore.kernel.org/all/179360346488.115681.12990812332058260390.stgit@devnote2/

Reported-by: Tiezhu Yang <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-06 12:22:22 +09:00
Masami Hiramatsu (Google) a553b499f2 kprobes: Validate re-registration earlier in register_kretprobe()
register_kretprobe() only checked for re-registration if rp->kp.addr was
specified, skipping the check when rp was registered with symbol_name
and rp->kp.addr was NULL. In that scenario, register_kretprobe()
proceeded to allocate a new rethook (or kretprobe holder), and when
register_kprobe(&rp->kp) subsequently failed due to re-registration, the
error path freed and NULL-ed rp->rh (or rp->rph) on the still-active
kretprobe, leading to NULL pointer dereferences when the active probe
was hit.

Resolve the target address via _kprobe_addr() up-front and check whether
the probe is already registered at that address via
check_kprobe_rereg_at() before allocating any resources, and drop the
WARN_ON_ONCE() in the re-registration check now that re-registration is
gracefully detected and rejected.

Link: https://lore.kernel.org/all/179375032568.247640.17429793187163536192.stgit@devnote2/

Fixes: 0188b87899 ("kretprobe: Avoid re-registration of the same kretprobe earlier")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-05 09:09:52 +09:00
Masami Hiramatsu (Google) 2053bac1d6 kprobes: Fix double free and NULL deref in unregister_kretprobes()
In unregister_kretprobes(), if __unregister_kprobe_top() returns an error
(e.g., if the kretprobe was not registered or was already unregistered),
rethook_free(rps[i]->rh) or rcu_assign_pointer(rps[i]->rph->rp, NULL) is
still executed. For rethook-based kretprobes, calling rethook_free() on an
already-freed rethook causes a double-free / list corruption in RCU. For
legacy kretprobes, rps[i]->rph is NULL after previous cleanup, resulting
in a NULL pointer dereference.

Skip rethook_free() and rph cleanup if __unregister_kprobe_top() fails,
and clear rps[i]->rh after synchronize_rcu() has waited for in-flight
pre_handler_kretprobe() invocations to complete.

Link: https://lore.kernel.org/all/179375031660.247640.6349602689169856649.stgit@devnote2/

Fixes: 73f9b911fa ("kprobes: Use rethook for kretprobe if possible")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-05 09:09:41 +09:00
Masami Hiramatsu (Google) 6a658cc2d6 kprobes: Fix error return and slot leak in __register_kprobe()
When arm_kprobe() fails in __register_kprobe(), the probe is removed
from kprobe_table and synchronize_rcu() is executed, but the error code
ret was ignored and try_to_optimize_kprobe(p) was executed, returning 0.
Additionally, the instruction slot allocated by prepare_kprobe() was
leaked.

Fix this by releasing the instruction slot via arch_remove_kprobe(p)
and returning ret when arm_kprobe() fails.

Link: https://lore.kernel.org/all/179375030756.247640.10859474201266455798.stgit@devnote2/

Fixes: 587e8e6d64 ("kprobes: Adopt guard() and scoped_guard()")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-11-05 09:08:25 +09:00
Masami Hiramatsu (Google) 5c45831072 bootconfig: skip internal tree sanity checks in kernel
In xbc_verify_tree(), the loop iterating through all nodes to check that
xbc_nodes[i].next < xbc_node_num and xbc_nodes[i].child < xbc_node_num is
a defensive sanity check against implementation regressions (such an
out-of-bounds index cannot be produced by malformed input).

Running this check in the kernel adds unnecessary boot-time overhead. 
Split this check out into xbc_sanity_check_tree() for userspace, so that
it continues to run during userspace bootconfig validation (e.g.  when
applying or testing bootconfig with tools/bootconfig), but is omitted in
the kernel to speed up initialization.

Link: https://lore.kernel.org/178913600409.248794.12941798680046327623.stgit@devnote2
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Reported-by: Sang-Heon Jeon <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Reviewed-by: Sang-Heon Jeon <[email protected]>
2026-10-13 21:25:43 -07:00
Masami Hiramatsu (Google) 3ccfe2a1a8 tracing/probes: Clarify btf_find_struct_member() container parameter and add kernel-doc
btf_find_struct_member() returns the containing structure or union type
(which can be an inner anonymous struct/union rather than the outer
passed type) via its last parameter. However, the parameter was named
@member_type, which easily confuses readers and static analyzers into
thinking it returns the member field's own datatype.

Rename @member_type to @container_type in the prototype, definition,
and callers to make the relationship explicit. Also convert the comment
above btf_find_struct_member() to standard kernel-doc format, documenting
all parameters and return values.

Link: https://lore.kernel.org/all/179030954365.77418.17193777972248047975.stgit@devnote2/

Assisted-by: LLM
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-10-12 19:01:56 +09:00
Masami Hiramatsu (Google) d6f97fcebd bootconfig: reject unexpected data after null character
Patch series "bootconfig: Reject unexpected data after null character and
cleanups", v2.

Make bootconfig reject unexpected config data after null character and
implement other cleanups including tools/bootconfig to consolidate
bootconfig initialization with errors, and to skip internal tree sanity
checks in kernel.


This patch (of 4):

If a bootconfig buffer contains an intermediate null character in the
middle of the configuration, xbc_parse_tree() stops at the null character
because string delimiter searches (e.g.  strpbrk()) stop at '\0', and
cleanly breaks out of the loop without error.  As a result, any
configuration data following the intermediate null character is silently
ignored, allowing unparsed or potentially malicious data to be hidden
after an early termination.

Fix this in xbc_parse_tree() by checking that no non-null data remains
between the parser termination point and the end of the input buffer. 
Trailing null characters (such as alignment padding in initrd) continue to
be accepted as valid.

Also update apply_xbc() in tools/bootconfig/main.c to calculate the buffer
size based on the loaded file size rather than strlen(), so that files
with intermediate null characters are not truncated before validation.

Link: https://lore.kernel.org/178913597653.248794.1237187523153227751.stgit@devnote2
Link: https://lore.kernel.org/178913598628.248794.1048773774471250986.stgit@devnote2
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Reviewed-by: Sang-Heon Jeon <[email protected]>
Assisted-by: Antigravity:gemini-3.8-flash
2026-10-10 18:56:46 -07:00
Masami Hiramatsu (Google) 677f83795f bootconfig: Move BOOTCONFIG_FOOTER_SIZE to include/linux/bootconfig.h
BOOTCONFIG_FOOTER_SIZE was defined locally in tools/bootconfig/main.c.
Move it to include/linux/bootconfig.h so that it can be shared with
the kernel and user-space tools. Also, use it in init/main.c instead
of the hardcoded (BOOTCONFIG_MAGIC_LEN + 8) expression when checking
the initrd size.

Link: https://lore.kernel.org/all/178913601321.248794.4786502771058559887.stgit@devnote2/

Suggested-by: Sang-Heon Jeon <[email protected]>
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Sang-Heon Jeon <[email protected]>
2026-10-11 10:33:40 +09:00
Masami Hiramatsu (Google) e84e60da22 bootconfig: Skip internal tree sanity checks in kernel
In xbc_verify_tree(), the loop iterating through all nodes to check that
xbc_nodes[i].next < xbc_node_num and xbc_nodes[i].child < xbc_node_num
is a defensive sanity check against implementation regressions (such
an out-of-bounds index cannot be produced by malformed input).

Running this check in the kernel adds unnecessary boot-time overhead.
Split this check out into xbc_sanity_check_tree() for userspace, so
that it continues to run during userspace bootconfig validation (e.g.
when applying or testing bootconfig with tools/bootconfig), but is
omitted in the kernel to speed up initialization.

Link: https://lore.kernel.org/all/178913600409.248794.12941798680046327623.stgit@devnote2/

Reported-by: Sang-Heon Jeon <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Sang-Heon Jeon <[email protected]>
2026-10-11 10:33:40 +09:00
Masami Hiramatsu (Google) 7871551192 tools/bootconfig: Consolidate xbc_init() to error message wrapper
Use init_xbc_with_error() for all bootconfig initialization in the
bootconfig tool instead of showing errors in different way.

This simplifies the code logic and make it easy to maintain.

Link: https://lore.kernel.org/all/178913599508.248794.10388592925402087434.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-10-11 10:33:40 +09:00
Masami Hiramatsu (Google) fac634087a bootconfig: Reject unexpected data after null character
If a bootconfig buffer contains an intermediate null character in the
middle of the configuration, xbc_parse_tree() stops at the null character
because string delimiter searches (e.g. strpbrk()) stop at '\0', and
cleanly breaks out of the loop without error. As a result, any
configuration data following the intermediate null character is silently
ignored, allowing unparsed or potentially malicious data to be hidden
after an early termination.

Fix this in xbc_parse_tree() by checking that no non-null data remains
between the parser termination point and the end of the input buffer.
Trailing null characters (such as alignment padding in initrd) continue
to be accepted as valid.

Also update apply_xbc() in tools/bootconfig/main.c to calculate the
buffer size based on the loaded file size rather than strlen(), so that
files with intermediate null characters are not truncated before
validation.

Link: https://lore.kernel.org/all/178913598628.248794.1048773774471250986.stgit@devnote2/

Assisted-by: LLM
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Sang-Heon Jeon <[email protected]>
2026-10-11 10:29:43 +09:00
Masami Hiramatsu (Google) 958c01049e bootconfig: Skip printing early params to cmdline from bootconfig
If user configures `kernel.key` in bootconfig, the 'key' is shown
in kernel cmdline (/proc/cmdline) and kernel boot parameter
handler associated with 'key' is invoked. However, since the
bootconfig does not support the parameter defined with early_param,
those keys are shown in '/proc/cmdline' but not handled by kernel.

This could easily mislead users who expected to be able to specify
early parameters via the boot configuration, leading them to wonder
why it doesn't work.

Let's skip printing out early params to cmdline buffer, and warn
if there is such parameters in bootconfig.

Link: https://lore.kernel.org/all/178844899530.263905.7707547252181797215.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-10-11 09:07:10 +09:00
Masami Hiramatsu (Google) 06e0d3b89d kprobes: Make optprobe optimizer multi-generational and asynchronous
Currently, kprobe_optimizer() holds kprobe_mutex, text_mutex, and
cpus_read_lock() simultaneously while executing synchronize_rcu_tasks().
Under PREEMPT_LAZY and server workloads with long-running CPU-bound kernel
tasks or heavy cgroup writeback loops, synchronize_rcu_tasks() can block
for seconds to minutes. Because text_mutex and cpus_read_lock() are held
during this entire wait, any concurrent static key updates, module
loading/unloading, CPU hotplug, or tracing updates stall, frequently
triggering hung-task detector panics.

Instead of penalizing the kernel preemption path with invasive hooks and
global hash lookups, decouple kprobe jump optimization from synchronous
waiting entirely:

1. Replace synchronize_rcu_tasks() with call_rcu_tasks(). Locks
   (text_mutex and cpus_read_lock()) are held only for the brief moment
   needed to patch instructions via arch_unoptimize_kprobes() and
   arch_optimize_kprobes() (microseconds), and are completely released
   while waiting for the Tasks RCU grace period.

2. Introduce a fixed ring of generations (optprobe_gens[OPTPROBE_GEN_MAX])
   to avoid any dynamic memory allocation (kmalloc) or -ENOMEM failure
   modes.

3. The last generation slot in the array is reserved as a "waiting room"
   and is not dispatched to RCU until another in-flight generation has
   finished. While a generation is waiting for its Tasks RCU grace period,
   any newly registered or unregistered probes accumulate in the waiting
   room generation without blocking or requiring additional slots.

4. When the Tasks RCU callback fires, it marks the generation as ready
   and wakes up the optimizer thread to finalize optimization (poking
   the jump instructions) and free cleaned probe slots. Once finalized,
   the generation is marked idle, allowing the waiting room generation
   to be dispatched next.

5. Flushing via wait_for_kprobe_optimizer() waits asynchronously for all
   in-flight and queued generations to drain without stalling other
   kernel subsystems.

On non-preemptive kernels or configs where CONFIG_TASKS_RCU=n,
call_rcu_tasks() transparently aliases to call_rcu(), preserving full
portability.

Link: https://lore.kernel.org/all/179091652953.526694.3402334249215311330.stgit@devnote2/

Assisted-by: LLM
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-10-03 09:27:54 +09:00
Masami Hiramatsu (Google) 313cb5169f selftests/ftrace: Add persistent ring buffer testcases
Add test cases for persistent ring buffer (reserve_mem= combined
with trace_instance=) and backup instance (trace_instance=backup=boot_map).

These test cases verify:
 - persistent-01-reserve-mem: Memory reservation via reserve_mem=
   and trace_instance=boot_map@trace. Verifies trace data retention in
   the boot_map instance across guest crash/reboot via sysrq-trigger.
 - persistent-02-backup-instance: Backup instance creation via
   trace_instance=backup=boot_map. Verifies that previous boot trace
   log is preserved in the backup instance on the subsequent boot.

These test cases specify '# REBOOT: 1' to enable multi-boot guest
crash/reboot testing with doubled QEMU timeout.

Link: https://lore.kernel.org/all/178649544683.438282.14573895196260214231.stgit@devnote2/

Assisted-by: LLM
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-10-03 09:27:54 +09:00
Masami Hiramatsu (Google) 8dd296e4ec selftests/ftrace: Add kernel cmdline tracing testcases
Add test cases for kernel command-line tracing options. It verifies
various parameters like trace_buf_size and trace_options by reading
the output of tracing files in sysfs.

Link: https://lore.kernel.org/all/178649543741.438282.2638887907664217934.stgit@devnote2/

Assisted-by: LLM
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-10-03 09:27:54 +09:00
Masami Hiramatsu (Google) 50cc9e8fe8 selftests/ftrace: Add boot-time tracing testcases
Add test cases for boot-time tracing configuration via bootconfig
(see Documentation/trace/boottime-trace.rst).

These test cases verify:
 - 01-kprobe: Dynamic kprobe events via bootconfig
 - 02-synth: Synthetic events via bootconfig
 - 03-eprobe: Event probes (eprobes) via bootconfig
 - 04-fprobe: Function probes (fprobes) via bootconfig
 - 05-tprobe: Tracepoint probes via bootconfig
 - 06-instance: Custom trace instances via bootconfig

Link: https://lore.kernel.org/all/178649542809.438282.16167291066989252262.stgit@devnote2/

Assisted-by: LLM
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-10-03 09:27:54 +09:00
Masami Hiramatsu (Google) e0a6249190 fprobe: Use guard(rcu_sched_notrace) and check rcu_is_watching()
unregister_fprobe() and unregister_fprobe_async() (used by BPF
kprobe-multi) rely on standard RCU grace periods (synchronize_rcu()
and call_rcu()) to wait until in-flight fprobe handlers complete before
freeing the fprobe.

However, if an fprobe handler executes while RCU is not watching (such
as in the idle loop or nohz_full extended quiescent states), standard
RCU does not track preemption-disabled sections. Consequently,
synchronize_rcu() does not wait for those executions, which can lead
to a use-after-free if the fprobe is freed immediately after
unregistration. Ensure handlers exit early when !rcu_is_watching().

Furthermore, fprobe_fgraph_entry() and fprobe_ftrace_entry() previously
used guard(rcu)() and rcu_read_lock(), which invoke lockdep on every
hit under CONFIG_PROVE_LOCKING. This adds overhead and can cause lockdep
recursion if probed functions interact with lockdep.

Since rhltable_lookup() and rhl_for_each_entry_rcu() use
rcu_dereference_all_check() (which checks rcu_read_lock_any_held()),
holding preemption disabled via rcu_read_lock_sched_notrace() is fully
valid and sufficient so long as rcu_is_watching() is true.

Define and use guard(rcu_sched_notrace)() across fprobe_ftrace_entry(),
fprobe_fgraph_entry(), and fprobe_return(). This eliminates fast-path
rcu_read_lock() and lockdep overhead while guaranteeing safe grace
period synchronization.

Link: https://lore.kernel.org/all/179064115227.394389.16910234241400391996.stgit@devnote2/

Reported-by: Sashiko <[email protected]>
Closes: https://sashiko.dev/#/bug/linux-e46bcd68-4a56-4f19-a255-e3772980e5e3
Fixes: 657b594b20 ("fprobe: Fix unregister_fprobe() to wait for RCU grace period")
Cc: [email protected]
Assisted-by: LLM
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Paul E. McKenney <[email protected]>
2026-09-30 08:41:31 +09:00
Masami Hiramatsu (Google) e666e65283 selftests/ftrace: Add generic boot tracing test framework
Add a generic test framework under tools/testing/selftests/ftrace/boottime/
to verify kernel boot tracing configurations (bootconfig, kernel
command-line tracing options, and persistent ring buffers) during early
boot.

The test runner (run_boottime_test.sh) sources ktap_helpers.sh to generate
output in TAP version 13 format. It builds a minimal initramfs with busybox,
dynamically resolves test specifications (.bconf for bootconfig, .cmdline
for kernel boot parameters, .qemuopts for QEMU options, and # REBOOT: 1
for multi-boot crash/reboot tests with doubled timeout), boots QEMU, and
runs corresponding tracefs checker scripts.

Link: https://lore.kernel.org/all/178649541846.438282.672153252242971310.stgit@devnote2/

Assisted-by: LLM
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-09-30 00:09:41 +09:00
Masami Hiramatsu (Google) b8d1d5b63a x86/mce: Fix hardware debug register corruption on task migration
In exc_machine_check_user(), local_db_save() and local_db_restore() are
invoked in the outer entry stubs (DEFINE_IDTENTRY_MCE_USER,
DEFINE_FREDENTRY_MCE, and DEFINE_IDTENTRY_RAW), surrounding
exc_machine_check_user().

However, exc_machine_check_user() calls irqentry_exit_to_user_mode(), which
handles pending thread work and may schedule() if TIF_NEED_RESCHED is set. If
the task migrates to another CPU during schedule(), local_db_restore() runs on
the new CPU with the dr7 state saved from the old CPU. This corrupts the new
CPU's DR7 hardware debug register and leaves the old CPU's DR7 disabled.  In
short, local_db_save() and local_db_restore() pair must be run on the same
CPU.

To fix this, move local_db_save() and local_db_restore() inside
exc_machine_check_user() and exc_machine_check_kernel(). In
exc_machine_check_user(), DR7 is saved and restored strictly around
do_machine_check() to avoid schedule() during migration. In
exc_machine_check_kernel(), local_db_save() is called at the entry point to
prevent early memory accesses from triggering nested #DB exceptions, and
restored on all exits.

Fixes: cd840e424f ("x86/entry, mce: Disallow #DB during #MC")
Assisted-by: LLM
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Borislav Petkov (AMD) <[email protected]>
Acked-by: Peter Zijlstra (Intel) <[email protected]>
Cc: <[email protected]>
Link: https://patch.msgid.link/179005109564.388919.3937970081044095776.stgit@devnote2
2026-09-23 11:28:56 -07:00
Masami Hiramatsu (Google) 7812d6dab0 bootconfig: Fix integer overflow in initrd size check
Sashiko reported that in get_boot_config_from_initrd(), a crafted initrd
with a huge bootconfig size (such as 0xFFFFFFFF) can cause the pointer
arithmetic:

    data = ((void *)hdr) - size;

to wrap around on 32-bit systems (or when pointer subtraction overflows).
Because data wraps around, the subsequent bounds check:

    if ((unsigned long)data < initrd_start)

evaluates to false, bypassing the check. The kernel then calls
xbc_calc_checksum(data, size), which attempts to read 4GB of memory,
hitting unmapped pages and triggering a fatal kernel page fault during
early boot. Furthermore, on 64-bit systems with an initrd > 4.29 GB, an
unbounded 32-bit size can similarly bypass the initrd_start check.

Fix this by:
1. Ensuring the initrd is at least large enough to contain the bootconfig
   footer and verifying hdr is within the initrd bounds.
2. Checking that size does not exceed XBC_DATA_MAX and does not exceed
   the available space between initrd_start and hdr before performing
   pointer subtraction.

Link: https://lore.kernel.org/all/178905333479.213925.1358412668943562406.stgit@devnote2/

Fixes: de462e5f10 ("bootconfig: Fix to remove bootconfig data from initrd while boot")
Cc: [email protected]
Reported-by: Sashiko <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Assisted-by: Antigravity:gemini-3.8-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Sang-Heon Jeon <[email protected]>
2026-09-11 23:06:10 +09:00
Masami Hiramatsu (Google) 462d0b066b tools/bootconfig: Fix integer overflow and truncation in size checks
Sashiko reported that on 32-bit systems, if an attacker crafts size in
the bootconfig footer such that adding BOOTCONFIG_FOOTER_SIZE wraps around
(for instance, if size is 0xFFFFFFFF), the size check in
load_xbc_from_initrd() can be bypassed:

    if (stat.st_size < size + BOOTCONFIG_FOOTER_SIZE) {
        pr_err("bootconfig size is too big\n");
        return -E2BIG;
    }

Furthermore, on 64-bit systems with an initrd > 4.29 GB, comparing a
corrupted 32-bit size (e.g. 0xFFFFFFFF) against
stat.st_size - BOOTCONFIG_FOOTER_SIZE can also bypass the check if
size is not bounded. Similarly, load_xbc_file() passes 64-bit stat.st_size
directly into the 32-bit int size parameter of load_xbc_fd(), truncating
large standalone files (>= 2GB).

In both cases, passing 0xFFFFFFFF to load_xbc_fd() truncates to -1,
resulting in malloc(0), an integer overflow in read(), and an
out-of-bounds null-byte write.

Fix this by:
1. Rejecting size > XBC_DATA_MAX or
   size > stat.st_size - BOOTCONFIG_FOOTER_SIZE in load_xbc_from_initrd().
2. Rejecting stat.st_size > XBC_DATA_MAX in load_xbc_file() before passing
   it to load_xbc_fd().
3. Checking size < 0 || size > XBC_DATA_MAX defensively in load_xbc_fd().

Link: https://lore.kernel.org/all/178905332413.213925.3179977110281463499.stgit@devnote2/

Fixes: 950313ebf7 ("tools: bootconfig: Add bootconfig command")
Cc: [email protected]
Reported-by: Sashiko <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Closes: https://lore.kernel.org/all/[email protected]/
Assisted-by: Antigravity:gemini-3.8-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Sang-Heon Jeon <[email protected]>
2026-09-11 23:05:38 +09:00
Masami Hiramatsu (Google) d7dbdd2ee0 tracing: Fix to avoid creating trace instances with duplicate names
Since commit e645535a95 ("tracing: Add option to use memmapped
memory for trace boot instance") changed trace_array_get_by_name() to
trace_array_create_systems(), enable_instances() does not reuse the
same name instance. Therefore, if an administrator mistakenly specifies
multiple `trace_instance=` options with duplicate names, all are
created but only the first is accessible via tracefs.

Check whether an instance with the same name already exists before
creating a new one, and reject duplicates with a warning.

Link: https://patch.msgid.link/178847790399.283263.5313150997200138426.stgit@devnote2
Fixes: e645535a95 ("tracing: Add option to use memmapped memory for trace boot instance")
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-09-04 11:44:40 -04:00
Masami Hiramatsu (Google) 0c4256196b kprobes: Protect kprobe_blacklist with RCU
__within_kprobe_blacklist() traverses kprobe_blacklist without holding
kprobe_mutex. When a module is unloaded, kprobe_remove_area_blacklist()
removes blacklist entries and immediately frees them with kfree().
A concurrent call to within_kprobe_blacklist() can therefore dereference
freed memory.

Furthermore, within_kprobe_blacklist() can be called in atomic or
non-preemptible contexts where the sleeping kprobe_mutex cannot be taken.

Protect kprobe_blacklist with RCU. Use guard(rcu)() and
list_for_each_entry_rcu() for traversal, list_add_tail_rcu() for
insertions, list_del_rcu() for deletions, and kfree_rcu() to reclaim
entries safely after a grace period.

Link: https://lore.kernel.org/all/178810004323.64882.16493230858653316962.stgit@devnote2/

Fixes: 376e242429 ("kprobes: Introduce NOKPROBE_SYMBOL() macro to maintain kprobes blacklist")
Cc: [email protected]
Reported-by: Sashiko <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Assisted-by: Antigravity:gemini-3.7-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-09-03 09:04:25 +09:00
Masami Hiramatsu (Google) 871e07b6e3 tracing/probes: Fix code indent in get_bitoffset_of_field()
Fix code block indentation introduced by commit f218345240
("tracing/probes: Support field specifier option for typecast").

Link: https://lore.kernel.org/all/178827252027.123716.7095571176291547259.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Steven Rostedt <[email protected]>
2026-09-03 09:04:25 +09:00
Masami Hiramatsu (Google) 47e93045a2 tracing/probes: Fix BTF kflag check for anonymous struct member access
btf_find_struct_member() traverses into nested anonymous structures and
unions to find a struct member. However, get_bitoffset_of_field() in
trace_probe.c checked btf_type_kflag(type) using the outer parent type
instead of the actual anonymous structure/union that directly contains
the found member.

If the parent structure and anonymous structure have mismatched kflags
(e.g., the parent has kflag=0 while the anonymous structure has kflag=1
because it contains bitfields), the bitfield size encoded in the upper
8 bits of member->offset is erroneously treated as part of the byte/bit
offset, corrupting the resolved offset and failing to set last_bitsize.
Similarly, btf_find_struct_member() pushed anonymous member offsets
onto anon_stack without masking BTF_MEMBER_BIT_OFFSET() when kflag is set.

To fix this problem, update btf_find_struct_member() to return actual
containing structure/union type via member_type, use appropriate
__btf_member_bit_offset() to get bit offset, and use member_type for
btf_type_kflag() in get_bitoffset_of_field().

Link: https://lore.kernel.org/all/178827250904.123716.17452648791331881284.stgit@devnote2/

Fixes: c440adfbe3 ("tracing/probes: Support BTF based data structure field access")
Cc: [email protected]
Reported-by: Sashiko <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Assisted-by: Antigravity:gemini-3.7-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Steven Rostedt <[email protected]>
2026-09-03 09:04:25 +09:00
Masami Hiramatsu (Google) f36d94a20c tracing/probes: Fix anon_stack check for unnamed bitfields in btf_find_struct_member
btf_find_struct_member() traverses into nested anonymous structures
and unions by pushing members with !member->name_off onto anon_stack.
However, it does not consider the unnamed bitfields (e.g. `int : 5`
or `unsigned int : 0`) which also have member->name_off == 0.

If such an unnamed bitfield is pushed to anon_stack, the
btf_find_struct_member() return an error even if there are other
valid entries in anon_stack.

To fix this, only push unnamed struct/union members to anon_stack.
Also move the btf_type_is_struct() check to the entry of this function
because now it is sure only struct/union are pushed to anon_stack.

Link: https://lore.kernel.org/all/178827249775.123716.7813217688423513612.stgit@devnote2/

Fixes: 302db0f5b3 ("tracing/probes: Add a function to search a member of a struct/union")
Cc: [email protected]
Reported-by: Sashiko <[email protected]>
Closes: https://lore.kernel.org/all/[email protected]/
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Steven Rostedt <[email protected]>
2026-09-03 09:04:25 +09:00
Masami Hiramatsu (Google) 29a86c5e63 fprobe: Simplify fprobe_remove_ips() by reusing existing helpers
fprobe_remove_ips() manually duplicates the unregister and filter-removal
logic for both graph and ftrace ops. Simplify it by delegating to the
existing fprobe_graph_remove_ips() and fprobe_ftrace_remove_ips() helpers.

Link: https://lore.kernel.org/all/178528139798.102586.5349128066643420018.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.6-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Steven Rostedt <[email protected]>
2026-08-10 17:13:20 +09:00
Masami Hiramatsu (Google) d093d4524b tracing/boot: Add support for eprobe, fprobe, and tprobe events
Boot-time tracing currently supports kprobe-events and synthetic-events
under per-event configuration options.

Extend boot-time tracing to support newly added dynamic probe types:
- event probes (eprobe) under the "eprobes" event group
- function probes (fprobe) under the "fprobes" event group
- tracepoint probes (tprobe) under the "tracepoints" or "tprobes"
  event group

To support this cleanly, update dyn_event_create() in trace_dynevent.c
so that passing NULL as the type parameter delegates to
create_dyn_event(), allowing generic creation of any registered
dynamic event type from a raw command string.

Update Documentation/trace/boottime-trace.rst accordingly to describe
the new per-event bootconfig options.

Link: https://lore.kernel.org/all/178613905149.259829.18185480460810689421.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.6-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>

Changes in v3:
 - Check return values of strscpy() and snprintf() in trace_boot_add_probe_event()
   to prevent silent buffer truncation when constructing probe event strings.

Changes in v2:
 - Fix raw command detection logic for eprobes, fprobes, and tprobes
   by requiring ':' or isspace() after type prefix.
 - Consolidate duplicate loop logic into trace_boot_add_probe_event()
   helper function.
2026-08-08 21:20:55 +09:00
Masami Hiramatsu (Google) faa0e9064a tracing/mmiotrace: Use trace_assign_type() in mmio_print_mark()
In mmio_print_mark(), a raw C cast (struct print_entry *)entry is used to
obtain the print_entry pointer.

Use the standard trace_assign_type() macro instead, matching the usage in
mmio_print_rw() and mmio_print_map().

Link: https://patch.msgid.link/178524301013.56416.9116249028160618790.stgit@devnote2
Assisted-by: Antigravity:gemini-3.6-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-08-07 20:45:58 -04:00
Masami Hiramatsu (Google) 260b20d9b7 ring-buffer: Fix subbuf_ids memory leak in rb_allocate_cpu_buffer() error path
In rb_allocate_cpu_buffer(), cpu_buffer->subbuf_ids is allocated using
kcalloc() when buffer->remote is non-NULL. If a subsequent page allocation
fails (e.g., ring_buffer_desc_page() returns NULL or rb_allocate_pages()
fails), execution jumps to fail_free_reader.

While __free(kfree) automatically frees the outer cpu_buffer structure
at scope exit, kfree(cpu_buffer) does not recursively free nested heap
pointers such as cpu_buffer->subbuf_ids, resulting in a memory leak.

Fix this by explicitly freeing cpu_buffer->subbuf_ids in the
fail_free_reader error unwinding path when cpu_buffer->remote is set.

Link: https://patch.msgid.link/178550740672.380917.6067449683620196150.stgit@devnote2
Fixes: 2e67fabd8b ("ring-buffer: Introduce ring-buffer remotes")
Assisted-by: Antigravity:gemini-3.6-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Vincent Donnefort <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-07-31 19:48:27 -04:00
Masami Hiramatsu (Google) c22c7b735f tracing/filters: Fix false positive match in regex_match_full()
regex_match_full() calls strncmp(str, r->pattern, len) where len is the
target field buffer size. When len is smaller than r->len (the filter
pattern length), strncmp() checks only len bytes of r->pattern against
str. If those len bytes match, strncmp() returns 0, resulting in a
false-positive match where a shorter string in a fixed-size field
matches a longer filter pattern.

For example, a 4-byte static string field containing "abcd" matched the
filter pattern "abcdefgh" because strncmp("abcd", "abcdefgh", 4)
returned 0. In this case, @len does NOT include '\0' because it is
fixed-size array.

Fix this by returning 0 (no match) early when len < r->len.

Fixes: 1889d20922 ("tracing/filters: Provide basic regex support")
Cc: [email protected]
Link: https://patch.msgid.link/178528488779.124250.5571741156199253769.stgit@devnote2
Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-07-29 14:32:11 -04:00
Masami Hiramatsu (Google) ac8719969e tracing: Check return value of __register_event() in trace_module_add_events()
trace_module_add_events() ignores the return value of __register_event()
and unconditionally calls __add_event_to_tracers() for each event.

If __register_event() fails (for example, if event_init() fails), the
trace_event_call is not added to ftrace_events list, but
__add_event_to_tracers() still creates a trace_event_file pointing to it.
If module loading subsequently fails and module memory is freed, tracing
state retains a stale trace_event_call pointer in trace_event_file,
leading to a use-after-free when tracefs or tracing subsystem operations
are later executed.

Fix this by checking the return value of __register_event() and only
calling __add_event_to_tracers() if event registration succeeded.

Fixes: ae63b31e4d ("tracing: Separate out trace events from global variables")
Cc: [email protected]
Link: https://patch.msgid.link/178528487878.124250.14170824576025743236.stgit@devnote2
Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-07-29 14:32:11 -04:00
Masami Hiramatsu (Google) 12b80cdbc5 tracing/mmiotrace: Add NULL check for mmio_trace_array in logging functions
mmio_trace_rw() and mmio_trace_mapping() retrieve mmio_trace_array into
tr and pass it to __trace_mmiotrace_rw() and __trace_mmiotrace_map().
If these functions are invoked while mmio_trace_array is NULL (e.g. before
initialization or after disabled), accessing tr->array_buffer.buffer will
result in a NULL pointer dereference crash.

Fix this by adding an explicit NULL check for tr at the beginning of
__trace_mmiotrace_rw() and __trace_mmiotrace_map().

Link: https://patch.msgid.link/178524300062.56416.8362487250709962380.stgit@devnote2
Fixes: f984b51e07 ("ftrace: add mmiotrace plugin")
Assisted-by: Antigravity:gemini-3.6-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-07-29 14:27:55 -04:00
Masami Hiramatsu (Google) c786d2bdf1 tracing/mmiotrace: Reset dropped_count in mmio_reset_data()
mmio_reset_data() is called during tracer initialization, reset, and
start. While it resets overrun_detected and prev_overruns, it neglects
to reset dropped_count. Consequently, dropped event counts from prior
tracing sessions persist in dropped_count and corrupt overrun reports
in subsequent runs.

Fix this by explicitly calling atomic_set(&dropped_count, 0) in
mmio_reset_data().

Link: https://patch.msgid.link/178524299122.56416.16277704230639425172.stgit@devnote2
Fixes: 173ed24ee2 ("mmiotrace: count events lost due to not recording")
Assisted-by: Antigravity:gemini-3.6-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-07-29 14:27:55 -04:00
Masami Hiramatsu (Google) 8cf2f40ceb fprobe: Fix module reference count leak on error in register_fprobe()
In register_fprobe(), get_ips_from_filter() resolves target function
addresses and increments module reference counts via try_module_get() for
symbols in kernel modules. If get_ips_from_filter() fails on the second
pass and returns an error, register_fprobe() returned directly without
releasing module references acquired up to that point.

Fix this by ensuring the cleanup loop executing module_put() runs even when
get_ips_from_filter() returns a negative error.

Link: https://lore.kernel.org/all/178528125360.101985.4144133640239273153.stgit@devnote2/

Fixes: d24fa977ee ("tracing: fprobe: Fix to lock module while registering fprobe")
Assisted-by: Antigravity:gemini-3.6-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-29 22:50:02 +09:00
Masami Hiramatsu (Google) c00e735410 tracing/probes: Treating longer symbol name on event comparation
MAX_COMMON_HEAD_LEN (63) was used to allocate a temporary buffer for
formatting command heads in trace_kprobe_match_command_head() and
trace_uprobe_match_command_head(). However, the buffer size is too
short for some longer symbols. Especially, with rust code, the symbol
can be mangled and become very long.

Refactor trace_kprobe_match_command_head() to perform direct string
comparisons using strcmp() and strncmp(), eliminating the need for a
temporary buffer and removing the MAX_COMMON_HEAD_LEN string length
restriction on probe symbol names.

For trace_uprobe_match_command_head(), since tu->filename is already
matched via strncmp(), use a fixed 64-byte stack buffer solely for
formatting offset and ref_ctr_offset (which requires at most 39 bytes).

With all users converted, remove the MAX_COMMON_HEAD_LEN definition from
trace_probe.h.

Link: https://lore.kernel.org/all/178521361102.34226.9650586522488974115.stgit@devnote2/

Reported-by: Zhan Xusheng <[email protected]>
Link: https://lore.kernel.org/all/[email protected]/
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-28 23:55:35 +09:00
Masami Hiramatsu (Google) 1a087033a6 selftests/ftrace: Reset triggers at top level before instance loop
When running instance tests, 'ftracetest' creates a new ftrace instance
and runs the tests inside it. Before starting each test, it executes
'initialize_system()' to reset the ftrace state to initial-state.

However, since 'initialize_system()' is executed in the context of the
instance directory, it only cleans up triggers and filters of that
instance.
Any triggers or dynamic events left behind in the top-level instance by
previous failed top-level tests, are left completely untouched. These
top-level leftovers can cause subsequent instance-based tests to fail
or even crash the kernel.

Fix this by executing 'initialize_system()' in the top-level tracing
directory once before entering the instance loop.

Cc: [email protected]
Link: https://patch.msgid.link/178425671889.84440.9477850701738666404.stgit@devnote2
Fixes: b5b77be812 ("selftests: ftrace: Allow some tests to be run in a tracing instance")
Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-07-24 13:43:18 -04:00
Masami Hiramatsu (Google) b4eb07bde6 tracing: Fix union collision of module and refcnt for dynamic events
In 'struct trace_event_call', the 'module' pointer and the 'refcnt'
atomic variable share the same memory space in a union. For dynamic
events, the union member is 'refcnt', which acts as an active
reference counter.

When a dynamic event (such as kprobe, uprobe, fprobe, eprobe, or
wprobe) has a non-zero reference count (e.g. due to active event
triggers or perf attachments), its 'call->module' evaluates to a
small non-zero integer instead of NULL.

When filtering or setting events for a specific module (e.g., writing
':mod:<module>' to 'set_event'), the code in
'__ftrace_set_clr_event_nolock()' and 'update_event_fields()' reads
'call->module' directly without checking whether the event is dynamic.
This causes the kernel to treat the small integer (refcnt) as a
'struct module' pointer, leading to a NULL/invalid pointer dereference
(Oops) when dereferencing the module name.

Fix this by ensuring that the 'TRACE_EVENT_FL_DYNAMIC' flag is checked
before treating 'call->module' as a valid pointer in these code paths.

Cc: [email protected]
Link: https://patch.msgid.link/178425670947.84440.11344393611899824907.stgit@devnote2
Fixes: 4c86bc531e ("tracing: Add :mod: command to enabled module events")
Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-07-24 13:43:17 -04:00
Masami Hiramatsu (Google) 5be3a9db60 tracing/probes: Fix extra whitespace in trace_probe_kernel.h
Clean up extra space after '=' in fetch_store_strlen_user().

Link: https://lore.kernel.org/all/178454430235.296567.9486503882045148585.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 18:00:13 +09:00
Masami Hiramatsu (Google) 5b385fd434 tracing/kprobe: Remove redundant memset in kprobe_perf_func()
kprobe_perf_func() calls memset(&entry[1], 0, dsize) prior to calling
store_trace_args(). store_trace_args() populates the entry buffer and
handles dynamic data fields.

Remove this redundant memset call to align with kretprobe_perf_func() and
other probe perf functions.

Link: https://lore.kernel.org/all/178454429309.296567.17379087988750549247.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 18:00:09 +09:00
Masami Hiramatsu (Google) 3d785646cc tracing/fprobe: Remove redundant memset in fentry_perf_func()
fentry_perf_func() calls memset(&entry[1], 0, dsize) prior to calling
store_trace_args(). store_trace_args() populates the entry buffer and
handles dynamic data fields.

Furthermore, passing dsize (the dynamic data byte length) to memset at
&entry[1] (the start of fixed trace arguments) is inaccurate as it zeroes
from the fixed args area rather than the dynamic data region.

Remove this redundant memset call to align with fexit_perf_func() and other
probe perf functions.

Link: https://lore.kernel.org/all/178454428366.296567.16465331441301815980.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 18:00:05 +09:00
Masami Hiramatsu (Google) 36db65d0e5 tracing/fprobe: Remove redundant snprintf in trace_fprobe_match_command_head()
trace_fprobe_match_command_head() copies trace_fprobe_symbol(tf) into a
local buffer 'buf' of size MAX_COMMON_HEAD_LEN + 1 using snprintf before
comparing with argv[0].

Since trace_fprobe_symbol(tf) already returns a null-terminated string,
comparing it directly with argv[0] via strcmp() avoids stack buffer usage
and potential symbol truncation at MAX_COMMON_HEAD_LEN.

Link: https://lore.kernel.org/all/178454427449.296567.12336315661120939938.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 18:00:01 +09:00
Masami Hiramatsu (Google) 0fb6fd1eb3 tracing/probes: Simplify BTF_KIND_PTR case in fetch_type_from_btf_type()
Use a ternary operator for checking IS_ENABLED(CONFIG_64BIT) in the
BTF_KIND_PTR case of fetch_type_from_btf_type() to simplify the code.

Link: https://lore.kernel.org/all/178454426554.296567.17700307233923830044.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 17:59:58 +09:00
Masami Hiramatsu (Google) 78d252c935 tracing/probes: Cleanup pointer arithmetic in store_trace_entry_data()
In store_trace_entry_data(), edata is cast to unsigned long for pointer
offset arithmetic before being cast back to unsigned long *. Cast edata
to u8 * instead.

Link: https://lore.kernel.org/all/178454425622.296567.16952341966130280432.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 17:59:54 +09:00
Masami Hiramatsu (Google) 5428fca0cd tracing/probes: Remove unused parameter from parse_probe_var_retval()
The parameter 'arg' in parse_probe_var_retval() is unused. Remove it
and update its caller accordingly.

Link: https://lore.kernel.org/all/178454424711.296567.15352344258939682112.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 17:59:50 +09:00
Masami Hiramatsu (Google) 6e9328ed75 tracing/probes: Remove redundant bounds check in trace_probe_compare_arg_type()
In trace_probe_compare_arg_type(), prior to entering the comparison loop,
a->nr_args and b->nr_args are checked for equality. Since the loop
condition is i < a->nr_args, i is guaranteed to be less than b->nr_args
inside the loop.

Remove the redundant (b->nr_args <= i) check.

Link: https://lore.kernel.org/all/178454423769.296567.6694636865644203423.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 17:59:46 +09:00
Masami Hiramatsu (Google) 794b5640aa tracing/probes: Remove redundant boolean conversion in trace_probe_has_single_file()
list_is_singular() returns a boolean value, so the double negation (!!)
in trace_probe_has_single_file() is redundant. Remove it.

Link: https://lore.kernel.org/all/178454422826.296567.4382363406595169533.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 17:59:42 +09:00
Masami Hiramatsu (Google) 323853e2d1 tracing/probes: Remove duplicate MAX_ARRAY_LEN macro definition
MAX_ARRAY_LEN is defined twice in trace_probe.h. Remove the redundant
definition.

Link: https://lore.kernel.org/all/178454421926.296567.6649983666070787570.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 17:59:39 +09:00
Masami Hiramatsu (Google) f418d68d71 tracing/eprobe: Fix exact system name matching in eprobe_dyn_event_match()
eprobe_dyn_event_match() checks if the target event system in argv[0]
matches ep->event_system using strncmp(ep->event_system, argv[0], len).
However, if ep->event_system is longer than len (e.g. "eprobes" vs
"ep/event"), strncmp() still returns 0 because the first len characters
match.

Check that ep->event_system[len] is '\0' to ensure exact system name
matching.

Link: https://lore.kernel.org/all/178454235856.290363.14872590900774231133.stgit@devnote2/

Fixes: 7d5fda1c84 ("tracing: Fix event probe removal from dynamic events")
Cc: [email protected]
Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 10:23:21 +09:00
Masami Hiramatsu (Google) 8ce20bfba4 tracing/probes: Fix potential underflow in LEN_OR_ZERO macro
In __set_print_fmt(), LEN_OR_ZERO is defined as (len ? len - pos : 0).
If len is non-zero but smaller than pos, len - pos evaluates to a negative
integer. When passed as a size argument to snprintf(), this negative value
is cast to a large unsigned size_t, bypassing buffer size limits.

Ensure len > pos before subtracting to avoid integer underflow.

Link: https://lore.kernel.org/all/178454234934.290363.15247317871499514139.stgit@devnote2/

Fixes: 5bf652aaf4 ("tracing/probes: Integrate duplicate set_print_fmt()")
Cc: [email protected]
Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 10:23:17 +09:00
Masami Hiramatsu (Google) a9d6fb2840 tracing/probes: Prevent out-of-bounds write in __trace_probe_log_err()
If trace_probe_log.argc is 0 in __trace_probe_log_err(), the loop
constructing the command string will not execute and p will remain equal to
command. Writing to *(p - 1) will cause an out-of-bounds access before
command. This should not happen, but better to be treated.

Reject if trace_probe_log.argc is 0.

Link: https://lore.kernel.org/all/178454233992.290363.18323091580600697731.stgit@devnote2/

Fixes: ab105a4fb8 ("tracing: Use tracing error_log with probe events")
Cc: [email protected]
Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 10:23:13 +09:00
Masami Hiramatsu (Google) 15f197856d tracing/probes: Avoid temporary buffer truncation in trace_probe_match_command_args()
In trace_probe_match_command_args(), a stack buffer buf[MAX_ARGSTR_LEN + 1]
(256 bytes) is used to format "<name>=<comm>". However, since name can
be up to 32 bytes (MAX_ARG_NAME_LEN) and comm up to 255 bytes
(MAX_ARGSTR_LEN), the formatted string can exceed 256 bytes and get
truncated by snprintf(), causing spurious argument matching failures.

Instead of formatting into a temporary buffer on stack, compare the
argument name, the '=' delimiter, and the comm expression directly.

Link: https://lore.kernel.org/all/178454233010.290363.10428767141343428804.stgit@devnote2/

Fixes: eb5bf81330 ("tracing/kprobe: Add per-probe delete from event")
Cc: [email protected]
Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-21 10:23:10 +09:00
Masami Hiramatsu (Google) 1a416ae446 selftests/ftrace: Add test case for a symbol in a module without module name
Add a test case for probing on a symbol in a module without module name.
When probing on a symbol in a module, ftrace accepts both the syntax that
<MODNAME>:<SYMBOL> and <SYMBOL>. Current test case only checks the former
syntax. This adds a test for the latter one.

Link: https://lore.kernel.org/all/169846405196.88147.17766692778800222203.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-15 11:06:18 +09:00
Masami Hiramatsu 1a0ffe10bf tracing/probes: Eliminate recursion in parse_probe_arg()
To avoid potential stack overflows on limited kernel stacks, convert
parse_probe_arg() from a recursive function into a loop-based
implementation with a simple local state stack.

Since recursion is eliminated using a loop with a fixed-size
stack in the context, this restricts the dereference nesting
depth. The maximum nesting depth of dereferences is now restricted
to the same limit as typecasts (TRACEPROBE_MAX_NESTED_LEVEL, which
is 8) and reports the same TOO_MANY_NESTED error. Update ftrace
selftests to reflect this restriction and simplify the checks.

Note that this change slightly alters the behavior of nested
dereferencing in fetcharg. Previously, dereferencing without BTF
allowed for up to 14 levels of nesting, whereas dereferencing
with BTF was limited to 3 levels. With this change, the nesting
depth is now limited to 8 levels in both cases.

Link: https://lore.kernel.org/all/178399141396.27810.5390060618628718661.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:40 +09:00
Masami Hiramatsu 47e4ec6871 tracing/probes: Extend max length of argument string
To support BTF argument parsing (such as accessing fields within nested
structures via typecasting), the maximum argument string length needs
to be extended. Extend MAX_ARGSTR_LEN from 63 to 255.

Since MAX_ARGSTR_LEN was previously reused to format command heads in
trace_*probe_match_command_head() functions, introduce a dedicated
MAX_COMMON_HEAD_LEN (63) macro for matching command heads and switch
these functions to use the new macro.

Link: https://lore.kernel.org/all/178399140457.27810.11387684872148824707.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:40 +09:00
Masami Hiramatsu 0b420da72e tracing/probes: Sort ERRORS list in trace_probe.h alphabetically
Sort the C-macro ERRORS list alphabetically in trace_probe.h to make
it easier to find and maintain error entries.

Link: https://lore.kernel.org/all/178399139516.27810.14930549550788208142.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:40 +09:00
Masami Hiramatsu 7e79d7fbaf tracing/probes: Refactor parse_probe_arg()
Decompose parse_probe_arg() by extracting register, memory/symbol,
dereference, immediate, and default BTF/CPU parsing handlers into
dedicated static helper functions (parse_probe_arg_register,
parse_probe_arg_mem_symbol, parse_probe_arg_deref, parse_probe_arg_imm,
and parse_probe_arg_default). This modularizes the recursive argument
parser and improves readability.

Link: https://lore.kernel.org/all/178399138581.27810.9471730417467607229.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:40 +09:00
Masami Hiramatsu 2590d67a1c tracing/probes: Refactor parse_probe_vars()
Decompose parse_probe_vars() by extracting retval, stack, current task
struct, and function argument parsing logic into dedicated static
helper functions (parse_probe_var_retval, parse_probe_var_stack,
parse_probe_var_current, and parse_probe_var_arg). This simplifies
parse_probe_vars() and improves its readability.

Link: https://lore.kernel.org/all/178399137612.27810.14869178899276413372.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:39 +09:00
Masami Hiramatsu (Google) 7d8d6ad659 tracing/probes: Add a new testcase for BTF typecasts
With the introduction of container_of-style BTF typecasting and
per-CPU variable access support in trace probes, we need a way to
verify their functionality and prevent regressions.

Add a new ftrace kselftest and update the trace event sample module
to test and validate these features.

Specifically, update the trace-events-sample module to set up a
periodic timer whose callback accesses a per-CPU counter. Introduce
a new sample trace event, foo_timer_fn, to trace this callback
and log the current counter value.

Then, add a new test case, btf_probe_event.tc, which defines a
dynamic probe on the timer callback. The probe uses BTF typecasting
to recover the parent structure from the timer argument and
this_cpu_read() to fetch the per-CPU counter. The test verifies
the integrity of the implementation by ensuring the values
recorded by the dynamic probe match those from the static tracepoint.

Link: https://lore.kernel.org/all/178271368625.1176915.13502654445483530822.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:16 +09:00
Masami Hiramatsu (Google) 49b0a3f605 tracing/probes: Add this_cpu_read() and this_cpu_ptr() dereference method to fetcharg
When tracing the kernel local variables, sometimes we need to get the
CPU local variables. To access it, current simple dereference is not
enough.

Thus, introduce a special this_cpu_read() dereference to access per-cpu
variable for the current CPU (accessing other CPU variable may race with
updates on other CPUs). Also this_cpu_ptr() is for accessing per-cpu
pointer.

Those are working as same as the kernel percpu macro.

Link: https://lore.kernel.org/all/178271367680.1176915.4711734074448973989.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:16 +09:00
Masami Hiramatsu (Google) 738b78ee4b tracing/probes: Add $current variable support
Since we can use the BTF to cast value to a structure pointer type,
it is useful to introduce "$current" special variable support to
fetcharg.

User can define a fetcharg to access current task_struct properties
using BTF info. e.g.

  $current->cpus_ptr

Link: https://lore.kernel.org/all/178271366709.1176915.15320906169981578568.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:16 +09:00
Masami Hiramatsu (Google) f218345240 tracing/probes: Support field specifier option for typecast
Add a field specifier option for the typecast. This works like
container_of() macro.

    (STRUCT[,FIELD[.FIELD2...]])VAR

This is equivalent to :

    container_of(VAR, struct STRUCT, FIELD[.FIELD2...])

For example:

 echo "f tick_nohz_handler next_tick=(tick_sched,sched_timer)timer->next_tick" >> dynamic_events

This will trace tick_nohz_handler() with its tick_sched::next_tick which
is converted from @timer by contianer_of(tick, struct tick_sched, sched_timer).
So, if you enabkle both fprobes:tick_nohz_handler__entry and
timer:hrtimer_expire_entry events, we will see something like:


          <idle>-0       [002] d.h1.  3778.087272: hrtimer_expire_entry: hrtimer=00000000d63db328 f
unction=tick_nohz_handler now=3777450051040
          <idle>-0       [002] d.h1.  3778.087281: tick_nohz_handler__entry: (tick_nohz_handler+0x4
/0x140) next_tick=3777450000000


Link: https://lore.kernel.org/all/178271365745.1176915.725923927180862257.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:16 +09:00
Masami Hiramatsu (Google) 52c76ec18e tracing/probes: Type casting always involves nested calls
This allows type casting to various fetchargs without parentheses
by recursively calling parse_probe_arg on the target when type
casting is used.

For example, this allows the following expressions:
 - (STRUCT)%REG->FIELD
 - (STRUCT)$stackN->FIELD
 - (STRUCT)@SYM->FIELD

Note that @SYM+/-OFFSET with typecast needs parentheses like:
  - (STRUCT)(@SYM-8)->FIELD

Link: https://lore.kernel.org/all/178271364804.1176915.17600229399446264813.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:16 +09:00
Masami Hiramatsu (Google) 60432df556 tracing/probes: Support nested typecast
When we hit an open parenthesis right after typecast closing
parenthesis, it means we have nested typecast. This allows us to
typecast a generic data member in a structure to a pointer to
another structure.

For example, to cast a DATA_MEMBER of VAR structure to STRUCT pointer
and get MEMBER value.

  (STRUCT)(VAR->DATA_MEMBER)->MEMBER

Also, we can nest typecast.

  (STRUCT1)((STRUCT2)$ARG->FIELD2)->FIELD1

Currently the max nest level is limited to 3.

This also allows user to use typecasting for registers or stacks on
kprobe events. e.g.

  (STRUCT)(%ax)->MEMBER

  (STRUCT)($stack0)->MEMBER


Link: https://lore.kernel.org/all/178271363855.1176915.16793301788257446529.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:16 +09:00
Masami Hiramatsu (Google) 438a8d6a82 tracing/probes: Support typecast for various probe events
Support BTF typecast feature on other probe events, but only if it is
kernel function entry or return, and must use function parameter name
or $retval. This means you can do:

  (STRUCT)PARAM->MEMBER

Note: you can not use other variables like $stackN, %reg etc. That
needs nesting support.

To support other probe events, we just need to use last_struct type
when we find a function parameter in parse_btf_arg().

This also updates <tracefs>/README file to show struct typecast.

Link: https://lore.kernel.org/all/178271362928.1176915.12235759508786922490.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:16 +09:00
Masami Hiramatsu (Google) 777bcbd2ac tools/bootconfig: Ignore comment lines in dynamic_events/kprobe_events file
Since dynamic_events/kprobe_events files show the fetcharg debug
information as comment lines, its reader needs to ignore it.

Link: https://lore.kernel.org/all/178271360563.1176915.423090353815990910.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-14 22:43:16 +09:00
Masami Hiramatsu (Google) dccddc39aa tracing/probes: Support dumping fetcharg program for debugging dynamic events
For debugging probe events, it is helpful to verify the compiled
fetch instructions for each probe argument. This introduces a new
kernel config CONFIG_PROBE_EVENTS_DUMP_FETCHARG to decode the
instruction sequence of each argument and display it under a
commented line starting with '#' immediately following the dynamic
event definition (such as in dynamic_events, kprobe_events,
uprobe_events, etc.).

For example:
 /sys/kernel/tracing # cat dynamic_events
 p:kprobes/p_vfs_read_0 vfs_read arg1=+0(file):ustring arg2=%ax:x16
 #  arg1: ARG(0) -> ST_USTRING(offset=0,size=4) -> END
 #  arg2: REG(80) -> ST_RAW(size=2) -> END

Link: https://lore.kernel.org/all/178271359508.1176915.11895926894608440183.stgit@devnote2/

Assisted-by: Antigravity:gemini-3.5-flash
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-02 21:12:40 +09:00
Masami Hiramatsu (Google) 427c240a02 tracing/probes: Allow eprobe to use variable without $ prefix
The commit 69efd863a7 ("tracing/eprobes: Allow use of BTF names
to dereference pointers") allows eprobe to use event field without
"$" prefix when it is used with typecast, it is natual to allow it
without typecast.

Link: https://lore.kernel.org/all/178271358117.1176915.13520279547897961254.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-02 21:12:40 +09:00
Masami Hiramatsu (Google) 7e07baaa9e tracing/probes: Rename FETCH_OP_DATA to FETCH_OP_IMMSTR
Since FETCH_OP_DATA is used solely to store immediate string
values, rename it to the more specific FETCH_OP_IMMSTR.

No behavior change, just rename it.

Link: https://lore.kernel.org/all/178217906914.643090.2958799486090467704.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-07-02 21:12:39 +09:00
Masami Hiramatsu (Google) 4f7442f7e7 perf/probe: Ignore comment lines in dynamic_events/kprobe_events file
Since dynamic_events/kprobe_events files show the fetcharg debug
information as comment lines, its reader needs to ignore it.

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Namhyung Kim <[email protected]>
2026-06-30 16:37:49 -07:00
Masami Hiramatsu (Google) a369299c3f tracing/probes: Make the $ prefix mandatory for comm access
Since $comm or $COMM are not event field but special fetcharg
variables to access current->comm, It should not be accessed
without '$' prefix even with typecast.

Link: https://lore.kernel.org/all/178231209724.732967.12049805699091810641.stgit@devnote2/

Fixes: 69efd863a7 ("tracing/eprobes: Allow use of BTF names to dereference pointers")
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-06-30 23:58:20 +09:00
Masami Hiramatsu (Google) 9a667b7750 tracing/probes: Fix double addition of offset for @+FOFFSET
Since commit 533059281e ("tracing: probeevent: Introduce new argument
 fetching code") wrongly use @offset local variable during the parsing,
the offset value is added twice when dereferencing.
Reset the @offset after setting it in FETCH_OP_FOFFS.

Link: https://lore.kernel.org/all/178217905962.643090.1978577464942171332.stgit@devnote2/

Fixes: 533059281e ("tracing: probeevent: Introduce new argument fetching code")
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Cc: [email protected]
2026-06-30 23:58:19 +09:00
Masami Hiramatsu (Google) cda1fbfc53 tracing/events: Fix to check the simple_tsk_fn creation
Sashiko pointed that this sample code does not correctly handle the
failure of thread creation because kthread_run() can return -errno.

Check the simple_tsk_fn is correctly initialized (created) or not.

Link: https://lore.kernel.org/all/178165817322.269421.3992299509400184196.stgit@devnote2/

Link: https://sashiko.dev/#/patchset/178092865666.163648.10457567771536160909.stgit%40devnote2

Fixes: 9cfe06f8cd ("tracing/events: add trace-events-sample")
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-06-30 23:58:19 +09:00
Masami Hiramatsu (Google) 251a8fe1b9 tracing/probes: Remove WARN_ON_ONCE from parse_btf_arg
Sashiko found that user can cause this WARN_ON_ONCE() easily
with adding a kprobe event based on a raw address with BTF
parameter.

Since this is not an unexpected condition, remove the
WARN_ON_ONCE().

Link: https://lore.kernel.org/all/178177265367.2059927.13789953014706792126.stgit@mhiramat.tok.corp.google.com/

Link: https://sashiko.dev/#/patchset/178165816303.269421.7302603996990753309.stgit%40devnote2

Reported-by: Sashiko <[email protected]>
Fixes: b576e09701 ("tracing/probes: Support function parameters if BTF is available")
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-06-30 23:58:19 +09:00
Masami Hiramatsu (Google) 4304c81652 tracing/probes: Ensure the uprobe buffer size is bigger than event size
Add BUILD_BUG_ON() to ensure the uprobe per-CPU working buffer
size is bigger than the event size.

Link: https://lore.kernel.org/all/177849383209.8038.1902170479780501237.stgit@devnote2/

Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-06-01 23:35:21 +09:00
Masami Hiramatsu (Google) 85e0f27dd1 tracing/probes: Point the error offset correctly for eprobe argument error
Fix to point the error offset correctly for eprobe argument error.
In the cleanup commit 1b8b0cd754 ("tracing/probes: Move event parameter
fetching code to common parser"), due to incorrect backward compatibility
aimed at conforming to the test specifications, the error location was set
to 0 when a non-existent formal parameter was specified for Eprobe.
However, this should be corrected in both the test and the implementation
to point correct error position.

Link: https://lore.kernel.org/all/177967567399.209006.1451571244515632097.stgit@devnote2/

Fixes: 1b8b0cd754 ("tracing/probes: Move event parameter fetching code to common parser")
Cc: [email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Reviewed-by: Steven Rostedt <[email protected]>
2026-05-30 22:45:50 +09:00
Masami Hiramatsu (Google) 7cf02d0aa6 ring-buffer: Cleanup buffer_data_page related code
Code cleanup related to buffer_data_page for readability,
which includes:
- Introduce rb_data_page_commit() and rb_data_page_size()
- Use 'dpage' for buffer_data_page, instead of 'bpage' because
  'bpage' is used for buffer_page.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-05-28 22:40:52 -04:00
Masami Hiramatsu (Google) ea250b7ef9 ring-buffer: Cleanup persistent ring buffer validation
Cleanup rb_meta_validate_events() function to make it easier to read.
This includes the following cleanups:
 - Introduce rb_validatation_state to hold working variables in
   validation.
 - Move repleated validation state updates into rb_validate_buffer().
 - Move reader_page injection code outside of rb_meta_validate_events().

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-05-28 22:40:52 -04:00
Masami Hiramatsu (Google) e500acc34b ring-buffer: Show commit numbers in buffer_meta file
In addition to the index number, show the commit numbers of
each data page in the per_cpu buffer_meta file.
This is useful for understanding the current status of the
persistent ring buffer. (Note that this file is shown
only for persistent ring buffer and its backup instance)

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-05-28 22:40:52 -04:00
Masami Hiramatsu (Google) 68413a36f0 ring-buffer: Add persistent ring buffer invalid-page inject test
Add a self-corrupting test for the persistent ring buffer.

This will inject an erroneous value to some sub-buffer pages (where
the index is even or multiples of 5) in the persistent ring buffer
when the kernel panics, and checks whether the number of detected
invalid pages and the total entry_bytes are the same as the recorded
values after reboot.

This ensures that the kernel can correctly recover a partially
corrupted persistent ring buffer after a reboot or panic.

The test only runs on the persistent ring buffer whose name is
"ptracingtest". The user has to fill it with events before a
kernel panic.

To run the test, enable CONFIG_RING_BUFFER_PERSISTENT_INJECT
and add the following kernel cmdline:

 reserve_mem=20M:2M:trace trace_instance=ptracingtest^traceoff@trace
 panic=1

Run the following commands after the 1st boot:

 cd /sys/kernel/tracing/instances/ptracingtest
 echo 1 > tracing_on
 echo 1 > events/enable
 sleep 3
 echo c > /proc/sysrq-trigger

After panic message, the kernel will reboot and run the verification
on the persistent ring buffer, e.g.

 Ring buffer meta [2] invalid buffer page detected
 Ring buffer meta [2] is from previous boot! (318 pages discarded)
 Ring buffer testing [2] invalid pages: PASSED (318/318)
 Ring buffer testing [2] entry_bytes: PASSED (1300476/1300476)

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-05-28 22:40:51 -04:00
Masami Hiramatsu (Google) c8a7d4b472 ring-buffer: Skip invalid sub-buffers when rewinding persistent ring buffer
Skip invalid sub-buffers when rewinding the persistent ring buffer
instead of stopping the rewinding the ring buffer. The skipped
buffers are cleared.

To ensure the rewinding stops at the unused page, this also clears
buffer_data_page::time_stamp when tracing resets the buffer. This
allows us to identify unused pages and empty pages.

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
[ SDR: Have reader_page still get evaluated if header_page fails ]
Signed-off-by: Steven Rostedt <[email protected]>
2026-05-28 22:40:51 -04:00
Masami Hiramatsu (Google) eb3bd277b3 ring-buffer: Skip invalid sub-buffers when validating persistent ring buffer
Skip invalid sub-buffers when validating the persistent ring buffer
instead of discarding the entire ring buffer. Only skipped buffers
are invalidated (cleared).

If the cache data in memory fails to be synchronized during a reboot,
the persistent ring buffer may become partially corrupted, but other
sub-buffers may still contain readable event data. Only discard the
subbuffers that are found to be corrupted.

Link: https://lore.kernel.org/all/[email protected]/

Link: https://patch.msgid.link/[email protected]
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
[SDR: Fixed max_loops in rb_iter_peek() as well ]
Signed-off-by: Steven Rostedt <[email protected]>
2026-05-28 22:40:51 -04:00
Masami Hiramatsu (Google) 8f0f5c4fb9 tracing: Do not call map->ops->elt_free() if elt_alloc() fails
In paths where tracing_map_elt_alloc() failed to allocate objects,
the map->ops->elt_alloc() call was never successful. In this case,
map->ops->elt_free() should not be called.

Link: https://sashiko.dev/#/patchset/20260520223101.34710-1-rosenp%40gmail.com

Cc: [email protected]
Cc: Tom Zanussi <[email protected]>
Cc: Mathieu Desnoyers <[email protected]>
Cc: Rosen Penev <[email protected]>
Reported-by: Sashiko <[email protected]>
Fixes: 2734b62952 ("tracing: Add per-element variable support to tracing_map")
Link: https://patch.msgid.link/177933895460.108746.5396070821443932634.stgit@devnote2
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-05-21 11:29:03 -04:00
Masami Hiramatsu (Google) a494d3c8d5 ring-buffer: Flush and stop persistent ring buffer on panic
On real hardware, panic and machine reboot may not flush hardware cache
to memory. This means the persistent ring buffer, which relies on a
coherent state of memory, may not have its events written to the buffer
and they may be lost. Moreover, there may be inconsistency with the
counters which are used for validation of the integrity of the
persistent ring buffer which may cause all data to be discarded.

To avoid this issue, stop recording of the ring buffer on panic and
flush the cache of the ring buffer's memory.

Fixes: e645535a95 ("tracing: Add option to use memmapped memory for trace boot instance")
Cc: [email protected]
Cc: Will Deacon <[email protected]>
Cc: Mathieu Desnoyers <[email protected]>
Cc: Ian Rogers <[email protected]>
Link: https://patch.msgid.link/177751969602.2136606.12031934362587643488.stgit@mhiramat.tok.corp.google.com
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
Acked-by: Catalin Marinas <[email protected]>
Acked-by: Geert Uytterhoeven <[email protected]>
Signed-off-by: Steven Rostedt <[email protected]>
2026-05-21 08:20:58 -04:00
Masami Hiramatsu (Google) 657b594b20 fprobe: Fix unregister_fprobe() to wait for RCU grace period
Commit 4346ba1604 ("fprobe: Rewrite fprobe on function-graph tracer")
changed fprobe to register struct fprobe to an rcu-hlist, but it forgot
to wait for RCU GP. Thus there can be use-after-free if the fprobe is
released right after unregistering. This can be happened on fprobe
event and sample module code.

To fix this issue, add synchronize_rcu() in unregister_fprobe().

Note that BPF is OK because fprobe is used as a part of
bpf_kprobe_multi_link. This unregisters its fprobe in
bpf_kprobe_multi_link_release() and it is deallocated via
bpf_kprobe_multi_link_dealloc(), which is invoked from
bpf_link_defer_dealloc_rcu_gp() RCU callback.

For BPF, this also introduced unregister_fprobe_async() which does
NOT wait for RCU grace priod.

Link: https://lore.kernel.org/all/177813998919.256460.2809243930741138224.stgit@mhiramat.tok.corp.google.com/

Fixes: 4346ba1604 ("fprobe: Rewrite fprobe on function-graph tracer")
Signed-off-by: Masami Hiramatsu (Google) <[email protected]>
2026-05-11 19:04:46 +09:00