tracing: wprobe: x86: Add wprobe for watchpoint
Subsystems (7)
Masami Hiramatsu (Google)
maintainerv17 cover tracing: wprobe: x86: Add wprobe for watchpoint
Hi,
Here is the 17th version of the series for adding new wprobe (watch probe) which provides memory access tracing event. Moreover, this can be used via event trigger. Thus it can trace memory access on dynamically allocated objects too.
The previous version is here:
https://lore.kernel.org/all/178939017565.94750.9431053336761330458.stgit@devnote2/
In this version, we address review feedback on KVM x86 debug register isolation and wprobe triggers:
- Replaced the ad-hoc cpu_dr_in_guest flag with a generic perf_guest_in_guest() helper by adding an .in_guest callback to perf_guest_info_callbacks. KVM implements this using its existing vcpu->mode (IN_GUEST_MODE / EXITING_GUEST_MODE), requiring zero additional per-entry/exit state writes.
(Sean, is this what you meant? I think we can also update the perf_guest_state() to check a new state flag, but that may need to update other callers.)
- Added dynamic CPU hotplug callbacks to handle CPU offline and online events so breakpoints are cleanly unregistered and reinstalled on hotplugged CPUs, serialized with cpus_read_lock(). Added a selftest (trigger-wprobe-hotplug.tc) to verify this behavior.
- Handled environmental watchpoint exhaustion in add_remove_wprobe.tc using exit_unresolved.
- Restored EVENT_FILE_FL_SOFT_DISABLED_BIT in wprobe_trigger_free() to prevent wprobe tracepoint leaks upon trigger unregistration.
- Checked trace_find_event_field() before skipping fields named "unlimited" in clear_wprobe trigger parsing.
- Added tracepoint_synchronize_unregister() before freeing trigger data.
- Implemented __wprobe_count_func() and wprobe_count_func() wrapper to consolidate precondition checks, update tw->missed on failure, and update the local hardware breakpoint before updating tw->addr.
Detailed changes are here.
Changes in v17:
[02/13]
- Drop changes to local_db_save() and local_db_restore().
- Drop cpu_dr_in_guest per-CPU flag.
- Introduce .in_guest callback in perf_guest_info_callbacks and perf_guest_in_guest() helper to query vcpu->mode.
- In arch_install_hw_breakpoint(), check perf_guest_in_guest().
[03/13]
- Drop cpu_dr_in_guest checks in local_db_save(), local_db_restore(), and within_cpu_entry().
[04/13]
- In arch_modify_local_hw_breakpoint_addr(), check perf_guest_in_guest() instead of cpu_dr_in_guest.
[08/13]
- Catch failures when enabling wprobe and call exit_unresolved in case hardware watchpoints are exhausted.
[10/13]
- Add dynamic CPU hotplug callbacks to handle CPU offline/online events and serialize wprobe_work_func() with cpus_read_lock().
- Restore EVENT_FILE_FL_SOFT_DISABLED_BIT in wprobe_trigger_free() to prevent wprobe event leaks when triggers are removed.
- Check whether trigger event has "unlimited" field before skipping "unlimited" in clear_wprobe trigger parsing.
- Call tracepoint_synchronize_unregister() before freeing trigger data via data->cmd_ops->free() on registration failure.
- Implement __wprobe_count_func() helper to consolidate precondition checks, optimize shared work_pending logic, and update tw->missed when trigger preconditions fail in wprobe_count_func().
- In wprobe_trigger(), only check __wprobe_count_func() if trigger is uncounted, and update local breakpoint before committing tw->addr.
[11/13]
- Add trigger-wprobe-hotplug.tc to verify wprobe triggers across CPU offline and online transitions.
Public branch
-------------
I will push this branch as topic/wprobe-v2 to my tree so that it can be easily tested.
https://git.kernel.org/pub/scm/linux/kernel/git/mhiramat/linux.git/log/?h=topic/wprobe-v2
This is based on linux-trace tree's linux-trace/probes/fixes.
Usage
-----
The basic usage of this wprobe is similar to other probes;
w:[GRP/][EVENT] [r|w|rw]@<ADDRESS|SYMBOL[+|-OFFS]>[:LEN] [FETCHARGS]
This defines a new wprobe event. For example, to trace jiffies update, you can do;
echo 'w:my_jiffies w@jiffies:8 value=+0($addr)' >> dynamic_events echo 1 > events/wprobes/my_jiffies/enable
Moreover, this can be combined with event trigger to trace the memory access on slab objects. The trigger syntax is;
set_wprobe:WPROBE_EVENT:FIELD[+|-OFFSET][:COUNT] [if FILTER] clear_wprobe:WPROBE_EVENT[:FIELD[+|-OFFSET][:COUNT]] [if FILTER]
set_wprobe sets WPROBE_EVENT's watch address on FIELD[+|-OFFSET]. clear_wprobe clears WPROBE_EVENT's watch address if it is set to FIELD[+|-OFFSET]. If FIELD is omitted, forcibly clear the watch address when trigger event is hit.
For example, trace the first 8 byte of the dentry data structure passed to do_truncate() until it is deleted by dentry_kill().
(Note: all tracefs setup uses '>>' so that it does not kick do_truncate())
# echo 'w:watch rw@-1:8 address=$addr value=+0($addr)' > dynamic_events
# echo 'f:truncate do_truncate dentry=$arg2' >> dynamic_events # echo 'set_wprobe:watch:dentry' >> events/fprobes/truncate/trigger
# echo 'f:dentry_kill dentry_kill dentry=$arg1' >> dynamic_events # echo 'clear_wprobe:watch:dentry' >> events/fprobes/dentry_kill/trigger
# echo 1 >> events/fprobes/truncate/enable # echo 1 >> events/fprobes/dentry_kill/enable
# echo aaa > /tmp/hoge # echo bbb > /tmp/hoge # echo ccc > /tmp/hoge # rm /tmp/hoge
Then, the trace data will show;
# tracer: nop
#
# entries-in-buffer/entries-written: 32/32 #P:8
#
# _-----=> irqs-off/BH-disabled
# / _----=> need-resched
# | / _---=> hardirq/softirq
# || / _--=> preempt-depth
# ||| / _-=> migrate-disable
# |||| / delay
# TASK-PID CPU# ||||| TIMESTAMP FUNCTION
# | | | ||||| | |
sh-107 [004] ...1. 9.990418: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004ad6618
sh-107 [004] ...1. 9.990914: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004b3de78
sh-107 [004] ...1. 9.993175: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049ddd40
sh-107 [004] ..... 9.995198: truncate: (do_truncate+0x4/0x120) dentry=0xffff8880048083a8
sh-107 [004] ...1. 9.995389: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049db998
sh-107 [004] ..Zff 9.997503: watch: (lookup_fast+0xaa/0x150) address=0xffff8880048083a8 value=0x8200080
sh-107 [004] ..Zff 9.997509: watch: (path_openat+0x211/0xda0) address=0xffff8880048083a8 value=0x8200080
sh-107 [004] ..Zff 9.997514: watch: (path_openat+0xa56/0xda0) address=0xffff8880048083a8 value=0x8200080
sh-107 [004] ..Zff 9.997518: watch: (path_openat+0xae2/0xda0) address=0xffff8880048083a8 value=0x8200080
sh-107 [004] ..... 9.997521: truncate: (do_truncate+0x4/0x120) dentry=0xffff8880048083a8
sh-107 [004] ...1. 9.997582: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004808270
sh-107 [004] ...1. 9.999365: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049db728
sh-107 [004] ...1. 9.999388: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004b1c000
rm-113 [005] ..Zff 10.000965: watch: (lookup_fast+0xaa/0x150) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] ..Zff 10.000971: watch: (path_lookupat+0x97/0x1e0) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] ..Zff 10.000984: watch: (lookup_fast+0xaa/0x150) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] ..Zff 10.000988: watch: (path_lookupat+0x97/0x1e0) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] ..Zff 10.001010: watch: (lookup_one_qstr_excl+0x28/0x140) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] ..Zff 10.001014: watch: (lookup_one_qstr_excl+0xd1/0x140) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] ..Zff 10.001018: watch: (may_delete_dentry+0x1c/0x200) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] ..Zff 10.001021: watch: (may_delete_dentry+0x195/0x200) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] ..Zff 10.001031: watch: (vfs_unlink+0x5e/0x260) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] d.Z.. 10.001067: watch: (d_make_discardable+0x1b/0x40) address=0xffff8880048083a8 value=0x8200080
rm-113 [005] d.Z.. 10.001071: watch: (d_make_discardable+0x29/0x40) address=0xffff8880048083a8 value=0x200080
rm-113 [005] ...1. 10.001072: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880048083a8
rm-113 [005] ...1. 10.001218: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880048083a8
sh-107 [004] ...1. 10.001416: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049db110
sh-107 [004] ...1. 10.001444: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049db248
sh-107 [004] ...1. 10.001500: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004ad6618
sh-107 [004] ...1. 10.002067: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004b41e78
sh-107 [004] ...1. 10.904920: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004b41e78
sh-107 [004] ...1. 10.905129: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004ad6618Thank you,
---
base-commit: 0c4256196b3a105307e2235fbfd85e768bbcdd0f
Jinchao Wang (2):
x86/hw_breakpoints: Make DR7 updates NMI safe x86/hw_breakpoints: Add arch_modify_local_hw_breakpoint_addr() API
Masami Hiramatsu (Google) (11):
x86/mce: Fix hardware debug register corruption on task migration perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
HWBP: Add modify_local_hw_breakpoint_addr() API tracing/wprobe: Add wprobe (watchpoint probe) trace event support
x86: hw_breakpoint: Add a kconfig to clarify when a breakpoint fires
selftests: tracing: Add a basic testcase for wprobe
selftests: tracing: Add syntax testcase for wprobe tracing/wprobe: Add set_wprobe and clear_wprobe event triggers
selftests: tracing: Add wprobe trigger testcases tracing/wprobe: Support BTF typecast in fetchargs tracing/wprobe: Support BTF struct offset resolution in set_wprobe trigger
Documentation/trace/index.rst | 1 Documentation/trace/wprobetrace.rst | 200 ++ arch/Kconfig | 18 arch/x86/Kconfig | 2 arch/x86/include/asm/debugreg.h | 68 + arch/x86/include/asm/hw_breakpoint.h | 2 arch/x86/kernel/cpu/mce/core.c | 29 arch/x86/kernel/hw_breakpoint.c | 158 +- arch/x86/kernel/nmi.c | 7 arch/x86/kernel/traps.c | 10 include/linux/hw_breakpoint.h | 6 include/linux/perf_event.h | 9 include/linux/trace_events.h | 3 kernel/events/core.c | 5 kernel/events/hw_breakpoint.c | 48 + kernel/trace/Kconfig | 24 kernel/trace/Makefile | 1 kernel/trace/trace.c | 9 kernel/trace/trace.h | 6 kernel/trace/trace_events_trigger.c | 2 kernel/trace/trace_probe.c | 36 kernel/trace/trace_probe.h | 22 kernel/trace/trace_wprobe.c | 1668 ++++++++++++++++++++ tools/testing/selftests/ftrace/config | 3 .../ftrace/test.d/dynevent/add_remove_wprobe.tc | 66 + .../test.d/dynevent/wprobes_syntax_errors.tc | 23 .../test.d/trigger/trigger-wprobe-btf-offset.tc | 85 + .../test.d/trigger/trigger-wprobe-btf-typecast.tc | 85 + .../test.d/trigger/trigger-wprobe-hotplug.tc | 150 ++ .../test.d/trigger/trigger-wprobe-syntax-errors.tc | 37 .../ftrace/test.d/trigger/trigger-wprobe.tc | 107 + virt/kvm/kvm_main.c | 12 32 files changed, 2805 insertions(+), 97 deletions(-) create mode 100644 Documentation/trace/wprobetrace.rst create mode 100644 kernel/trace/trace_wprobe.c create mode 100644 tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc create mode 100644 tools/testing/selftests/ftrace/test.d/dynevent/wprobes_syntax_errors.tc create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-btf-offset.tc create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-btf-typecast.tc create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-syntax-errors.tc create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe.tc
--
Masami Hiramatsu (Google) <[email protected]>
Masami Hiramatsu (Google)
maintainerPATCH v17 1/13 x86/mce: Fix hardware debug register corruption on task migration
From: Masami Hiramatsu (Google) <[email protected]>
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.
---
Changes in v15:
- Move local_db_save() to the entry of exc_machine_check_kernel() and restore it on early return from mce_check_crashing_cpu() to prevent nested #DB on watched variables.
Changes in v14:
- Newly added.
--- arch/x86/kernel/cpu/mce/core.c | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-)
arch/x86/kernel/cpu/mce/core.c +10 -17
@@ -2108,6 +2108,9 @@ bool filter_mce(struct mce *m) static __always_inline void exc_machine_check_kernel(struct pt_regs *regs) {irqentry_state_t irq_state; +unsigned long dr7; + + dr7 =local_db_save ();WARN_ON_ONCE (user_mode (regs));
@@ -2116,20 +2119,26 @@ static __always_inline void exc_machine_check_kernel(struct pt_regs *regs)* mce_check_crashing_cpu() for details. */ if (mca_cfg.initialized &&mce_check_crashing_cpu ()) -return ; + goto out; irq_state =irqentry_nmi_enter (regs);do_machine_check (regs);irqentry_nmi_exit (regs, irq_state); +out: +local_db_restore (dr7); } static __always_inline void exc_machine_check_user(struct pt_regs *regs) { +unsigned long dr7; +irqentry_enter_from_user_mode (regs); + dr7 =local_db_save ();do_machine_check (regs); +local_db_restore (dr7);irqentry_exit_to_user_mode (regs); }
@@ -2138,21 +2147,13 @@ static __always_inline void exc_machine_check_user(struct pt_regs *regs)/* MCE hit kernel mode */ DEFINE_IDTENTRY_MCE (exc_machine_check) { -unsigned long dr7; - - dr7 =local_db_save ();exc_machine_check_kernel (regs); -local_db_restore (dr7); }/* The user mode variant. */ DEFINE_IDTENTRY_MCE_USER (exc_machine_check) { -unsigned long dr7; - - dr7 =local_db_save ();exc_machine_check_user (regs); -local_db_restore (dr7); }#ifdef CONFIG_X86_FRED
@@ -2169,28 +2170,20 @@ DEFINE_IDTENTRY_MCE_USER(exc_machine_check)*/ DEFINE_FREDENTRY_MCE (exc_machine_check) { -unsigned long dr7; - - dr7 =local_db_save ();if (user_mode (regs))exc_machine_check_user (regs);else exc_machine_check_kernel (regs); -local_db_restore (dr7); }#endif #else /* 32bit unified entry point */ DEFINE_IDTENTRY_RAW (exc_machine_check) { -unsigned long dr7; - - dr7 =local_db_save ();if (user_mode (regs))exc_machine_check_user (regs);else exc_machine_check_kernel (regs); -local_db_restore (dr7); }#endif
[email protected]
AI reviewRe: [PATCH v17 01/13] x86/mce: Fix hardware debug register corruption on task migration
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 24 lines
From: Masami Hiramatsu (Google) <[email protected]>
In
exc_machine_check_user(),local_db_save()andlocal_db_restore()are invoked in the outer entry stubs (DEFINE_IDTENTRY_MCE_USER,DEFINE_FREDENTRY_MCE, andDEFINE_IDTENTRY_RAW), surroundingexc_machine_check_user().However,
exc_machine_check_user()callsirqentry_exit_to_user_mode(), which handles pending thread work and mayschedule()ifTIF_NEED_RESCHEDis set. If the task migrates to another CPU duringschedule(),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()andlocal_db_restore()pair must be run on the same CPU.To fix this, move
local_db_save()andlocal_db_restore()insideexc_machine_check_user()andexc_machine_check_kernel(). Inexc_machine_check_user(), DR7 is saved and restored strictly arounddo_machine_check()to avoidschedule()during migration. Inexc_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.
Quoted 3 lines
Fixes cd840e424f27 ("x86/entry, mce: Disallow #DB during #MC")Assisted-by Antigravity:gemini-3.8-flashSigned-off-by Masami Hiramatsu (Google) <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=1
Borislav Petkov
maintainerRe: [PATCH v17 01/13] x86/mce: Fix hardware debug register corruption on task migration
In reply to Masami Hiramatsu (Google)Quoted 24 lines · Masami Hiramatsu (Google)
From: Masami Hiramatsu (Google) <[email protected]>
In
exc_machine_check_user(),local_db_save()andlocal_db_restore()are invoked in the outer entry stubs (DEFINE_IDTENTRY_MCE_USER,DEFINE_FREDENTRY_MCE, andDEFINE_IDTENTRY_RAW), surroundingexc_machine_check_user().However,
exc_machine_check_user()callsirqentry_exit_to_user_mode(), which handles pending thread work and mayschedule()ifTIF_NEED_RESCHEDis set. If the task migrates to another CPU duringschedule(),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()andlocal_db_restore()pair must be run on the same CPU.To fix this, move
local_db_save()andlocal_db_restore()insideexc_machine_check_user()andexc_machine_check_kernel(). Inexc_machine_check_user(), DR7 is saved and restored strictly arounddo_machine_check()to avoidschedule()during migration. Inexc_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.
Quoted 2 lines
Fixes cd840e424f27 ("x86/entry, mce: Disallow #DB during #MC")Assisted-by Antigravity:gemini-3.8-flash
verify_tags: WARNING: Zapping LLM ads tag: ['Antigravity:gemini-3.8-flash'].
Needs to be:
Please fix all your patches.
Quoted 11 lines
Signed-off-by Masami Hiramatsu (Google) <[email protected]>---
Changes in v15:
- Movelocal_db_save()to the entry ofexc_machine_check_kernel()and restore it on early return frommce_check_crashing_cpu()to prevent nested #DB on watched variables.
Changes in v14:
- Newly added.--- arch/x86/kernel/cpu/mce/core.c | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-)
Yah, makes sense.
I'm thinking this needs to be CC:stable and I should take it in now.
Peter?
Signature · 4 lines
Regards/Gruss,
Boris.
https://people.kernel.org/tglx/notes-about-netiquetteRe: [PATCH v17 01/13] x86/mce: Fix hardware debug register corruption on task migration
Quoted 48 lines · Borislav Petkov
Quoted 24 lines · Masami Hiramatsu (Google)
From: Masami Hiramatsu (Google) <[email protected]>
In
exc_machine_check_user(),local_db_save()andlocal_db_restore()are invoked in the outer entry stubs (DEFINE_IDTENTRY_MCE_USER,DEFINE_FREDENTRY_MCE, andDEFINE_IDTENTRY_RAW), surroundingexc_machine_check_user().However,
exc_machine_check_user()callsirqentry_exit_to_user_mode(), which handles pending thread work and mayschedule()ifTIF_NEED_RESCHEDis set. If the task migrates to another CPU duringschedule(),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()andlocal_db_restore()pair must be run on the same CPU.To fix this, move
local_db_save()andlocal_db_restore()insideexc_machine_check_user()andexc_machine_check_kernel(). Inexc_machine_check_user(), DR7 is saved and restored strictly arounddo_machine_check()to avoidschedule()during migration. Inexc_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.Quoted 2 lines
Fixes cd840e424f27 ("x86/entry, mce: Disallow #DB during #MC")Assisted-by Antigravity:gemini-3.8-flash
verify_tags: WARNING: Zapping LLM ads tag: ['Antigravity:gemini-3.8-flash'].Needs to be:
Assisted-by LLMPlease fix all your patches.
Quoted 11 lines
Signed-off-by Masami Hiramatsu (Google) <[email protected]>---
Changes in v15:
- Movelocal_db_save()to the entry ofexc_machine_check_kernel()and restore it on early return frommce_check_crashing_cpu()to prevent nested #DB on watched variables.
Changes in v14:
- Newly added.--- arch/x86/kernel/cpu/mce/core.c | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-)
Quoted 5 lines
Yah, makes sense.
I'm thinking this needs to be CC:stable and I should take it in now.
Peter?
Yep is right.
Masami Hiramatsu (Google)
maintainerRe: [PATCH v17 01/13] x86/mce: Fix hardware debug register corruption on task migration
In reply to Borislav PetkovQuoted 28 lines · On Tue, 22 Sep 2026 17:27:40 -0700 Borislav Petkov <[email protected]> wrote:
Quoted 24 lines · Masami Hiramatsu (Google)
From: Masami Hiramatsu (Google) <[email protected]>
In
exc_machine_check_user(),local_db_save()andlocal_db_restore()are invoked in the outer entry stubs (DEFINE_IDTENTRY_MCE_USER,DEFINE_FREDENTRY_MCE, andDEFINE_IDTENTRY_RAW), surroundingexc_machine_check_user().However,
exc_machine_check_user()callsirqentry_exit_to_user_mode(), which handles pending thread work and mayschedule()ifTIF_NEED_RESCHEDis set. If the task migrates to another CPU duringschedule(),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()andlocal_db_restore()pair must be run on the same CPU.To fix this, move
local_db_save()andlocal_db_restore()insideexc_machine_check_user()andexc_machine_check_kernel(). Inexc_machine_check_user(), DR7 is saved and restored strictly arounddo_machine_check()to avoidschedule()during migration. Inexc_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.Quoted 2 lines
Fixes cd840e424f27 ("x86/entry, mce: Disallow #DB during #MC")Assisted-by Antigravity:gemini-3.8-flash
Quoted 7 lines
verify_tags: WARNING: Zapping LLM ads tag: ['Antigravity:gemini-3.8-flash'].Needs to be:
Assisted-by LLMPlease fix all your patches.
Ah, let me fix it.
Quoted 13 lines
Quoted 9 lines
Signed-off-by Masami Hiramatsu (Google) <[email protected]>---
Changes in v15:
- Movelocal_db_save()to the entry ofexc_machine_check_kernel()and restore it on early return frommce_check_crashing_cpu()to prevent nested #DB on watched variables.
Changes in v14:
- Newly added.Quoted 3 lines
--- arch/x86/kernel/cpu/mce/core.c | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-)
Quoted 3 lines
Yah, makes sense.
I'm thinking this needs to be CC:stable and I should take it in now.
OK. thanks for review!
Quoted 8 lines
Peter?
Signature · 4 lines
Regards/Gruss, Boris. https://people.kernel.org/tglx/notes-about-netiquette
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
[tip: x86/urgent] x86/mce: Fix hardware debug register corruption on task migration
In reply to Masami Hiramatsu (Google)The following commit has been merged into the x86/urgent branch of tip:
The following commit has been merged into the x86/urgent branch of tip:
Commit-ID: b8d1d5b63a8ef532038eebd9d97d406860385668 Gitweb: https://git.kernel.org/tip/b8d1d5b63a8ef532038eebd9d97d406860385668 Author: Masami Hiramatsu (Google) <[email protected]> AuthorDate: Tue, 22 Sep 2026 13:24:55 +09:00 Committer: Borislav Petkov (AMD) <[email protected]> CommitterDate: Wed, 23 Sep 2026 11:28:56 -07:00
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.
--- arch/x86/kernel/cpu/mce/core.c | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-)
arch/x86/kernel/cpu/mce/core.c +10 -17
@@ -2108,6 +2108,9 @@ bool filter_mce(struct mce *m) static __always_inline void exc_machine_check_kernel(struct pt_regs *regs) {irqentry_state_t irq_state; +unsigned long dr7; + + dr7 =local_db_save ();WARN_ON_ONCE (user_mode (regs));
@@ -2116,20 +2119,26 @@ static __always_inline void exc_machine_check_kernel(struct pt_regs *regs)* mce_check_crashing_cpu() for details. */ if (mca_cfg.initialized &&mce_check_crashing_cpu ()) -return ; + goto out; irq_state =irqentry_nmi_enter (regs);do_machine_check (regs);irqentry_nmi_exit (regs, irq_state); +out: +local_db_restore (dr7); } static __always_inline void exc_machine_check_user(struct pt_regs *regs) { +unsigned long dr7; +irqentry_enter_from_user_mode (regs); + dr7 =local_db_save ();do_machine_check (regs); +local_db_restore (dr7);irqentry_exit_to_user_mode (regs); }
@@ -2138,21 +2147,13 @@ static __always_inline void exc_machine_check_user(struct pt_regs *regs)/* MCE hit kernel mode */ DEFINE_IDTENTRY_MCE (exc_machine_check) { -unsigned long dr7; - - dr7 =local_db_save ();exc_machine_check_kernel (regs); -local_db_restore (dr7); }/* The user mode variant. */ DEFINE_IDTENTRY_MCE_USER (exc_machine_check) { -unsigned long dr7; - - dr7 =local_db_save ();exc_machine_check_user (regs); -local_db_restore (dr7); }#ifdef CONFIG_X86_FRED
@@ -2169,28 +2170,20 @@ DEFINE_IDTENTRY_MCE_USER(exc_machine_check)*/ DEFINE_FREDENTRY_MCE (exc_machine_check) { -unsigned long dr7; - - dr7 =local_db_save ();if (user_mode (regs))exc_machine_check_user (regs);else exc_machine_check_kernel (regs); -local_db_restore (dr7); }#endif #else /* 32bit unified entry point */ DEFINE_IDTENTRY_RAW (exc_machine_check) { -unsigned long dr7; - - dr7 =local_db_save ();if (user_mode (regs))exc_machine_check_user (regs);else exc_machine_check_kernel (regs); -local_db_restore (dr7); }#endif
Masami Hiramatsu (Google)
maintainerPATCH v17 2/13 perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
When KVM enters a guest OS, host hardware breakpoints are disabled before running the guest. However, an NMI can occur while executing in guest mode or during guest transition, where arch_install_hw_breakpoint() can be invoked from NMI context.
If arch_install_hw_breakpoint() is executed while the CPU is in guest mode or during the VM entry transition window, hardware debug registers can be modified with host breakpoint settings, leaking host breakpoints into the guest OS or clobbering the guest's debug registers.
To prevent this without introducing ad-hoc per-CPU flags, introduce an .in_guest callback to struct perf_guest_info_callbacks and an inline helper perf_guest_in_guest(). In KVM, implement .in_guest by checking whether the current vCPU is in IN_GUEST_MODE or EXITING_GUEST_MODE. In arch_install_hw_breakpoint(), check perf_guest_in_guest() and return -EBUSY if the CPU is running or transitioning to/from a guest.
---
Changes in v17:
- Drop changes to local_db_save() and local_db_restore().
- Drop cpu_dr_in_guest per-CPU flag.
- Introduce .in_guest callback in perf_guest_info_callbacks and perf_guest_in_guest() helper to query vcpu->mode. (avoid breaking perf_guest_state() users)
- In arch_install_hw_breakpoint(), check perf_guest_in_guest()
Changes in v16:
- Newly added.
--- arch/x86/kernel/hw_breakpoint.c | 3 +++ include/linux/perf_event.h | 9 ++++++++- kernel/events/core.c | 5 +++++ virt/kvm/kvm_main.c | 12 ++++++++++++ 4 files changed, 28 insertions(+), 1 deletion(-)
arch/x86/kernel/hw_breakpoint.c +3 -0
@@ -102,6 +102,9 @@ int arch_install_hw_breakpoint(struct perf_event *bp)lockdep_assert_irqs_disabled (); +if (perf_guest_in_guest ()) +return -EBUSY ; +for (i =0 ; i <HBP_NUM ; i++) {struct perf_event **slot =this_cpu_ptr (&bp_per_reg[i]);
include/linux/perf_event.h +8 -1
@@ -1677,8 +1677,8 @@ struct perf_guest_info_callbacks {unsigned int (*state)(void );unsigned long (*get_ip)(void );unsigned int (*handle_intel_pt_intr)(void ); -void (*handle_mediated_pmi)(void ); +bool (*in_guest)(void ); };#ifdef CONFIG_GUEST_PERF_EVENTS
@@ -1689,6 +1689,7 @@ DECLARE_STATIC_CALL(__perf_guest_state, *perf_guest_cbs->state);DECLARE_STATIC_CALL (__perf_guest_get_ip, *perf_guest_cbs->get_ip);DECLARE_STATIC_CALL (__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);DECLARE_STATIC_CALL (__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi); +DECLARE_STATIC_CALL (__perf_guest_in_guest, *perf_guest_cbs->in_guest);static inline unsigned int perf_guest_state (void ) {
@@ -1710,6 +1711,11 @@ static inline void perf_guest_handle_mediated_pmi(void)static_call (__perf_guest_handle_mediated_pmi)(); } +static inline bool perf_guest_in_guest (void ) +{ +return static_call (__perf_guest_in_guest)(); +} +extern void perf_register_guest_info_callbacks (struct perf_guest_info_callbacks *cbs);extern void perf_unregister_guest_info_callbacks (struct perf_guest_info_callbacks *cbs);
@@ -1718,6 +1724,7 @@ extern void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbackstatic inline unsigned int perf_guest_state (void ) {return 0 ; }static inline unsigned long perf_guest_get_ip (void ) {return 0 ; }static inline unsigned int perf_guest_handle_intel_pt_intr (void ) {return 0 ; } +static inline bool perf_guest_in_guest (void ) {return false; }#endif /* !CONFIG_GUEST_PERF_EVENTS */
kernel/events/core.c +5 -0
@@ -7749,6 +7749,7 @@ DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);DEFINE_STATIC_CALL_RET0 (__perf_guest_get_ip, *perf_guest_cbs->get_ip);DEFINE_STATIC_CALL_RET0 (__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);DEFINE_STATIC_CALL_RET0 (__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi); +DEFINE_STATIC_CALL_RET0 (__perf_guest_in_guest, *perf_guest_cbs->in_guest);void perf_register_guest_info_callbacks (struct perf_guest_info_callbacks *cbs) {
@@ -7767,6 +7768,9 @@ void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)if (cbs->handle_mediated_pmi)static_call_update (__perf_guest_handle_mediated_pmi, cbs->handle_mediated_pmi); + +if (cbs->in_guest) +static_call_update (__perf_guest_in_guest, cbs->in_guest); }EXPORT_SYMBOL_GPL (perf_register_guest_info_callbacks);
@@ -7780,6 +7784,7 @@ void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)static_call_update (__perf_guest_get_ip, (void *)&__static_call_return0);static_call_update (__perf_guest_handle_intel_pt_intr, (void *)&__static_call_return0);static_call_update (__perf_guest_handle_mediated_pmi, (void *)&__static_call_return0); +static_call_update (__perf_guest_in_guest, (void *)&__static_call_return0);synchronize_rcu (); }EXPORT_SYMBOL_GPL (perf_unregister_guest_info_callbacks);
virt/kvm/kvm_main.c +12 -0
@@ -6476,11 +6476,23 @@ static unsigned long kvm_guest_get_ip(void)return kvm_arch_vcpu_get_ip (vcpu); } +static bool kvm_guest_in_guest (void ) +{ +struct kvm_vcpu *vcpu =kvm_get_running_vcpu (); + +if (!vcpu) +return false; + +return READ_ONCE (vcpu->mode) ==IN_GUEST_MODE || +READ_ONCE (vcpu->mode) ==EXITING_GUEST_MODE ; +} +static struct perf_guest_info_callbacks kvm_guest_cbs = { .state = kvm_guest_state, .get_ip = kvm_guest_get_ip, .handle_intel_pt_intr =NULL , .handle_mediated_pmi =NULL , + .in_guest = kvm_guest_in_guest, }; void __kvm_register_perf_callbacks(unsigned int (*pt_intr_handler)(void),
[email protected]
AI reviewRe: [PATCH v17 02/13] perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] perf/x86: -EBUSY in arch_install_hw_breakpoint breaks KGDB and misses NMI clobbers --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] perf/x86: -EBUSY in arch_install_hw_breakpoint breaks KGDB and misses NMI clobbers --
commit f10b90aff527e68c852cc3297fd95e985f01fa91
Author: Masami Hiramatsu (Google) <[email protected]>
perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
When KVM enters a guest OS, host hardware breakpoints are disabled before running the guest. However, an NMI can occur while executing in guest mode or during guest transition, where arch_install_hw_breakpoint() can be invoked from NMI context.
If arch_install_hw_breakpoint() is executed while the CPU is in guest mode or during the VM entry transition window, hardware debug registers can be modified with host breakpoint settings, leaking host breakpoints into the guest OS or clobbering the guest's debug registers.
arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 107
Quoted 11 lines
arch/x86/kernel/hw_breakpoint.c +3
-0@@ -102,6 +102,9 @@ int arch_install_hw_breakpoint(struct perf_event *bp)lockdep_assert_irqs_disabled (); +if (perf_guest_in_guest ()) +return -EBUSY ; +
[Severity: High]
Does returning -EBUSY here break KGDB?
If an NMI (e.g., KGDB entry) occurs while the CPU is in guest mode, this will return -EBUSY. In arch/x86/kernel/kgdb.c:kgdb_correct_hw_break(), it receives this and leaves the breakpoint permanently disabled, since it does not retry:
val = arch_install_hw_breakpoint(bp); if (!val) bp->attr.disabled = 0;
Also, since arch_uninstall_hw_breakpoint() and hw_breakpoint_restore() in arch/x86/kernel/hw_breakpoint.c do not have this perf_guest_in_guest() check, will they still unconditionally write host state to the physical DR7 register?
For example, if KGDB removes breakpoints or resumes the CPU during guest mode, they might still clobber the guest's active DR7:
arch/x86/kernel/hw_breakpoint.c:arch_uninstall_hw_breakpoint() {
...
dr7 &= ~__encode_dr7(i, info->len, info->type);
set_debugreg(dr7, 7);
...
}arch/x86/kernel/hw_breakpoint.c:hw_breakpoint_restore() {
...
set_debugreg(__this_cpu_read(cpu_dr7), 7);
...
}Quoted 3 lines
arch/x86/kernel/hw_breakpoint.c +0
-0for (i =0 ; i <HBP_NUM ; i++) {struct perf_event **slot =this_cpu_ptr (&bp_per_reg[i]);
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=2
Peter Zijlstra
maintainerRe: [PATCH v17 02/13] perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
In reply to Masami Hiramatsu (Google)Quoted 6 lines · Masami Hiramatsu (Google)
From: Masami Hiramatsu (Google) <[email protected]>
When KVM enters a guest OS, host hardware breakpoints are disabled before running the guest. However, an NMI can occur while executing in guest mode or during guest transition, where
arch_install_hw_breakpoint()can be invoked from NMI context.
How? AFAICT perf doesn't do that. arch_install_hw_breakpoint() is called through pmu::add() which is strictly IPI context.
Sean Christopherson
reviewerRe: [PATCH v17 02/13] perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Masami Hiramatsu (Google)
From: Masami Hiramatsu (Google) <[email protected]>
When KVM enters a guest OS, host hardware breakpoints are disabled before running the guest. However, an NMI can occur while executing in guest mode or during guest transition, where
arch_install_hw_breakpoint()can be invoked from NMI context.How? AFAICT perf doesn't do that.
arch_install_hw_breakpoint()is called throughpmu::add()which is strictly IPI context.
I assume it's:
kgdb_nmi_handler()
|
-> kgdb_nmicallin()
|
-> kgdb_cpu_enter()
|
-> arch_kgdb_ops.correct_hw_break()
|
-> kgdb_correct_hw_break()
|
-> arch_install_hw_breakpoint()Masami Hiramatsu (Google)
maintainerRe: [PATCH v17 02/13] perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
Quoted 17 lines · On Wed, 23 Sep 2026 07:33:15 -0700 Sean Christopherson <[email protected]>…
Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Masami Hiramatsu (Google)
From: Masami Hiramatsu (Google) <[email protected]>
When KVM enters a guest OS, host hardware breakpoints are disabled before running the guest. However, an NMI can occur while executing in guest mode or during guest transition, where
arch_install_hw_breakpoint()can be invoked from NMI context.How? AFAICT perf doesn't do that.
arch_install_hw_breakpoint()is called throughpmu::add()which is strictly IPI context.I assume it's:
kgdb_nmi_handler()
|
->kgdb_nmicallin()
Quoted 8 lines
|
-> kgdb_cpu_enter()
|
-> arch_kgdb_ops.correct_hw_break()
|
-> kgdb_correct_hw_break()
|
-> arch_install_hw_breakpoint()Yes, it is done by KGDB. perf has no problem with it.
Thank you,
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
Peter Zijlstra
maintainerRe: [PATCH v17 02/13] perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
In reply to Sean ChristophersonQuoted 17 lines · Sean Christopherson
Quoted 10 lines · Peter Zijlstra
Quoted 6 lines · Masami Hiramatsu (Google)
From: Masami Hiramatsu (Google) <[email protected]>
When KVM enters a guest OS, host hardware breakpoints are disabled before running the guest. However, an NMI can occur while executing in guest mode or during guest transition, where
arch_install_hw_breakpoint()can be invoked from NMI context.How? AFAICT perf doesn't do that.
arch_install_hw_breakpoint()is called throughpmu::add()which is strictly IPI context.I assume it's:
kgdb_nmi_handler()
|
->kgdb_nmicallin()
Quoted 8 lines
|
-> kgdb_cpu_enter()
|
-> arch_kgdb_ops.correct_hw_break()
|
-> kgdb_correct_hw_break()
|
-> arch_install_hw_breakpoint()So I would *love* to delete KGDB support for x86. Is anybody actually using this turd?
Peter Zijlstra
maintainerRe: [PATCH v17 02/13] perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
In reply to Masami Hiramatsu (Google)arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 105
Quoted 9 lines · Masami Hiramatsu (Google)
arch/x86/kernel/hw_breakpoint.c +1
-0@@ -102,6 +102,9 @@ int arch_install_hw_breakpoint(struct perf_event *bp)lockdep_assert_irqs_disabled (); +if (perf_guest_in_guest ())
That naming is hilariously bad :-)
arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 110
Quoted 5 lines
arch/x86/kernel/hw_breakpoint.c +2
-0+return -EBUSY ; +for (i =0 ; i <HBP_NUM ; i++) {struct perf_event **slot =this_cpu_ptr (&bp_per_reg[i]);
Note how the other -EBUSY return is a WARN. Why is silently not doing anything not a WARN in this case?
And I suppose this is KGDB again?
Sean Christopherson
reviewerRe: [PATCH v17 02/13] perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
Quoted 7 lines · Peter Zijlstra
Quoted 6 lines · Masami Hiramatsu (Google)
arch/x86/kernel/hw_breakpoint.c +0
-0@@ -102,6 +102,9 @@ int arch_install_hw_breakpoint(struct perf_event *bp)
Quoted 5 lines
arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 105
Quoted 3 lines
arch/x86/kernel/hw_breakpoint.c +1
-0lockdep_assert_irqs_disabled (); +if (perf_guest_in_guest ())That naming is hilariously bad :-)
Indeed. It's also misleading and confusing, because it's really checking for "in KVM's core run loop", whereas the goal of perf_guest_state() returns a non-zero value if and only if the IRQ/NMI really did occur while the guest was active (I say "the goal" because it's imperfect due to architectural limitations, but the goal is purely to detect guest PMIs).
Ugh, and routing this through perf was my suggestion[*]:
: If we decide this is how to fix arch_install_hw_breakpoint() clobbering DRs from : NMI context, I would rather have more generic flag to tell perf that KVM is about : to enter the guest, e.g. so that we don't have to separately solve the same problem : for other perf events:
After seeing the code, that feels like a pretty stupid suggestion. Though in my defense, I was thinking of a per-CPU flag as opposed to a new callback. Anyways, I don't think we should key off IN_GUEST_MODE and EXITING_GUEST_MODE because they are very much an arch-specific, KVM-internal concept.
What I was trying to say by "more generic flag" is that I would prefer not to have a super specific cpu_dr_in_guest. I'm not opposed to have a dedicated flag (though if we can avoid one, that would be lovely). The biggest problem I see with adding a generic flag is how to make it precise enough to be useful, without end up with a confusing name. E.g. "guest_state_loaded" is terrible because KVM keeps some guest state loaded even when the task is scheduled out.
And to Peter's point below, is arch_install_hw_breakpoint() even the right place to handle this? It seems like KGDB itself should be handling this, at which point maybe we just do something like this? Then we can provide nop stubs when KGDB support is disabled.
x86/kvm/x86.c +4 -0
@@ -8273,6 +8273,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)kvm_load_xfeatures (vcpu, true); +kgdb_arch_enter_guest (); +if (unlikely (vcpu->arch.switch_db_regs && !(vcpu->arch.switch_db_regs &KVM_DEBUGREG_AUTO_SWITCH ))) {set_debugreg (DR7_FIXED_1 ,7 );
@@ -8365,6 +8367,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)if (hw_breakpoint_active ())hw_breakpoint_restore (); +kgdb_arch_exit_guest (); + vcpu->arch.last_vmentry_cpu = vcpu->cpu; vcpu->arch.last_guest_tsc =kvm_read_l1_tsc (vcpu,rdtsc ());
[*] https://lore.kernel.org/all/[email protected]
Quoted 8 lines
arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 110
Quoted 5 lines
arch/x86/kernel/hw_breakpoint.c +2
-0+return -EBUSY ; +for (i =0 ; i <HBP_NUM ; i++) {struct perf_event **slot =this_cpu_ptr (&bp_per_reg[i]);Note how the other
-EBUSYreturn is a WARN. Why is silently not doing anything not a WARN in this case?
Probably because the WARN would trigger anytime KGDB's NMI craziness happens to hit a vCPU, i.e. isn't a kernel bug.
Masami Hiramatsu (Google)
maintainerRe: [PATCH v17 02/13] perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
Quoted 8 lines · On Wed, 23 Sep 2026 08:32:08 -0700 Sean Christopherson <[email protected]>…
Quoted 7 lines · Peter Zijlstra
Quoted 6 lines · Masami Hiramatsu (Google)
arch/x86/kernel/hw_breakpoint.c +0
-0@@ -102,6 +102,9 @@ int arch_install_hw_breakpoint(struct perf_event *bp)
Quoted 5 lines
Quoted 5 lines
arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 105
Quoted 3 lines
arch/x86/kernel/hw_breakpoint.c +1
-0lockdep_assert_irqs_disabled (); +if (perf_guest_in_guest ())That naming is hilariously bad :-)
Agreed.
Quoted 6 lines
Indeed. It's also misleading and confusing, because it's really checking for "in KVM's core run loop", whereas the goal of
perf_guest_state()returns a non-zero value if and only if the IRQ/NMI really did occur while the guest was active (I say "the goal" because it's imperfect due to architectural limitations, but the goal is purely to detect guest PMIs).
Yeah, I see.
Quoted 8 lines
Ugh, and routing this through perf was my suggestion[*]:
: If we decide this is how to fix
arch_install_hw_breakpoint()clobbering DRs from : NMI context, I would rather have more generic flag to tell perf that KVM is about : to enter the guest, e.g. so that we don't have to separately solve the same problem : for other perf events:
Quoted 4 lines
After seeing the code, that feels like a pretty stupid suggestion. Though in my defense, I was thinking of a per-CPU flag as opposed to a new callback. Anyways, I don't think we should key off
IN_GUEST_MODEandEXITING_GUEST_MODEbecause they are very much an arch-specific, KVM-internal concept.
OK.
Quoted 7 lines
What I was trying to say by "more generic flag" is that I would prefer not to have a super specific
cpu_dr_in_guest. I'm not opposed to have a dedicated flag (though if we can avoid one, that would be lovely). The biggest problem I see with adding a generic flag is how to make it precise enough to be useful, without end up with a confusing name. E.g. "guest_state_loaded" is terrible because KVM keeps some guest state loaded even when the task is scheduled out.
Something like "cpu_in_guest_transition"?
Quoted 5 lines
And to Peter's point below, is
arch_install_hw_breakpoint()even the right place to handle this? It seems like KGDB itself should be handling this, at which point maybe we just do something like this? Then we can provide nop stubs when KGDB support is disabled.
Hmm, so instead of kgdb specific flag, add a per-cpu flag for entering/exiting guest, and use it for kgdb and other users like wprobe? (it may work similar to in_nmi() check.)
Quoted 34 lines
x86/kvm/x86.c +4
-0@@ -8273,6 +8273,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)kvm_load_xfeatures (vcpu, true); +kgdb_arch_enter_guest (); +if (unlikely (vcpu->arch.switch_db_regs && !(vcpu->arch.switch_db_regs &KVM_DEBUGREG_AUTO_SWITCH ))) {set_debugreg (DR7_FIXED_1 ,7 );@@ -8365,6 +8367,8 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)if (hw_breakpoint_active ())hw_breakpoint_restore (); +kgdb_arch_exit_guest (); + vcpu->arch.last_vmentry_cpu = vcpu->cpu; vcpu->arch.last_guest_tsc =kvm_read_l1_tsc (vcpu,rdtsc ());[*] https://lore.kernel.org/all/[email protected]
Quoted 8 lines
arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 110
Quoted 5 lines
arch/x86/kernel/hw_breakpoint.c +2
-0+return -EBUSY ; +for (i =0 ; i <HBP_NUM ; i++) {struct perf_event **slot =this_cpu_ptr (&bp_per_reg[i]);Note how the other
-EBUSYreturn is a WARN. Why is silently not doing anything not a WARN in this case?
Quoted 2 lines
Probably because the WARN would trigger anytime KGDB's NMI craziness happens to hit a vCPU, i.e. isn't a kernel bug.
Yeah, this may confuse the caller. OK, let me change it to check the state flag in caller side.
Thank you,
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
Peter Zijlstra
maintainerRe: [PATCH v17 02/13] perf/x86, KVM: Prevent host debug register leak into guest OS on NMI
In reply to Sean ChristophersonQuoted 11 lines · Sean Christopherson
Quoted 8 lines
Review
Quoted 5 lines
(quoted diff) +2
-0+ return -EBUSY; + for (i = 0; i < HBP_NUM; i++) { struct perf_event **slot = this_cpu_ptr(&bp_per_reg[i]);Note how the other
-EBUSYreturn is a WARN. Why is silently not doing anything not a WARN in this case?Probably because the WARN would trigger anytime KGDB's NMI craziness happens to hit a vCPU, i.e. isn't a kernel bug.
Yeah, but using KGDB to install a watchpoint would then have perf/ptrace/whatnot trip the "Can't find any breakpoint slot" case and WARN, even though it isn't actually their fault either.
Masami Hiramatsu (Google)
maintainerPATCH v17 3/13 x86/hw_breakpoints: Make DR7 updates NMI safe
In reply to Masami Hiramatsu (Google)From: Jinchao Wang <[email protected]>
Hardware breakpoint installation and removal run with IRQs disabled, but an NMI can still enter the same code through KGDB. The interrupted operation and the NMI can consequently claim the same slot or overwrite each other's DR7 state.
Claim and release per-CPU slots with cmpxchg. Update cpu_dr7 with single-instruction per-CPU operations, and preserve hardware-first disable and hardware-last enable ordering. Add a per-CPU sequence number so interrupted DR7 writers and restore paths detect an NMI update and retry from the latest shadow state.
---
Changes in v17:
- Drop cpu_dr_in_guest checks in local_db_save(), local_db_restore(), and within_cpu_entry().
Changes in v16:
- In local_db_save(), remove the hypervisor check so all paths go through the sequence retry loop, preventing an intervening NMI from bypassing the sequence check on return.
- In local_db_save(), check cpu_dr7_seq before clearing hardware DR7 and load from shadow cpu_dr7 on sequence retry to prevent destructively clobbering hardware DR7 state installed by an NMI.
- In local_db_restore(), restore from shadow cpu_dr7 whenever cpu_dr7_seq changed instead of evaluating dr7 ? cpu_dr7 : 0, ensuring breakpoints installed by an NMI are preserved when dr7 was initially 0.
Changes in v15:
- Always preserve DR7_FIXED_1 in arch_install_hw_breakpoint(), arch_uninstall_hw_breakpoint(), and hw_breakpoint_restore() to comply with the x86 architectural specification.
- Wrap local_db_save() in a cpu_dr7_seq loop to detect NMI breakpoint updates and ensure DR7 is disabled before entry.
- In local_db_restore(), if dr7 is 0 and an NMI modified breakpoints, restore DR7_FIXED_1 to undo the NMI's overwrite and preserve KVM guest isolation.
- Always write "val | DR7_FIXED_1" to hardware DR7 in local_db_restore() to ensure architectural compliance.
- Avoid modifying the saved dr7 argument in-place across retry loops.
Changes in v14:
- In local_db_restore(), return immediately if saved dr7 is 0 to avoid overwriting intentionally cleared hardware DR7 state (e.g. KVM guest entry) with cpu_dr7 when an NMI increments cpu_dr7_seq.
Changes in v13:
- Add compiler barriers (barrier()) before checking cpu_dr7_seq to prevent the compiler from hoisting the sequence check before debug register updates or shadow state modifications.
Changes in v12:
- Use stack variables dr7 and dr7_seq directly in exc_nmi() and remove unnecessary per-CPU nmi_dr7 and nmi_dr7_seq variables.
--- arch/x86/include/asm/debugreg.h | 68 +++++++++++++++++++-------- arch/x86/kernel/cpu/mce/core.c | 10 ++-- arch/x86/kernel/hw_breakpoint.c | 100 ++++++++++++++++++++------------------- arch/x86/kernel/nmi.c | 7 ++- arch/x86/kernel/traps.c | 10 +++- 5 files changed, 116 insertions(+), 79 deletions(-)
arch/x86/include/asm/debugreg.h +49 -19
@@ -18,6 +18,7 @@#define DR7_FIXED_1 0x00000400 DECLARE_PER_CPU(unsigned long, cpu_dr7); +DECLARE_PER_CPU(unsigned int, cpu_dr7_seq);#ifndef CONFIG_PARAVIRT_XXL /*
@@ -125,40 +126,69 @@ static __always_inline bool hw_breakpoint_active(void)extern void hw_breakpoint_restore (void ); -static __always_inline unsigned long local_db_save (void ) +static __always_inline void local_db_save(unsigned long *dr7, +unsigned int *dr7_seq) { -unsigned long dr7; +bool retrying = false; -if (cpu_feature_enabled (X86_FEATURE_HYPERVISOR ) && !hw_breakpoint_active ()) -return 0 ; +do { +/* Inner loop: get DR7 with checking cpu_dr7_seq. */ + *dr7_seq =this_cpu_read (cpu_dr7_seq); -get_debugreg (dr7,7 ); +if (unlikely (retrying)) { + *dr7 =this_cpu_read (cpu_dr7); + }else { +get_debugreg (*dr7,7 ); -/* Architecturally set bit */ - dr7 &= ~DR7_FIXED_1 ; -if (dr7) -set_debugreg (DR7_FIXED_1 ,7 ); +/* Architecturally set bit */ + *dr7 &= ~DR7_FIXED_1 ; + } -/* -* Ensure the compiler doesn't lower the above statements into -* the critical section; disabling breakpoints late would not -* be good. -*/ -barrier (); +barrier (); +if (unlikely (*dr7_seq !=this_cpu_read (cpu_dr7_seq))) { + retrying = true; +continue ; + } + +/* Outer loop: clear DR7 and retry if sequence number is updated. */ +if (*dr7) +set_debugreg (DR7_FIXED_1 ,7 ); -return dr7; +/* +* Ensure the compiler doesn't lower the above statements into +* the critical section; disabling breakpoints late would not +* be good. +*/ +barrier (); + retrying = true; + }while (unlikely (*dr7_seq !=this_cpu_read (cpu_dr7_seq))); } -static __always_inline void local_db_restore(unsigned long dr7) +static __always_inline void local_db_restore(unsigned long dr7, +unsigned int dr7_seq) { +unsigned long val; +unsigned int seq; +/* * Ensure the compiler doesn't raise this statement into * the critical section; enabling breakpoints early would * not be good. */ barrier (); -if (dr7) -set_debugreg (dr7,7 ); +do { + seq =this_cpu_read (cpu_dr7_seq); +if (seq == dr7_seq) { +if (!dr7) +return ; + val = dr7; + }else { + val =this_cpu_read (cpu_dr7); + } + +set_debugreg (val |DR7_FIXED_1 ,7 ); +barrier (); + }while (unlikely (seq !=this_cpu_read (cpu_dr7_seq))); }#ifdef CONFIG_CPU_SUP_AMD
arch/x86/kernel/cpu/mce/core.c +6 -4
@@ -2109,8 +2109,9 @@ static __always_inline void exc_machine_check_kernel(struct pt_regs *regs) {irqentry_state_t irq_state;unsigned long dr7; +unsigned int dr7_seq; - dr7 =local_db_save (); +local_db_save (&dr7, &dr7_seq);WARN_ON_ONCE (user_mode (regs));
@@ -2127,18 +2128,19 @@ static __always_inline void exc_machine_check_kernel(struct pt_regs *regs)irqentry_nmi_exit (regs, irq_state); out: -local_db_restore (dr7); +local_db_restore (dr7, dr7_seq); } static __always_inline void exc_machine_check_user(struct pt_regs *regs) {unsigned long dr7; +unsigned int dr7_seq;irqentry_enter_from_user_mode (regs); - dr7 =local_db_save (); +local_db_save (&dr7, &dr7_seq);do_machine_check (regs); -local_db_restore (dr7); +local_db_restore (dr7, dr7_seq);irqentry_exit_to_user_mode (regs); }
arch/x86/kernel/hw_breakpoint.c +50 -50
156 lines not on this page · raw message
arch/x86/kernel/nmi.c +4 -3
@@ -531,11 +531,12 @@ enum nmi_states { }; static DEFINE_PER_CPU(enum nmi_states, nmi_state); static DEFINE_PER_CPU(unsigned long, nmi_cr2); -static DEFINE_PER_CPU(unsigned long, nmi_dr7);DEFINE_IDTENTRY_RAW (exc_nmi ) {irqentry_state_t irq_state; +unsigned long dr7; +unsigned int dr7_seq;struct nmi_stats *nsp =this_cpu_ptr (&nmi_stats);/*
@@ -572,7 +573,7 @@ DEFINE_IDTENTRY_RAW(exc_nmi)*/ sev_es_ist_enter (regs); -this_cpu_write (nmi_dr7,local_db_save ()); +local_db_save (&dr7, &dr7_seq); irq_state =irqentry_nmi_enter (regs);
@@ -594,7 +595,7 @@ DEFINE_IDTENTRY_RAW(exc_nmi)irqentry_nmi_exit (regs, irq_state); -local_db_restore (this_cpu_read (nmi_dr7)); +local_db_restore (dr7, dr7_seq);sev_es_ist_exit ();
arch/x86/kernel/traps.c +7 -3
@@ -1231,8 +1231,12 @@ static noinstr void exc_debug_kernel(struct pt_regs *regs, unsigned long dr6)* it results in an endless recursion and stack overflow. Thus we stay * with the IDT approach, i.e., save DR7 and disable #DB. */ -unsigned long dr7 =local_db_save (); -irqentry_state_t irq_state =irqentry_nmi_enter (regs); +unsigned long dr7; +unsigned int dr7_seq; +irqentry_state_t irq_state; + +local_db_save (&dr7, &dr7_seq); + irq_state =irqentry_nmi_enter (regs);instrumentation_begin ();/*
@@ -1289,7 +1293,7 @@ static noinstr void exc_debug_kernel(struct pt_regs *regs, unsigned long dr6)instrumentation_end ();irqentry_nmi_exit (regs, irq_state); -local_db_restore (dr7); +local_db_restore (dr7, dr7_seq); } static noinstr void exc_debug_user(struct pt_regs *regs, unsigned long dr6)
[email protected]
AI reviewRe: [PATCH v17 03/13] x86/hw_breakpoints: Make DR7 updates NMI safe
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 13 lines
From: Jinchao Wang <[email protected]>
Hardware breakpoint installation and removal run with IRQs disabled, but an NMI can still enter the same code through KGDB. The interrupted operation and the NMI can consequently claim the same slot or overwrite each other's DR7 state.
Claim and release per-CPU slots with cmpxchg. Update
cpu_dr7with single-instruction per-CPU operations, and preserve hardware-first disable and hardware-last enable ordering. Add a per-CPU sequence number so interrupted DR7 writers and restore paths detect an NMI update and retry from the latest shadow state.
Quoted 5 lines
Assisted-by Antigravity:gemini-3.8-flashSigned-off-by Jinchao Wang <[email protected]>Signed-off-by Masami Hiramatsu (Google) <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=3
Peter Zijlstra
maintainerRe: [PATCH v17 03/13] x86/hw_breakpoints: Make DR7 updates NMI safe
In reply to Masami Hiramatsu (Google)Quoted 7 lines · Masami Hiramatsu (Google)
From: Jinchao Wang <[email protected]>
Hardware breakpoint installation and removal run with IRQs disabled, but an NMI can still enter the same code through KGDB. The interrupted operation and the NMI can consequently claim the same slot or overwrite each other's DR7 state.
Quoted 5 lines
Claim and release per-CPU slots with cmpxchg. Update
cpu_dr7with single-instruction per-CPU operations, and preserve hardware-first disable and hardware-last enable ordering. Add a per-CPU sequence number so interrupted DR7 writers and restore paths detect an NMI update and retry from the latest shadow state.
Bah, KGDB.. Aren't there far more problems with that thing?
arch/x86/include/asm/debugreg.h line 21
Quoted 9 lines
arch/x86/include/asm/debugreg.h +1
-0@@ -18,6 +18,7 @@#define DR7_FIXED_1 0x00000400 DECLARE_PER_CPU(unsigned long, cpu_dr7); +DECLARE_PER_CPU(unsigned int, cpu_dr7_seq);
Would it make sense to:
typedef struct {
unsigned long dr7;
unsigned int seq;
} dr7_save_t;arch/x86/include/asm/debugreg.h static __always_inline bool hw_breakpoint_active(void) · line 130
Quoted 9 lines
arch/x86/include/asm/debugreg.h +2
-1#ifndef CONFIG_PARAVIRT_XXL /* @@ -125,40 +126,69 @@ static __always_inline bool hw_breakpoint_active(void)extern void hw_breakpoint_restore (void ); -static __always_inline unsigned long local_db_save (void ) +static __always_inline void local_db_save(unsigned long *dr7, +unsigned int *dr7_seq)
static __always_inline dr7_save_t local_db_save(void)
arch/x86/include/asm/debugreg.h static __always_inline bool hw_breakpoint_active(void) · line 168
Quoted 7 lines
arch/x86/include/asm/debugreg.h +2
-1{ } -static __always_inline void local_db_restore(unsigned long dr7) +static __always_inline void local_db_restore(unsigned long dr7, +unsigned int dr7_seq)
static __always_inline void local_db_restore(dr7_save_t dr7)
Quoted 29 lines
arch/x86/include/asm/debugreg.h +0
-0{ }#ifdef CONFIG_CPU_SUP_AMD arch/x86/kernel/hw_breakpoint.c +12
-0@@ -106,32 +108,25 @@ int arch_install_hw_breakpoint(struct perf_event *bp) +do { + seq =this_cpu_inc_return (cpu_dr7_seq); +this_cpu_write (cpu_debugreg[i], info->address); +barrier (); +set_debugreg (info->address, i); +if (info->mask) +amd_set_dr_addr_mask (info->mask, i); +this_cpu_or (cpu_dr7,encode_dr7 (i, info->len, info->type)); +barrier (); +set_debugreg (this_cpu_read (cpu_dr7) |DR7_FIXED_1 ,7 ); +barrier (); + }while (seq !=this_cpu_read (cpu_dr7_seq));return 0 ; }
arch/x86/kernel/hw_breakpoint.c void arch_uninstall_hw_breakpoint(struct perf_event *bp) · line 147
Quoted 4 lines
arch/x86/kernel/hw_breakpoint.c +3
-0@@ -149,36 +144,34 @@ void arch_uninstall_hw_breakpoint(struct perf_event *bp) + do { + seq = this_cpu_inc_return(cpu_dr7_seq); + dr7 = this_cpu_read(cpu_dr7);
You're inconsistent with the leading barrier().
arch/x86/kernel/hw_breakpoint.c void arch_uninstall_hw_breakpoint(struct perf_event *bp) · line 175
Quoted 13 lines
arch/x86/kernel/hw_breakpoint.c +12
-0+ dr7 &= ~__encode_dr7 (i, info->len, info->type); +set_debugreg (dr7 |DR7_FIXED_1 ,7 ); +if (info->mask) +amd_set_dr_addr_mask (0 , i); +barrier (); +this_cpu_and (cpu_dr7, + ~__encode_dr7 (i, info->len, info->type)); +barrier (); + }while (seq !=this_cpu_read (cpu_dr7_seq)); + +WARN_ONCE (this_cpu_cmpxchg (bp_per_reg[i], bp,NULL ) != bp, +"Can't release breakpoint slot" ); }
These loops should be far more similar. Note how the top one does:
this_cpu_or(cpu_dr7, encode_dr7(...)); set_debugreg(this_cpu_read(cpu_dr7) | ..., 7);
while the bottom one does:
dr7 &= ~encode_dr7(...) set_debugreg(dr7 | ...); this_cpu_and(cpu_dr7, ~encode_dr7(...));
Why can't they both have the same shape and only one encode_dr7() instance?
arch/x86/kernel/hw_breakpoint.c void flush_ptrace_hw_breakpoint(struct task_struct *tsk) · line 486
Quoted 8 lines
arch/x86/kernel/hw_breakpoint.c +4
-0@@ -486,12 +480,18 @@ void flush_ptrace_hw_breakpoint(struct task_struct *tsk)void hw_breakpoint_restore (void ) { +unsigned int seq; + + do { + seq = this_cpu_inc_return(cpu_dr7_seq);
no barrier().
arch/x86/kernel/hw_breakpoint.c void flush_ptrace_hw_breakpoint(struct task_struct *tsk) · line 496
Quoted 10 lines
arch/x86/kernel/hw_breakpoint.c +8
-0+set_debugreg (this_cpu_read (cpu_debugreg[0 ]),0 ); +set_debugreg (this_cpu_read (cpu_debugreg[1 ]),1 ); +set_debugreg (this_cpu_read (cpu_debugreg[2 ]),2 ); +set_debugreg (this_cpu_read (cpu_debugreg[3 ]),3 ); +set_debugreg (DR6_RESERVED ,6 ); +set_debugreg (this_cpu_read (cpu_dr7) |DR7_FIXED_1 ,7 ); +barrier (); + }while (seq !=this_cpu_read (cpu_dr7_seq)); }EXPORT_SYMBOL_FOR_KVM (hw_breakpoint_restore);
I really can't say I'm a fan of this. Is KGDB really a thing?
Masami Hiramatsu (Google)
maintainerRe: [PATCH v17 03/13] x86/hw_breakpoints: Make DR7 updates NMI safe
Quoted 8 lines · On Wed, 23 Sep 2026 11:13:20 +0200 Peter Zijlstra <[email protected]> wrote:
Quoted 7 lines · Masami Hiramatsu (Google)
From: Jinchao Wang <[email protected]>
Hardware breakpoint installation and removal run with IRQs disabled, but an NMI can still enter the same code through KGDB. The interrupted operation and the NMI can consequently claim the same slot or overwrite each other's DR7 state.
Quoted 7 lines
Quoted 5 lines
Claim and release per-CPU slots with cmpxchg. Update
cpu_dr7with single-instruction per-CPU operations, and preserve hardware-first disable and hardware-last enable ordering. Add a per-CPU sequence number so interrupted DR7 writers and restore paths detect an NMI update and retry from the latest shadow state.Bah, KGDB.. Aren't there far more problems with that thing?
Yes, it could be... Hmm, it looks like we need to take a closer look at other issues related to KGDB as well.
Quoted 14 lines
arch/x86/include/asm/debugreg.h line 21
Quoted 11 lines
arch/x86/include/asm/debugreg.h +1
-0@@ -18,6 +18,7 @@#define DR7_FIXED_1 0x00000400 DECLARE_PER_CPU(unsigned long, cpu_dr7); +DECLARE_PER_CPU(unsigned int, cpu_dr7_seq);Would it make sense to:
Quoted 4 lines
typedef struct {
unsigned long dr7;
unsigned int seq;
} dr7_save_t;Yeah, thanks for the good idea :)
Quoted 54 lines
arch/x86/include/asm/debugreg.h static __always_inline bool hw_breakpoint_active(void) · line 130
Quoted 11 lines
arch/x86/include/asm/debugreg.h +2
-1#ifndef CONFIG_PARAVIRT_XXL /* @@ -125,40 +126,69 @@ static __always_inline bool hw_breakpoint_active(void)extern void hw_breakpoint_restore (void ); -static __always_inline unsigned long local_db_save (void ) +static __always_inline void local_db_save(unsigned long *dr7, +unsigned int *dr7_seq)static
__always_inlinedr7_save_tlocal_db_save(void)arch/x86/include/asm/debugreg.h static __always_inline bool hw_breakpoint_active(void) · line 168
Quoted 7 lines
arch/x86/include/asm/debugreg.h +2
-1{ } -static __always_inline void local_db_restore(unsigned long dr7) +static __always_inline void local_db_restore(unsigned long dr7, +unsigned int dr7_seq)static
__always_inlinevoidlocal_db_restore(dr7_save_t dr7)Quoted 29 lines
arch/x86/include/asm/debugreg.h +0
-0{ }#ifdef CONFIG_CPU_SUP_AMD arch/x86/kernel/hw_breakpoint.c +12
-0@@ -106,32 +108,25 @@ int arch_install_hw_breakpoint(struct perf_event *bp) +do { + seq =this_cpu_inc_return (cpu_dr7_seq); +this_cpu_write (cpu_debugreg[i], info->address); +barrier (); +set_debugreg (info->address, i); +if (info->mask) +amd_set_dr_addr_mask (info->mask, i); +this_cpu_or (cpu_dr7,encode_dr7 (i, info->len, info->type)); +barrier (); +set_debugreg (this_cpu_read (cpu_dr7) |DR7_FIXED_1 ,7 ); +barrier (); + }while (seq !=this_cpu_read (cpu_dr7_seq));return 0 ; }@@ -149,36 +144,34 @@ void arch_uninstall_hw_breakpoint(struct perf_event *bp)
Quoted 5 lines
arch/x86/kernel/hw_breakpoint.c void arch_uninstall_hw_breakpoint(struct perf_event *bp) · line 162
Quoted 3 lines
arch/x86/kernel/hw_breakpoint.c +3
-0+ do { + seq = this_cpu_inc_return(cpu_dr7_seq); + dr7 = this_cpu_read(cpu_dr7);You're inconsistent with the leading
barrier().
Ah, OK.
Quoted 20 lines
Quoted 4 lines
arch/x86/kernel/hw_breakpoint.c +3
-0+ dr7 &= ~__encode_dr7 (i, info->len, info->type); +set_debugreg (dr7 |DR7_FIXED_1 ,7 ); +if (info->mask)arch/x86/kernel/hw_breakpoint.c void arch_uninstall_hw_breakpoint(struct perf_event *bp) · line 175
Quoted 10 lines
arch/x86/kernel/hw_breakpoint.c +9
-0+amd_set_dr_addr_mask (0 , i); +barrier (); +this_cpu_and (cpu_dr7, + ~__encode_dr7 (i, info->len, info->type)); +barrier (); + }while (seq !=this_cpu_read (cpu_dr7_seq)); + +WARN_ONCE (this_cpu_cmpxchg (bp_per_reg[i], bp,NULL ) != bp, +"Can't release breakpoint slot" ); }These loops should be far more similar. Note how the top one does:
this_cpu_or(cpu_dr7, encode_dr7(...)); set_debugreg(this_cpu_read(cpu_dr7) | ..., 7);
Quoted 8 lines
while the bottom one does:
dr7 &= ~encode_dr7(...) set_debugreg(dr7 | ...); this_cpu_and(cpu_dr7, ~encode_dr7(...));Why can't they both have the same shape and only one
encode_dr7()instance?
Indeed. It should have the same shape.
Quoted 13 lines
arch/x86/kernel/hw_breakpoint.c void flush_ptrace_hw_breakpoint(struct task_struct *tsk) · line 486
Quoted 10 lines
arch/x86/kernel/hw_breakpoint.c +4
-0@@ -486,12 +480,18 @@ void flush_ptrace_hw_breakpoint(struct task_struct *tsk)void hw_breakpoint_restore (void ) { +unsigned int seq; + + do { + seq = this_cpu_inc_return(cpu_dr7_seq);no
barrier().
Quoted 12 lines
arch/x86/kernel/hw_breakpoint.c void flush_ptrace_hw_breakpoint(struct task_struct *tsk) · line 496
Quoted 10 lines
arch/x86/kernel/hw_breakpoint.c +8
-0+set_debugreg (this_cpu_read (cpu_debugreg[0 ]),0 ); +set_debugreg (this_cpu_read (cpu_debugreg[1 ]),1 ); +set_debugreg (this_cpu_read (cpu_debugreg[2 ]),2 ); +set_debugreg (this_cpu_read (cpu_debugreg[3 ]),3 ); +set_debugreg (DR6_RESERVED ,6 ); +set_debugreg (this_cpu_read (cpu_dr7) |DR7_FIXED_1 ,7 ); +barrier (); + }while (seq !=this_cpu_read (cpu_dr7_seq)); }EXPORT_SYMBOL_FOR_KVM (hw_breakpoint_restore);I really can't say I'm a fan of this. Is KGDB really a thing?
No, I would like to drop this patch (and KVM patch)from this series since wprobe is not supporting to set the DR7 from NMI context.
I think it is better to split the series into 2 threads,
- wprobe related features/improvements. ([4/13]-[13/13])
- NMI-safe DR7 for KGDB. ([2/13] and [3/13])
Thank you,
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
Masami Hiramatsu (Google)
maintainerPATCH v17 4/13 x86/hw_breakpoints: Add arch_modify_local_hw_breakpoint_addr() API
In reply to Masami Hiramatsu (Google)From: Jinchao Wang <[email protected]>
Wprobe needs to move an active per-CPU watchpoint without releasing and reserving its hardware slot.
Add arch_modify_local_hw_breakpoint_addr() as the architecture backend for modify_local_hw_breakpoint_addr(). It validates the new address, finds the installed local slot, and updates the hardware debug register and per-CPU shadow register. The core layer (modify_local_hw_breakpoint_addr()) handles updating bp->attr.bp_addr and counter_arch_bp(bp)->address.
The caller must provide an installed local event and a valid address. Slot ownership, breakpoint type, length, mask and DR7 remain unchanged.
---
Changes in v17:
- In arch_modify_local_hw_breakpoint_addr(), check perf_guest_in_guest() instead of cpu_dr_in_guest.
Changes in v16:
- Clear breakpoint in shadow cpu_dr7 before setting hardware DR7 so an intervening NMI cannot re-enable the breakpoint via local_db_restore() while the address register is being updated, preventing spurious #DB exceptions.
- Check cpu_dr_in_guest and return -EBUSY to reject modifying local breakpoints while executing a KVM guest.
Changes in v15:
- Temporarily clear the breakpoint enable bit in DR7 before updating the debug address register, and re-enable it afterward, to comply with the x86 hardware specification and avoid spurious #DB exceptions.
Changes in v13:
- Add compiler barrier (barrier()) before checking cpu_dr7_seq to prevent hoisting the sequence check before set_debugreg().
- Clarify in commit log and code comment that the core layer manages updating bp->attr.bp_addr and counter_arch_bp(bp)->address.
Changes in v11:
- Return int error code instead of void.
- Validate the new address using hw_breakpoint_arch_parse() before updating registers.
- Increment cpu_dr7_seq in a sequence loop for NMI protection.
- Return -ENOENT if the breakpoint slot is not found on the local CPU.
--- arch/x86/include/asm/hw_breakpoint.h | 2 + arch/x86/kernel/hw_breakpoint.c | 61 ++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+)
arch/x86/include/asm/hw_breakpoint.h +2 -0
@@ -59,6 +59,8 @@ extern int hw_breakpoint_exceptions_notify(struct notifier_block *unused,int arch_install_hw_breakpoint (struct perf_event *bp); +int arch_modify_local_hw_breakpoint_addr (struct perf_event *bp, +unsigned long addr);void arch_uninstall_hw_breakpoint (struct perf_event *bp);void hw_breakpoint_pmu_read (struct perf_event *bp);void hw_breakpoint_pmu_unthrottle (struct perf_event *bp);
arch/x86/kernel/hw_breakpoint.c +61 -0
67 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v17 04/13] x86/hw_breakpoints: Add arch_modify_local_hw_breakpoint_addr() API
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 11 lines
From: Jinchao Wang <[email protected]>
Wprobe needs to move an active per-CPU watchpoint without releasing and reserving its hardware slot.
Add
arch_modify_local_hw_breakpoint_addr()as the architecture backend formodify_local_hw_breakpoint_addr(). It validates the new address, finds the installed local slot, and updates the hardware debug register and per-CPU shadow register. The core layer (modify_local_hw_breakpoint_addr()) handles updatingbp->attr.bp_addrand counter_arch_bp(bp)->address.
Quoted 8 lines
The caller must provide an installed local event and a valid address. Slot ownership, breakpoint type, length, mask and DR7 remain unchanged.
Assisted-by Antigravity:gemini-3.8-flashSigned-off-by Jinchao Wang <[email protected]>Signed-off-by Masami Hiramatsu (Google) <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=4
Masami Hiramatsu (Google)
maintainerPATCH v17 5/13 HWBP: Add modify_local_hw_breakpoint_addr() API
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
Add modify_local_hw_breakpoint_addr() to update only the watched address of an installed hardware breakpoint on the local CPU without releasing and reserving its hardware slot. This is available when the architecture selects CONFIG_HAVE_MODIFY_LOCAL_HW_BREAKPOINT_ADDR.
The caller must provide an installed local event and a valid address, and update other CPUs separately.
---
Changes in v15:
- Use WRITE_ONCE() for counter_arch_bp(bp)->address and bp->attr.bp_addr in both update and rollback paths to prevent data races with concurrent readers (e.g. NMI handlers).
Changes in v13:
- Add comment to modify_local_hw_breakpoint_addr() clarifying the early update behavior of bp->attr.bp_addr during the NMI race window.
Changes in v12:
- Update bp->attr.bp_addr and counter_arch_bp(bp)->address before calling arch_modify_local_hw_breakpoint_addr() to prevent race conditions during interrupt handling.
- Restore counter_arch_bp(bp)->address and bp->attr.bp_addr if arch_modify_local_hw_breakpoint_addr() fails.
Changes in v11:
- Check return value of arch_modify_local_hw_breakpoint_addr() and return error on failure.
- Update bp->attr.bp_addr and counter_arch_bp(bp)->address only after arch modification succeeds.
--- arch/Kconfig | 8 +++++++ arch/x86/Kconfig | 1 + include/linux/hw_breakpoint.h | 6 +++++ kernel/events/hw_breakpoint.c | 48 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 63 insertions(+)
arch/Kconfig +8 -0
@@ -474,6 +474,14 @@ config HAVE_MIXED_BREAKPOINTS_REGS Select this option if your arch implements breakpoints under the latter fashion. +config HAVE_MODIFY_LOCAL_HW_BREAKPOINT_ADDR + bool + depends on HAVE_HW_BREAKPOINT + help + Select this if the architecture can modify the address of an + installed hardware breakpoint on the local CPU without releasing + and reserving its hardware slot. + config HAVE_USER_RETURN_NOTIFIER bool
arch/x86/Kconfig +1 -0
@@ -249,6 +249,7 @@ config X86 select HAVE_FUNCTION_TRACER select HAVE_GCC_PLUGINS select HAVE_HW_BREAKPOINT + select HAVE_MODIFY_LOCAL_HW_BREAKPOINT_ADDR select HAVE_IOREMAP_PROT select HAVE_IRQ_EXIT_ON_IRQ_STACK if X86_64 select HAVE_IRQ_TIME_ACCOUNTING
include/linux/hw_breakpoint.h +6 -0
@@ -81,6 +81,9 @@ register_wide_hw_breakpoint(struct perf_event_attr *attr,perf_overflow_handler_t triggered, void *context); +int modify_local_hw_breakpoint_addr (struct perf_event *bp, +unsigned long addr); +extern int register_perf_hw_breakpoint (struct perf_event *bp);extern void unregister_hw_breakpoint (struct perf_event *bp);extern void unregister_wide_hw_breakpoint (struct perf_event *__percpu *cpu_events);
@@ -124,6 +127,9 @@ register_wide_hw_breakpoint(struct perf_event_attr *attr,perf_overflow_handler_t triggered, void *context) { return NULL; }static inline int +modify_local_hw_breakpoint_addr (struct perf_event *bp, +unsigned long addr) {return -EOPNOTSUPP ; } +static inline int register_perf_hw_breakpoint (struct perf_event *bp) {return -ENOSYS ; }static inline void unregister_hw_breakpoint (struct perf_event *bp) { } static inline void
kernel/events/hw_breakpoint.c +48 -0
54 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v17 05/13] HWBP: Add modify_local_hw_breakpoint_addr() API
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines
From: Masami Hiramatsu (Google) <[email protected]>
Add
modify_local_hw_breakpoint_addr()to update only the watched address of an installed hardware breakpoint on the local CPU without releasing and reserving its hardware slot. This is available when the architecture selectsCONFIG_HAVE_MODIFY_LOCAL_HW_BREAKPOINT_ADDR.
Quoted 8 lines
The caller must provide an installed local event and a valid address, and update other CPUs separately.
Assisted-by Antigravity:gemini-3.8-flashSigned-off-by Masami Hiramatsu (Google) <[email protected]>Signed-off-by Jinchao Wang <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=5
Masami Hiramatsu (Google)
maintainerPATCH v17 6/13 tracing/wprobe: Add wprobe (watchpoint probe) trace event support
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
Add hardware-breakpoint-based dynamic trace event support (wprobe). Wprobe creates a dynamic event on data read/write accesses using hardware breakpoints and logs the access context and fetchargs.
---
Changes in v16:
- Remove non-existent wprobe_events file description from readme_msg in kernel/trace/trace.c as wprobe events are created via dynamic_events.
Changes in v15:
- Introduce trace_wprobe_is_valid_addr() to validate target address and natural alignment for wprobe length during event creation.
- Move local variable declarations to function entry in trace_wprobe_show() to comply with kernel C coding standards.
- Fix indentation in kernel/trace/trace.c to use tabs instead of spaces.
Changes in v14:
- In parse_address_spec(), reject address 0 and user-space addresses by changing the check to '_addr < TASK_SIZE'.
- In trace_wprobe_show(), format symbol and offset explicitly instead of using '%pS' to ensure dynamic event restoration works properly.
- Add offset field to struct trace_wprobe and pass it to alloc_trace_wprobe().
Changes in v13:
- Fix documentation notation to SYMBOL[+|-OFFS] as same as others.
- Fix documentation indents and add default value.
- Fix README file to add [<args>].
- Add a note about module unloading.
Changes in v12:
- Fix syntax comment typo ('b' to 'w') and remove dead 'ret = 0' initialization in __trace_wprobe_create().
- Fix documentation notation to SYMBOL[[+|-]OFFS].
Changes in v11:
- Add trace_wprobe_is_busy() to prevent releasing busy events.
Changes in v9:
- Use kzalloc_flex for alloc_trace_wprobe.
--- Documentation/trace/index.rst | 1 Documentation/trace/wprobetrace.rst | 78 ++++ include/linux/trace_events.h | 2 kernel/trace/Kconfig | 13 + kernel/trace/Makefile | 1 kernel/trace/trace.c | 5 kernel/trace/trace.h | 5 kernel/trace/trace_probe.c | 21 + kernel/trace/trace_probe.h | 10 kernel/trace/trace_wprobe.c | 775 +++++++++++++++++++++++++++++++++++ 10 files changed, 907 insertions(+), 4 deletions(-) create mode 100644 Documentation/trace/wprobetrace.rst create mode 100644 kernel/trace/trace_wprobe.c
Documentation/trace/index.rst +1 -0
@@ -36,6 +36,7 @@ the Linux kernel. kprobes kprobetrace fprobetrace + wprobetrace eprobetrace fprobe ring-buffer-design
Documentation/trace/wprobetrace.rst new file +78 -0
78 lines not on this page · raw message
include/linux/trace_events.h +2 -0
@@ -337,6 +337,7 @@ enum {TRACE_EVENT_FL_UPROBE_BIT ,TRACE_EVENT_FL_EPROBE_BIT ,TRACE_EVENT_FL_FPROBE_BIT , +TRACE_EVENT_FL_WPROBE_BIT ,TRACE_EVENT_FL_CUSTOM_BIT , TRACE_EVENT_FL_TEST_STR_BIT, };
@@ -367,6 +368,7 @@ enum {TRACE_EVENT_FL_UPROBE = (1 <<TRACE_EVENT_FL_UPROBE_BIT ),TRACE_EVENT_FL_EPROBE = (1 <<TRACE_EVENT_FL_EPROBE_BIT ),TRACE_EVENT_FL_FPROBE = (1 <<TRACE_EVENT_FL_FPROBE_BIT ), +TRACE_EVENT_FL_WPROBE = (1 <<TRACE_EVENT_FL_WPROBE_BIT ),TRACE_EVENT_FL_CUSTOM = (1 <<TRACE_EVENT_FL_CUSTOM_BIT ), TRACE_EVENT_FL_TEST_STR = (1 << TRACE_EVENT_FL_TEST_STR_BIT), };
kernel/trace/Kconfig +13 -0
@@ -862,6 +862,19 @@ config EPROBE_EVENTS convert the type of an event field. For example, turn an address into a string. +config WPROBE_EVENTS + bool "Enable wprobe-based dynamic events" + depends on TRACING + depends on HAVE_HW_BREAKPOINT + select PROBE_EVENTS + select DYNAMIC_EVENTS + help + This allows the user to add watchpoint tracing events based on + hardware breakpoints on the fly via the ftrace interface. + + Those events can be inserted wherever hardware breakpoints can be + set, and record accessed memory address and values. + config BPF_EVENTS depends on BPF_SYSCALL depends on (KPROBE_EVENTS || UPROBE_EVENTS) && PERF_EVENTS
kernel/trace/Makefile +1 -0
@@ -126,6 +126,7 @@ obj-$(CONFIG_FTRACE_RECORD_RECURSION) += trace_recursion_record.o obj-$(CONFIG_FPROBE) += fprobe.o obj-$(CONFIG_RETHOOK) += rethook.o obj-$(CONFIG_FPROBE_EVENTS) += trace_fprobe.o +obj-$(CONFIG_WPROBE_EVENTS) += trace_wprobe.o obj-$(CONFIG_TRACEPOINT_BENCHMARK) += trace_benchmark.o obj-$(CONFIG_RV) += rv/
kernel/trace/trace.c +4 -1
@@ -4295,7 +4295,7 @@ static const char readme_msg[] = "\t\t\t Write into this file to define/undefine new trace events.\n"#endif #if defined(CONFIG_KPROBE_EVENTS ) || defined(CONFIG_UPROBE_EVENTS ) || \ - defined(CONFIG_FPROBE_EVENTS ) + defined(CONFIG_FPROBE_EVENTS ) || defined(CONFIG_WPROBE_EVENTS ) "\t accepts: event-definitions (one definition per line)\n"#if defined(CONFIG_KPROBE_EVENTS ) || defined(CONFIG_UPROBE_EVENTS )"\t Format: p[:[<group>/][<event>]] <place> [<args>]\n"
@@ -4305,6 +4305,9 @@ static const char readme_msg[] ="\t f[:[<group>/][<event>]] <func-name>[%return] [<args>]\n" "\t t[:[<group>/][<event>]] <tracepoint> [<args>]\n"#endif +#ifdef CONFIG_WPROBE_EVENTS + "\t w[:[<group>/][<event>]] [r|w|rw]@<addr>[:<len>] [<args>]\n" +#endif #ifdef CONFIG_HIST_TRIGGERS "\t s:[synthetic/]<event> <field> [<field>]\n"#endif
kernel/trace/trace.h +5 -0
@@ -179,6 +179,11 @@ struct fexit_trace_entry_head {unsigned long ret_ip; }; +struct wprobe_trace_entry_head { +struct trace_entry ent; +unsigned long ip; +}; +#define TRACE_BUF_SIZE 1024struct trace_array ;
kernel/trace/trace_probe.c +19 -2
@@ -1403,6 +1403,23 @@ static int parse_probe_vars(char *orig_arg, const struct fetch_type *t,return 0 ; } +/* wprobe only support "$addr" and "$value" variable */ +if (ctx->flags &TPARG_FL_WPROBE ) { +if (!strcmp (arg,"addr" )) { + code->op =FETCH_OP_BADDR ; +return 0 ; + } +if (!strcmp (arg,"value" )) { + code->op =FETCH_OP_BADDR ; + code++; + code->op =FETCH_OP_DEREF ; + code->offset =0 ; + *pcode = code; +return 0 ; + } + goto inval; + } +if (strcmp (arg,"comm" ) ==0 ||strcmp (arg,"COMM" ) ==0 ) { code->op =FETCH_OP_COMM ;return 0 ;
@@ -1462,8 +1479,8 @@ static int parse_probe_arg_register(char *arg, struct fetch_insn *code, {int ret; -if (ctx->flags & (TPARG_FL_TEVENT |TPARG_FL_FPROBE )) { -/* eprobe and fprobe do not handle registers */ +if (ctx->flags & (TPARG_FL_TEVENT |TPARG_FL_FPROBE |TPARG_FL_WPROBE )) { +/* eprobe, fprobe and wprobe do not handle registers */ trace_probe_log_err (ctx->offset,BAD_VAR );return -EINVAL ; }
kernel/trace/trace_probe.h +9 -1
@@ -90,6 +90,7 @@ typedef int (*print_type_func_t)(struct trace_seq *, void *, void *);FETCH_OP (STACK , param),/* Stack: .param = index */ \FETCH_OP (STACKP , none),/* Stack pointer */ \FETCH_OP (RETVAL , none),/* Return value */ \ +FETCH_OP (BADDR , none),/* Break address */ \FETCH_OP (IMM , imm),/* Immediate: .immediate */ \FETCH_OP (COMM , none),/* Current comm */ \ FETCH_OP(CURRENT, none), /* Current task_struct address */\
@@ -420,6 +421,7 @@ static inline int traceprobe_get_entry_data_size(struct trace_probe *tp)#define TPARG_FL_USER BIT(4)#define TPARG_FL_FPROBE BIT(5)#define TPARG_FL_TPOINT BIT(6) +#define TPARG_FL_WPROBE BIT(7)#define TPARG_FL_LOC_MASK GENMASK(4, 0)static inline bool tparg_is_function_entry (unsigned int flags)
@@ -546,6 +548,10 @@ extern int traceprobe_define_arg_fields(struct trace_event_call *event_call,C (ARG_TOO_LONG ,"Argument expression is too long" ), \C (ARRAY_NO_CLOSE ,"Array is not closed" ), \C (ARRAY_TOO_BIG ,"Array number is too big" ), \ +C (BAD_ACCESS_ADDR ,"Invalid access memory address" ), \ +C (BAD_ACCESS_FMT ,"Access memory address requires @" ), \ +C (BAD_ACCESS_LEN ,"This memory access length is not supported" ), \ +C (BAD_ACCESS_TYPE ,"Bad memory access type" ), \C (BAD_ADDR_SUFFIX ,"Invalid probed address suffix" ), \C (BAD_ARG_NAME ,"Argument name must follow the same rules as C identifiers" ), \ C(BAD_ARG_NUM, "Invalid argument number"), \
@@ -628,7 +634,9 @@ extern int traceprobe_define_arg_fields(struct trace_event_call *event_call,C (TYPECAST_NOT_EVENT ,"Typecasts are only for eprobe fields" ), \C (TYPECAST_REQ_FIELD ,"Typecast requires a field access" ), \C (TYPECAST_SYM_OFFSET ,"@SYM+/-OFFSET with typecast needs parentheses" ), \ -C (USED_ARG_NAME ,"This argument name is already used" ), +C (USED_ARG_NAME ,"This argument name is already used" ), \ +C (WPROBE_NO_MAXACT ,"Watchpoint probe does not support maxactive" ), \ +C (WPROBE_NO_SIBLING ,"Watchpoint probe does not support sibling probes" ), #undef C #define C(a, b) TP_ERR_##a
kernel/trace/trace_wprobe.c new file +775 -0
775 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v17 06/13] tracing/wprobe: Add wprobe (watchpoint probe) trace event support
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 10 lines
From: Masami Hiramatsu (Google) <[email protected]>
Add hardware-breakpoint-based dynamic trace event support (wprobe). Wprobe creates a dynamic event on data read/write accesses using hardware breakpoints and logs the access context and fetchargs.
Assisted-by Antigravity:gemini-3.8-flashSigned-off-by Masami Hiramatsu (Google) <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=6
Masami Hiramatsu (Google)
maintainerPATCH v17 7/13 x86: hw_breakpoint: Add a kconfig to clarify when a breakpoint fires
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
Add CONFIG_HAVE_POST_BREAKPOINT_HOOK which indicates the hw_breakpoint on that architecture fires after the target memory has been modified. This is currently x86 only behavior.
---
Changes in v11:
- Move select to alphabetically sorted place.
--- arch/Kconfig | 10 ++++++++++ arch/x86/Kconfig | 1 + kernel/trace/Kconfig | 1 + 3 files changed, 12 insertions(+)
arch/Kconfig +10 -0
@@ -474,6 +474,16 @@ config HAVE_MIXED_BREAKPOINTS_REGS Select this option if your arch implements breakpoints under the latter fashion. +config HAVE_POST_BREAKPOINT_HOOK + bool + depends on HAVE_HW_BREAKPOINT + help + Depending on the arch implementation of hardware breakpoints, + some of them provide breakpoint hook after the target memory + is modified. + Select this option if your arch implements breakpoints overflow + handler hooks after the target memory is modified. + config HAVE_MODIFY_LOCAL_HW_BREAKPOINT_ADDR bool depends on HAVE_HW_BREAKPOINT
arch/x86/Kconfig +1 -0
@@ -289,6 +289,7 @@ config X86 select MMU_GATHER_RCU_TABLE_FREE select MMU_GATHER_MERGE_VMAS select HAVE_POSIX_CPU_TIMERS_TASK_WORK + select HAVE_POST_BREAKPOINT_HOOK select HAVE_REGS_AND_STACK_ACCESS_API select HAVE_RELIABLE_STACKTRACE if UNWINDER_ORC || STACK_VALIDATION select HAVE_FUNCTION_ARG_ACCESS_API
kernel/trace/Kconfig +1 -0
@@ -866,6 +866,7 @@ config WPROBE_EVENTS bool "Enable wprobe-based dynamic events" depends on TRACING depends on HAVE_HW_BREAKPOINT + depends on HAVE_POST_BREAKPOINT_HOOK select PROBE_EVENTS select DYNAMIC_EVENTS help
[email protected]
AI reviewRe: [PATCH v17 07/13] x86: hw_breakpoint: Add a kconfig to clarify when a breakpoint fires
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 7 lines
From: Masami Hiramatsu (Google) <[email protected]>
Add
CONFIG_HAVE_POST_BREAKPOINT_HOOKwhich indicates thehw_breakpointon that architecture fires after the target memory has been modified. This is currently x86 only behavior.Signed-off-by Masami Hiramatsu (Google) <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=7
Masami Hiramatsu (Google)
maintainerPATCH v17 8/13 selftests: tracing: Add a basic testcase for wprobe
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
Add 'add_remove_wprobe.tc' testcase for testing wprobe event that tests adding and removing operations of the wprobe event.
---
Changes in v17:
- Catch failures when enabling wprobe and call exit_unresolved in case hardware watchpoints are exhausted.
Changes in v9:
- Fix command check logic to prevent early exit under 'set -e' (errexit) when grep or test fails.
- Simplify enable/disable status checks by removing cat pipes.
Changes in v8:
- Fixed silently test failure path.
--- tools/testing/selftests/ftrace/config | 1 .../ftrace/test.d/dynevent/add_remove_wprobe.tc | 66 ++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc
tools/testing/selftests/ftrace/config +1 -0
@@ -27,3 +27,4 @@ CONFIG_STACK_TRACER=y CONFIG_TRACER_SNAPSHOT=y CONFIG_UPROBES=y CONFIG_UPROBE_EVENTS=y +CONFIG_WPROBE_EVENTS=y
tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc new file +66 -0
66 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v17 08/13] selftests: tracing: Add a basic testcase for wprobe
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 6 lines
From: Masami Hiramatsu (Google) <[email protected]>
Add 'add_remove_wprobe.tc' testcase for testing wprobe event that tests adding and removing operations of the wprobe event.
Signed-off-by Masami Hiramatsu (Google) <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=8
Masami Hiramatsu (Google)
maintainerPATCH v17 9/13 selftests: tracing: Add syntax testcase for wprobe
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
Add "wprobe_syntax_errors.tc" testcase for testing syntax errors of the watch probe events.
---
Changes in v14:
- Update comment for invalid offset syntax check to BAD_PROBE_ADDR.
- Add testcase for invalid address 0 error check (BAD_ACCESS_ADDR).
Changes in v12:
- Add NO_ARG_BODY error case.
Changes in v11:
- Add WPROBE_NO_MAXACT syntax error case.
--- .../test.d/dynevent/wprobes_syntax_errors.tc | 23 ++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 tools/testing/selftests/ftrace/test.d/dynevent/wprobes_syntax_errors.tc
tools/testing/selftests/ftrace/test.d/dynevent/wprobes_syntax_errors.tc new file +23 -0
@@ -0,0 +1,23 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# description: Watch probe event parser error log check +# requires: dynamic_events "w[:[<group>/][<event>]] [r|w|rw]@<addr>[:<len>]":README + +check_error() { # command-with-error-pos-by-^ + ftrace_errlog_check 'wprobe' "$1" 'dynamic_events' +} + +check_error '^w' # NO_ARG_BODY +check_error 'w^10 w@jiffies' # WPROBE_NO_MAXACT +check_error 'w ^symbol' # BAD_ACCESS_FMT +check_error 'w ^a@symbol' # BAD_ACCESS_TYPE +check_error 'w w@^symbol' # BAD_ACCESS_ADDR +check_error 'w w@^0:4' # BAD_ACCESS_ADDR +check_error 'w w@jiffies^+offset' # BAD_PROBE_ADDR +check_error 'w w@jiffies:^100' # BAD_ACCESS_LEN +check_error 'w w@jiffies ^$arg1' # BAD_VAR +check_error 'w w@jiffies ^$retval' # BAD_VAR +check_error 'w w@jiffies ^$stack' # BAD_VAR +check_error 'w w@jiffies ^%ax' # BAD_VAR + +exit 0
[email protected]
AI reviewRe: [PATCH v17 09/13] selftests: tracing: Add syntax testcase for wprobe
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 6 lines
From: Masami Hiramatsu (Google) <[email protected]>
Add "wprobe_syntax_errors.tc" testcase for testing syntax errors of the watch probe events.
Signed-off-by Masami Hiramatsu (Google) <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=9
Masami Hiramatsu (Google)
maintainerPATCH v17 10/13 tracing/wprobe: Add set_wprobe and clear_wprobe event triggers
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
Add set_wprobe and clear_wprobe event triggers to dynamically attach and detach hardware breakpoint address monitoring based on event field contents.
---
Changes in v17:
- Add dynamic CPU hotplug callbacks to handle CPU offline/online.
- Restore EVENT_FILE_FL_SOFT_DISABLED_BIT in wprobe_trigger_free().
- Check whether trigger event has "unlimited" field before skipping "unlimited" in clear_wprobe trigger parsing.
- Call tracepoint_synchronize_unregister() before freeing trigger data via data->cmd_ops->free() on registration failure.
- Implement __wprobe_count_func()/wprobe_count_func() helpers to consolidate precondition checks and use it for count_func() and inside wprobe_trigger() function.
Changes in v16:
- Immediately update the hardware breakpoint on the local CPU via trace_wprobe_update_local() in wprobe_trigger() to avoid workqueue latency, and only kick irq_work for other CPUs.
- Skip redundant updates in trace_wprobe_update_local() if bp->attr.bp_addr already matches the target address.
- Use strcmp() instead of strncmp() for "unlimited" to avoid misinterpreting field names starting with "unlimited" as count.
- Normalize "unlimited" and "count=" parameters before creating trigger data so trigger parsing handles count keywords correctly.
Changes in v15:
- Use trace_wprobe_is_valid_addr() in wprobe_trigger() to validate address and natural alignment for wprobe length.
- Record SMP local update failures in tw->missed counter.
- Expose missed event count as a trailing comment in trigger file.
- Add set_wprobe and clear_wprobe triggers to readme_msg in trace.c.
- Fix line length exceeding 100 columns in wprobe_trigger_log_err macro.
- Initialize irq_work and work structs immediately after allocation in alloc_trace_wprobe() and check tw->work.func in free_trace_wprobe() to prevent WARN_ON(!work->func) on early allocation failure.
Changes in v14:
- Allow '-1' as a dummy address in parse_address_spec() to set initial address to WPROBE_DEFAULT_CLEAR_ADDRESS for trigger-only wprobes.
- In trace_wprobe_show(), format WPROBE_DEFAULT_CLEAR_ADDRESS as '-1'.
- Update documentation and examples to use '-1' instead of '0'.
- Skip field parsing in clear_wprobe if parameter is a count keyword.
- Set tw->addr to WPROBE_DEFAULT_CLEAR_ADDRESS before soft-enabling event and roll back on failure.
- Fix memory and refcount leak of trigger_data/wprobe_data on error path.
Changes in v13:
- Align WPROBE_DEFAULT_CLEAR_ADDRESS to 8 bytes using dedicated u64.
- Remove manual count decrement to rely on core event_trigger_count().
- Parse optional FIELD argument in clear_wprobe command.
- Fix trigger reference count leak and error cleanup in command parsing.
- Update document to add [:COUNT] to trigger syntax and fix adjust forms.
- Add notes about the exclusive trigger setting behavior.
- Remove unused dyn_event_ops_mutex.
Changes in v12:
- Decrement trigger data->count only when watchpoint state is actually changed.
- Remove dyn_event_ops_mutex to fix lockdep circular dependency deadlock.
- Add event_trigger_init() call to prevent premature freeing of trigger_data.
--- Documentation/trace/wprobetrace.rst | 107 +++++ include/linux/trace_events.h | 1 kernel/trace/Kconfig | 10 kernel/trace/trace.c | 4 kernel/trace/trace.h | 1 kernel/trace/trace_events_trigger.c | 2 kernel/trace/trace_probe.c | 2 kernel/trace/trace_probe.h | 9 kernel/trace/trace_wprobe.c | 757 +++++++++++++++++++++++++++++++++++ 9 files changed, 889 insertions(+), 4 deletions(-)
Documentation/trace/wprobetrace.rst +107 -0
@@ -76,3 +76,110 @@ Wprobe event does not disable itself even if the module is unloaded. For example, if you add a wprobe event on a module variable, and then unload the module, the wprobe event will still be enabled. This is for watching the address is used unexpectedly after the module is unloaded. + +Combination with trigger action +------------------------------- +The event trigger action can extend the utilization of this wprobe. + +- set_wprobe:WPEVENT:FIELD[+|-ADJUST][:COUNT] +- clear_wprobe:WPEVENT[:FIELD[+|-ADJUST][:COUNT]] + +Set these triggers to the target event, then the WPROBE event will be +setup to trace the memory access at FIELD[+|-ADJUST] address. +When clear_wprobe is hit, if FIELD is NOT specified, the WPEVENT is +forcibly cleared. If FIELD[+|-ADJUST] is set, it clears WPEVENT only +if its watching address is the same as the FIELD[+|-ADJUST] value. +If COUNT is specified, it will set/clear WPEVENT only if it hits COUNT +times. + +Notes: +- set_wprobe only works on the wprobe which is NOT set a valid address yet, + and it must be enabled after the trigger is set. +- clear_wprobe only works on the wprobe which is set a valid address, and it + will be soft-disabled after the trigger is cleared. +- Therefore, if a trigger sets/clears a wprobe, other/same trigger events + will not work (on the same event) while the wprobe is set. + +The set_wprobe trigger does not change the type and length, these +must be set when creating a new wprobe. + +The WPROBE event must be disabled when setting the new trigger +and it will be busy afterwards. Recommended usage is to add a new +wprobe at invalid dummy address (-1) and keep disabled. + +Wprobe triggers only support target addresses in kernel memory. If a +set_wprobe trigger evaluates to a user-space memory address or NULL +pointer, the trigger action ignores the update and skips setting the +watchpoint. + +Wprobe triggers are not supported on kprobe_events, because kprobes +themselves can use software breakpoints which conflicts with wprobe +operation. + + +For example, trace the first 8 bytes of the dentry data structure passed +to do_truncate() until it is deleted by dentry_kill(). +(Note: all tracefs setup uses '>>' so that it does not kick do_truncate()) +:: + + # echo 'w:watch rw@-1:8 address=$addr value=+0($addr)' >> dynamic_events + # echo 'f:truncate do_truncate dentry=$arg2' >> dynamic_events + # echo 'set_wprobe:watch:dentry' >> events/fprobes/truncate/trigger + # echo 'f:dentry_kill dentry_kill dentry=$arg1' >> dynamic_events + # echo 'clear_wprobe:watch:dentry' >> events/fprobes/dentry_kill/trigger + # echo 1 >> events/fprobes/truncate/enable + # echo 1 >> events/fprobes/dentry_kill/enable + + # echo aaa > /tmp/hoge + # echo bbb > /tmp/hoge + # echo ccc > /tmp/hoge + # rm /tmp/hoge + +Then, the trace data will show:: + + # tracer: nop + # + # entries-in-buffer/entries-written: 32/32 #P:8 + # + # _-----=> irqs-off/BH-disabled + # / _----=> need-resched + # | / _---=> hardirq/softirq + # || / _--=> preempt-depth + # ||| / _-=> migrate-disable + # |||| / delay + # TASK-PID CPU# ||||| TIMESTAMP FUNCTION + # | | | ||||| | | + sh-107 [004] ...1. 9.990418: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004ad6618 + sh-107 [004] ...1. 9.990914: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004b3de78 + sh-107 [004] ...1. 9.993175: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049ddd40 + sh-107 [004] ..... 9.995198: truncate: (do_truncate+0x4/0x120) dentry=0xffff8880048083a8 + sh-107 [004] ...1. 9.995389: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049db998 + sh-107 [004] ..Zff 9.997503: watch: (lookup_fast+0xaa/0x150) address=0xffff8880048083a8 value=0x8200080 + sh-107 [004] ..Zff 9.997509: watch: (path_openat+0x211/0xda0) address=0xffff8880048083a8 value=0x8200080 + sh-107 [004] ..Zff 9.997514: watch: (path_openat+0xa56/0xda0) address=0xffff8880048083a8 value=0x8200080 + sh-107 [004] ..Zff 9.997518: watch: (path_openat+0xae2/0xda0) address=0xffff8880048083a8 value=0x8200080 + sh-107 [004] ..... 9.997521: truncate: (do_truncate+0x4/0x120) dentry=0xffff8880048083a8 + sh-107 [004] ...1. 9.997582: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004808270 + sh-107 [004] ...1. 9.999365: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049db728 + sh-107 [004] ...1. 9.999388: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004b1c000 + rm-113 [005] ..Zff 10.000965: watch: (lookup_fast+0xaa/0x150) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] ..Zff 10.000971: watch: (path_lookupat+0x97/0x1e0) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] ..Zff 10.000984: watch: (lookup_fast+0xaa/0x150) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] ..Zff 10.000988: watch: (path_lookupat+0x97/0x1e0) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] ..Zff 10.001010: watch: (lookup_one_qstr_excl+0x28/0x140) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] ..Zff 10.001014: watch: (lookup_one_qstr_excl+0xd1/0x140) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] ..Zff 10.001018: watch: (may_delete_dentry+0x1c/0x200) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] ..Zff 10.001021: watch: (may_delete_dentry+0x195/0x200) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] ..Zff 10.001031: watch: (vfs_unlink+0x5e/0x260) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] d.Z.. 10.001067: watch: (d_make_discardable+0x1b/0x40) address=0xffff8880048083a8 value=0x8200080 + rm-113 [005] d.Z.. 10.001071: watch: (d_make_discardable+0x29/0x40) address=0xffff8880048083a8 value=0x200080 + rm-113 [005] ...1. 10.001072: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880048083a8 + rm-113 [005] ...1. 10.001218: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880048083a8 + sh-107 [004] ...1. 10.001416: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049db110 + sh-107 [004] ...1. 10.001444: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff8880049db248 + sh-107 [004] ...1. 10.001500: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004ad6618 + sh-107 [004] ...1. 10.002067: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004b41e78 + sh-107 [004] ...1. 10.904920: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004b41e78 + sh-107 [004] ...1. 10.905129: dentry_kill: (dentry_kill+0x0/0x2c0) dentry=0xffff888004ad6618 + +You can see the watch event is correctly configured on the dentry.
include/linux/trace_events.h +1 -0
@@ -738,6 +738,7 @@ enum event_trigger_type {ETT_EVENT_HIST = (1 <<4 ),ETT_HIST_ENABLE = (1 <<5 ),ETT_EVENT_EPROBE = (1 <<6 ), + ETT_EVENT_WPROBE = (1 << 7), };extern int filter_match_preds (struct event_filter *filter,void *rec);
kernel/trace/Kconfig +10 -0
@@ -876,6 +876,16 @@ config WPROBE_EVENTS Those events can be inserted wherever hardware breakpoints can be set, and record accessed memory address and values. +config WPROBE_TRIGGERS + depends on WPROBE_EVENTS + depends on HAVE_MODIFY_LOCAL_HW_BREAKPOINT_ADDR + bool + default y + help + This adds an event trigger which will set the wprobe on a specific + field of an event. This allows user to trace the memory access of + an address pointed by the event field. + config BPF_EVENTS depends on BPF_SYSCALL depends on (KPROBE_EVENTS || UPROBE_EVENTS) && PERF_EVENTS
kernel/trace/trace.c +4 -0
@@ -4362,6 +4362,10 @@ static const char readme_msg[] = "\t trigger: traceon, traceoff\n" "\t enable_event:<system>:<event>\n" "\t disable_event:<system>:<event>\n" +#ifdef CONFIG_WPROBE_TRIGGERS + "\t set_wprobe:<wprobe-event>:<field>[+|-<offset>]\n" + "\t clear_wprobe:<wprobe-event>[:<field>[+|-<offset>]]\n" +#endif#ifdef CONFIG_HIST_TRIGGERS "\t enable_hist:<system>:<event>\n" "\t disable_hist:<system>:<event>\n"
kernel/trace/trace.h +1 -0
@@ -1983,6 +1983,7 @@ trigger_data_alloc(struct event_command *cmd_ops, char *cmd, char *param, void *private_data);extern void trigger_data_free (struct event_trigger_data *data);extern int event_trigger_init (struct event_trigger_data *data); +extern void event_trigger_free (struct event_trigger_data *data);extern int trace_event_trigger_enable_disable (struct trace_event_file *file,int trigger_enable);extern void update_cond_flag (struct trace_event_file *file);
kernel/trace/trace_events_trigger.c +1 -1
@@ -589,7 +589,7 @@ int event_trigger_init(struct event_trigger_data *data)* Usually used directly as the @free method in event trigger * implementations. */ -static void +void event_trigger_free (struct event_trigger_data *data) {if (WARN_ON_ONCE (data->ref <=0 ))
kernel/trace/trace_probe.c +1 -1
@@ -20,7 +20,7 @@#undef C#define C (a, b) b -static const char *trace_probe_err_text[] = {ERRORS }; +const char *trace_probe_err_text[] = {ERRORS };static const char *reserved_field_names[] = {"common_type" ,
kernel/trace/trace_probe.h +8 -1
@@ -636,7 +636,12 @@ extern int traceprobe_define_arg_fields(struct trace_event_call *event_call,C (TYPECAST_SYM_OFFSET ,"@SYM+/-OFFSET with typecast needs parentheses" ), \C (USED_ARG_NAME ,"This argument name is already used" ), \C (WPROBE_NO_MAXACT ,"Watchpoint probe does not support maxactive" ), \ -C (WPROBE_NO_SIBLING ,"Watchpoint probe does not support sibling probes" ), +C (WPROBE_NO_SIBLING ,"Watchpoint probe does not support sibling probes" ), \ +C (WPROBE_ON_KPROBE ,"Wprobe trigger is not supported on kprobe event" ), \ +C (WPROBE_NOT_FOUND ,"Target wprobe event is not found" ), \ +C (WPROBE_BUSY ,"Target wprobe event is already enabled" ), \ +C (WPROBE_NEED_FIELD ,"Wprobe trigger requires a target field" ), \ +C (WPROBE_BAD_FIELD ,"Target field must be pointer size" ), #undef C #define C(a, b) TP_ERR_##a
@@ -660,6 +665,8 @@ void __trace_probe_log_err(int offset, int err); DEFINE_FREE(trace_probe_log_clear, const char *, if (_T) trace_probe_log_clear()) +extern const char *trace_probe_err_text[]; +#define trace_probe_log_err (offs, err) \ __trace_probe_log_err(offs, TP_ERR_##err)
kernel/trace/trace_wprobe.c +756 -1
846 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v17 10/13] tracing/wprobe: Add set_wprobe and clear_wprobe event triggers
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] tracing/wprobe: NMI deadlock in wprobe_trigger() when count is not specified - [High]…
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] tracing/wprobe: NMI deadlock in wprobe_trigger() when count is not specified
- [High] tracing/wprobe: CPU hotplug race in __register_trace_wprobe() misses new CPUs
- [Medium] tracing/wprobe: TOCTOU race in wprobe_trigger() corrupts watchpoint address --
commit b9f67542e6bf772512bb8cbf3c3011379c301eb4
Author: Masami Hiramatsu (Google) <[email protected]>
tracing/wprobe: Add set_wprobe and clear_wprobe event triggers
Add set_wprobe and clear_wprobe event triggers to dynamically attach and detach hardware breakpoint address monitoring based on event field contents.
Quoted 5 lines
kernel/trace/trace_wprobe.c +0
-0@@ -193,20 +217,130 @@ static int __register_trace_wprobe(struct trace_wprobe *tw)
[ ... ]
kernel/trace/trace_wprobe.c static int __register_trace_wprobe(struct trace_wprobe *tw) · line 263
Quoted 12 lines
kernel/trace/trace_wprobe.c +4
-0tw->bp_event =register_wide_hw_breakpoint (&attr, wprobe_perf_handler, tw);if (IS_ERR_PCPU (tw->bp_event)) {int ret =PTR_ERR_PCPU (tw->bp_event); tw->bp_event =NULL ;return ret; } +mutex_lock (&wprobe_mutex); +list_add (&tw->active_list, &active_wprobes); +mutex_unlock (&wprobe_mutex); +
[Severity: High]
Does this code have a race condition with CPU hotplug?
Looking at __register_trace_wprobe(), it calls register_wide_hw_breakpoint() which installs breakpoints and releases the hotplug lock internally.
If a new CPU comes online immediately after that lock is released, but before this wprobe is added to active_wprobes under wprobe_mutex, could the wprobe_cpu_online() callback miss the wprobe? This would leave the new CPU without hardware breakpoints installed for this probe.
Quoted 2 lines
return 0;
}
[ ... ]
Quoted 1 line
kernel/trace/trace_wprobe.c +0
-0@@ -767,9 +923,608 @@ static int trace_wprobe_show(struct seq_file *m, struct dyn_event *ev)
[ ... ]
Quoted 7 lines
kernel/trace/trace_wprobe.c +7
-0+static void wprobe_trigger (struct event_trigger_data *data, +struct trace_buffer *buffer,void *rec, +struct ring_buffer_event *event) +{ +struct wprobe_trigger_data *wprobe_data = data->private_data; +struct trace_wprobe *tw = wprobe_data->tw; +unsigned long target_addr, addr =0 , flags;
kernel/trace/trace_wprobe.c static int trace_wprobe_show(struct seq_file *m, struct dyn_event *ev) · line 1040
Quoted 10 lines
kernel/trace/trace_wprobe.c +10
-0+ +if (wprobe_data->field) { +if (!rec) +return ; + addr = *(unsigned long *)((char *)rec + wprobe_data->offset); + addr += wprobe_data->adjust; + } + +raw_spin_lock_irqsave (&tw->lock, flags); +
[Severity: High]
Could this raw_spin_lock_irqsave() cause a deadlock if interrupted by an NMI?
When no count limit is specified (EVENT_TRIGGER_FL_COUNT is not set), wprobe_trigger() takes tw->lock before calling __wprobe_count_func().
If an NMI interrupts a CPU already holding tw->lock and hits a trace event that fires the same uncounted trigger, it will attempt to acquire tw->lock again here. Since the in_nmi() check is located inside __wprobe_count_func(), the NMI would spin forever before realizing it shouldn't proceed.
kernel/trace/trace_wprobe.c static int trace_wprobe_show(struct seq_file *m, struct dyn_event *ev) · line 1046
Quoted 6 lines
kernel/trace/trace_wprobe.c +6
-0+if (!(data->flags &EVENT_TRIGGER_FL_COUNT )) { +if (!__wprobe_count_func (data, addr)) { +atomic_inc (&tw->missed); + goto out; + } + }
[Severity: Medium]
Is there a time-of-check to time-of-use (TOCTOU) race here for counted triggers?
For counted triggers, wprobe_count_func() is called locklessly by the trace core, which evaluates __wprobe_count_func(). Then, wprobe_trigger() is called and takes tw->lock. Because EVENT_TRIGGER_FL_COUNT is set, the state validation check (__wprobe_count_func()) is explicitly skipped under the lock.
If a counted trigger fires concurrently on multiple CPUs, both might observe the unset address locklessly. Could the second CPU unconditionally overwrite tw->addr, breaking the exclusive trigger constraint?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=10
Masami Hiramatsu (Google)
maintainerRe: [PATCH v17 10/13] tracing/wprobe: Add set_wprobe and clear_wprobe event triggers
Quoted 41 lines · On Tue, 22 Sep 2026 04:43:24 +0000 [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] tracing/wprobe: NMI deadlock inwprobe_trigger()when count is not specified
- [High] tracing/wprobe: CPU hotplug race in__register_trace_wprobe()misses new CPUs
- [Medium] tracing/wprobe: TOCTOU race inwprobe_trigger()corrupts watchpoint address --commit
b9f67542e6bf772512bb8cbf3c3011379c301eb4
Author: Masami Hiramatsu (Google) <[email protected]>tracing/wprobe: Add
set_wprobeandclear_wprobeevent triggersAdd
set_wprobeandclear_wprobeevent triggers to dynamically attach and detach hardware breakpoint address monitoring based on event field contents.Quoted 5 lines
kernel/trace/trace_wprobe.c +0
-0@@ -193,20 +217,130 @@ static int __register_trace_wprobe(struct trace_wprobe *tw)[ ... ]
kernel/trace/trace_wprobe.c static int __register_trace_wprobe(struct trace_wprobe *tw) · line 263
Quoted 12 lines
kernel/trace/trace_wprobe.c +4
-0tw->bp_event =register_wide_hw_breakpoint (&attr, wprobe_perf_handler, tw);if (IS_ERR_PCPU (tw->bp_event)) {int ret =PTR_ERR_PCPU (tw->bp_event); tw->bp_event =NULL ;return ret; } +mutex_lock (&wprobe_mutex); +list_add (&tw->active_list, &active_wprobes); +mutex_unlock (&wprobe_mutex); +[Severity: High]
Does this code have a race condition with CPU hotplug?
Quoted 7 lines
Looking at
__register_trace_wprobe(), it callsregister_wide_hw_breakpoint()which installs breakpoints and releases the hotplug lock internally.If a new CPU comes online immediately after that lock is released, but before this wprobe is added to
active_wprobesunderwprobe_mutex, could thewprobe_cpu_online()callback miss the wprobe? This would leave the new CPU without hardware breakpoints installed for this probe.
Hmm, OK. Taking a cpus_read_lock() for both can avoid this issue.
Quoted 31 lines
Quoted 3 lines
return 0;
}[ ... ]
Quoted 1 line
kernel/trace/trace_wprobe.c +0
-0@@ -767,9 +923,608 @@ static int trace_wprobe_show(struct seq_file *m, struct dyn_event *ev)[ ... ]
Quoted 7 lines
kernel/trace/trace_wprobe.c +7
-0+static void wprobe_trigger (struct event_trigger_data *data, +struct trace_buffer *buffer,void *rec, +struct ring_buffer_event *event) +{ +struct wprobe_trigger_data *wprobe_data = data->private_data; +struct trace_wprobe *tw = wprobe_data->tw; +unsigned long target_addr, addr =0 , flags;kernel/trace/trace_wprobe.c static int trace_wprobe_show(struct seq_file *m, struct dyn_event *ev) · line 1040
Quoted 10 lines
kernel/trace/trace_wprobe.c +10
-0+ +if (wprobe_data->field) { +if (!rec) +return ; + addr = *(unsigned long *)((char *)rec + wprobe_data->offset); + addr += wprobe_data->adjust; + } + +raw_spin_lock_irqsave (&tw->lock, flags); +[Severity: High]
Could thisraw_spin_lock_irqsave()cause a deadlock if interrupted by an NMI?
Quoted 7 lines
When no count limit is specified (
EVENT_TRIGGER_FL_COUNTis not set),wprobe_trigger()takestw->lockbefore calling__wprobe_count_func().If an NMI interrupts a CPU already holding
tw->lockand hits a trace event that fires the same uncounted trigger, it will attempt to acquiretw->lockagain here. Since thein_nmi()check is located inside__wprobe_count_func(), the NMI would spin forever before realizing it shouldn't proceed.
Ah, indeed. It should check in_nmi() earlier than the spin lock.
Quoted 12 lines
kernel/trace/trace_wprobe.c static int trace_wprobe_show(struct seq_file *m, struct dyn_event *ev) · line 1046
Quoted 7 lines
kernel/trace/trace_wprobe.c +6
-0+if (!(data->flags &EVENT_TRIGGER_FL_COUNT )) { +if (!__wprobe_count_func (data, addr)) { +atomic_inc (&tw->missed); + goto out; + } + }[Severity: Medium]
Is there a time-of-check to time-of-use (TOCTOU) race here for counted triggers?
Quoted 8 lines
For counted triggers,
wprobe_count_func()is called locklessly by the trace core, which evaluates__wprobe_count_func(). Then,wprobe_trigger()is called and takestw->lock. BecauseEVENT_TRIGGER_FL_COUNTis set, the state validation check (__wprobe_count_func()) is explicitly skipped under the lock.If a counted trigger fires concurrently on multiple CPUs, both might observe the unset address locklessly. Could the second CPU unconditionally overwrite
tw->addr, breaking the exclusive trigger constraint?
Hmm, indeed. I think the current event trigger subsystem is not well designed for the concurrency. Let me move the data->count update to wprobe_trigger() inside tw->lock critical region.
Thank you,
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
Masami Hiramatsu (Google)
maintainerPATCH v17 11/13 selftests: tracing: Add wprobe trigger testcases
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
Add testcases for checking wprobe triggers. This sets set_wprobe and clear_wprobe triggers on fprobe event and static trace event to monitor memory accesses within the trace-events-sample kernel module. Also add a testcase for verifying wprobe triggers across CPU hotplug, and a testcase for verifying wprobe trigger syntax error logging.
---
Changes in v17:
- Add trigger-wprobe-hotplug.tc to verify wprobe triggers across CPU offline and online transitions.
Changes in v15:
- Add explicit failure checks with fail helper in trigger-wprobe.tc.
- Declare fprobe README requirement in trigger-wprobe.tc.
- Add trigger file check to trigger-wprobe-syntax-errors.tc requires line.
- Fix subject tag to tracing.
Changes in v14:
- Update dummy wprobe event definition to use '-1' instead of '0'.
- Add BTF argument dependency requirement in trigger-wprobe.tc.
- Add delay before clear_trace in trigger-wprobe.tc to avoid race with clear_wprobe trigger execution.
Changes in v13:
- Look up target function dynamically in trigger-wprobe-syntax-errors.tc.
- Disable set_wprobe trigger before verifying clear_wprobe in trigger-wprobe.tc to avoid race condition with sample_timer_cb.
Changes in v12:
- Add trigger-wprobe-syntax-errors.tc for verifying wprobe trigger syntax error logging.
- Fix requires line in trigger-wprobe-syntax-errors.tc so test is not evaluated as unsupported prior to execution.
- Define dfd=$arg1 fetcharg on testevent for trigger syntax checks.
Changes in v11:
- Update testcase to use trace-events-sample kernel module instead of VFS file operations.
--- tools/testing/selftests/ftrace/config | 1 .../test.d/trigger/trigger-wprobe-hotplug.tc | 150 ++++++++++++++++++++ .../test.d/trigger/trigger-wprobe-syntax-errors.tc | 37 +++++ .../ftrace/test.d/trigger/trigger-wprobe.tc | 107 ++++++++++++++ 4 files changed, 295 insertions(+) create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-syntax-errors.tc create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe.tc
tools/testing/selftests/ftrace/config +1 -0
@@ -28,3 +28,4 @@ CONFIG_TRACER_SNAPSHOT=y CONFIG_UPROBES=y CONFIG_UPROBE_EVENTS=y CONFIG_WPROBE_EVENTS=y +CONFIG_WPROBE_TRIGGERS=y
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc new file +150 -0
150 lines not on this page · raw message
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-syntax-errors.tc new file +37 -0
@@ -0,0 +1,37 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# description: event trigger - test wprobe trigger syntax errors +# requires: dynamic_events error_log "w[:[<group>/][<event>]] [r|w|rw]@<addr>[:<len>]":README "f[:[<group>/][<event>]] <func-name>[%return] [<args>]":README events/sched/sched_process_fork/trigger + +check_error() { # command-with-error-pos-by-^ + ftrace_errlog_check "wprobe_trigger" "$1" "events/fprobes/testevent/trigger" +} + +TARGET_FUNC=$(grep -m 1 -E -w "[tT] (vfs_read|do_sys_openat2|do_sys_open)" /proc/kallsyms | awk '{print $3}') +if [ -z "$TARGET_FUNC" ]; then + echo "UNRESOLVED: target function not found" + exit_unresolved +fi + +# Add a dummy fprobe event to attach triggers to +echo "f:fprobes/testevent $TARGET_FUNC dfd=\$arg1" > dynamic_events + +# Add a target wprobe event +echo 'w:watch rw@-1:8' >> dynamic_events + +# Test errors on trigger syntax +check_error 'set_wprobe:^non_exist_wprobe:dfd' # WPROBE_NOT_FOUND +check_error 'set_wprobe:^' # WPROBE_NOT_FOUND +check_error 'set_wprobe:watch^' # WPROBE_NEED_FIELD +check_error 'set_wprobe:watch:^non_exist_field' # NO_EVENT_FIELD + +# Enable target wprobe event and test WPROBE_BUSY error +echo 1 > events/wprobes/watch/enable +check_error 'set_wprobe:^watch:dfd' # WPROBE_BUSY +echo 0 > events/wprobes/watch/enable + +# Cleanup +echo '-:watch' >> dynamic_events +echo '-:testevent' >> dynamic_events + +exit 0
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe.tc new file +107 -0
107 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v17 11/13] selftests: tracing: Add wprobe trigger testcases
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider: - [Low] kselftest: trace buffer not cleared before verifying offline wprobe triggers - [Low] kselftest…
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Low] kselftest: trace buffer not cleared before verifying offline wprobe triggers
- [Low] kselftest: missing set_wprobe dependency check in requires lines
--
commit 0d531760cdf15ae449a5bc0545ea39a43134b990
Author: Masami Hiramatsu (Google) <[email protected]>
selftests: tracing: Add wprobe trigger testcases
This commit adds several test scripts for wprobe triggers in the ftrace selftests. The test scripts verify setting and clearing wprobe triggers, CPU hotplug behavior for wprobes, and syntax error logging.
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc line 4
Quoted 8 lines
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc new file +4
-0@@ -0,0 +1,150 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# description: event trigger - test wprobe trigger across cpu hotplug +# requires: dynamic_events "w[:[<group>/][<event>]] [r|w|rw]@<addr>[:<len>]":README "f[:[<group>/][<event>]] <func-name>[%return] [<args>]":README events/sched/sched_process_fork/trigger "[(structname[,field])]<argname>[->field[->field|.field...]]":README
[Severity: Low]
Should we check for set_wprobe in the README in this requires line? If a kernel has CONFIG_WPROBE_EVENTS=y but CONFIG_WPROBE_TRIGGERS=n, it seems this test will execute and fail unexpectedly with "Failed to set set_wprobe trigger" instead of being gracefully skipped as UNRESOLVED.
[ ... ]
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc line 100
Quoted 11 lines
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc new file +11
-0+:;: "Take target CPU offline" ;: +echo 0 > $cpu/online +sleep 1 + +# Wait for sample_timer_cb to fire and set_wprobe trigger to activate while CPU is offline +sleep 2 + +:;: "Check set_wprobe trigger activated the watchpoint" ;: +if ! grep -q watch trace; then + fail "Failed to trigger watchpoint while CPU is offline" +fi
[Severity: Low]
Does this grep falsely match events generated while the CPU was still online? Because the target fprobe (sample_timer_cb) fires continuously, the trace buffer could log a watch event before the offlining process actually completes. Should we add a clear_trace call either before or right after taking the CPU offline?
[ ... ]
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-syntax-errors.tc line 4
Quoted 8 lines
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-syntax-errors.tc new file +4
-0@@ -0,0 +1,37 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# description: event trigger - test wprobe trigger syntax errors +# requires: dynamic_events error_log "w[:[<group>/][<event>]] [r|w|rw]@<addr>[:<len>]":README "f[:[<group>/][<event>]] <func-name>[%return] [<args>]":README events/sched/sched_process_fork/trigger
[Severity: Low]
Similar to the hotplug script, does this requires line need a set_wprobe README check to prevent false test failures on kernels that lack wprobe trigger support?
[ ... ]
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe.tc line 4
Quoted 8 lines
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe.tc new file +4
-0@@ -0,0 +1,107 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# description: event trigger - test wprobe trigger +# requires: dynamic_events "w[:[<group>/][<event>]] [r|w|rw]@<addr>[:<len>]":README "f[:[<group>/][<event>]] <func-name>[%return] [<args>]":README events/sched/sched_process_fork/trigger "[(structname[,field])]<argname>[->field[->field|.field...]]":README
[Severity: Low]
Does this requires line also need the set_wprobe dependency check to ensure the feature is fully supported before execution?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=11
Masami Hiramatsu (Google)
maintainerRe: [PATCH v17 11/13] selftests: tracing: Add wprobe trigger testcases
Quoted 16 lines · On Tue, 22 Sep 2026 04:41:53 +0000 [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:
- [Low] kselftest: trace buffer not cleared before verifying offline wprobe triggers
- [Low] kselftest: missingset_wprobedependency check in requires lines
--commit
0d531760cdf15ae449a5bc0545ea39a43134b990
Author: Masami Hiramatsu (Google) <[email protected]>selftests: tracing: Add wprobe trigger testcases
This commit adds several test scripts for wprobe triggers in the ftrace selftests. The test scripts verify setting and clearing wprobe triggers, CPU hotplug behavior for wprobes, and syntax error logging.
Quoted 14 lines
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc line 4
Quoted 8 lines
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc new file +4
-0@@ -0,0 +1,150 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0 +# description: event trigger - test wprobe trigger across cpu hotplug +# requires: dynamic_events "w[:[<group>/][<event>]] [r|w|rw]@<addr>[:<len>]":README "f[:[<group>/][<event>]] <func-name>[%return] [<args>]":README events/sched/sched_process_fork/trigger "[(structname[,field])]<argname>[->field[->field|.field...]]":README[Severity: Low]
Should we check forset_wprobein the README in this requires line? If a kernel hasCONFIG_WPROBE_EVENTS=ybutCONFIG_WPROBE_TRIGGERS=n, it seems this test will execute and fail unexpectedly with "Failed to setset_wprobetrigger" instead of being gracefully skipped as UNRESOLVED.
Ah, good catch! OK, let me add that in the requires line.
Quoted 13 lines
[ ... ]
Quoted 10 lines
+:;: "Take target CPU offline" ;:
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-hotplug.tc new file +9
-0+echo 0 > $cpu/online +sleep 1 + +# Wait for sample_timer_cb to fire and set_wprobe trigger to activate while CPU is offline +sleep 2 + +:;: "Check set_wprobe trigger activated the watchpoint" ;: +if ! grep -q watch trace; then + fail "Failed to trigger watchpoint while CPU is offline"
Quoted 8 lines
Quoted 1 line
+fi
[Severity: Low]
Does this grep falsely match events generated while the CPU was still online? Because the target fprobe (sample_timer_cb) fires continuously, the trace buffer could log a watch event before the offlining process actually completes. Should we add aclear_tracecall either before or right after taking the CPU offline?
OK, let me add it.
Thanks!
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
Masami Hiramatsu (Google)
maintainerPATCH v17 12/13 tracing/wprobe: Support BTF typecast in fetchargs
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
Allow BTF typecast syntax (STRUCT)FETCHARG->MEMBER in wprobe event fetchargs. Previously, handle_typecast() rejected any probe context that was not a function entry/return or tracepoint event probe.
Wprobe events use $addr (the accessed address) and $value (the value at that address). By enabling BTF typecast, users can now cast these to a concrete struct type and access its fields directly. For example:
echo 'w:watch rw@-1:8 dflag=(dentry)$addr->d_flags' >> dynamic_events
With a set_wprobe trigger pointing the watchpoint at a dentry address, the resulting trace shows d_flags being accessed at that location.
Note that $addr and $value are restricted to kernel-space memory, which is consistent with the existing TPARG_FL_KERNEL flag used when parsing wprobe fetchargs.
---
Changes in v15:
- Document BTF typecast syntax for wprobe fetchargs in wprobetrace.rst.
- Add explicit failure checks with fail helper in trigger-wprobe-btf-typecast.tc.
- Declare fprobe README requirement in trigger-wprobe-btf-typecast.tc.
Changes in v14:
- Update dummy wprobe event definition to use '-1' instead of '0'.
Changes in v11:
- Update trigger-wprobe-btf-typecast.tc to use trace-events-sample kernel module.
- Fix commit comment.
Changes in v9:
- Newly added.
--- Documentation/trace/wprobetrace.rst | 8 ++ kernel/trace/trace_probe.c | 13 +++ kernel/trace/trace_probe.h | 5 + tools/testing/selftests/ftrace/config | 1 .../test.d/trigger/trigger-wprobe-btf-typecast.tc | 85 ++++++++++++++++++++ 5 files changed, 111 insertions(+), 1 deletion(-) create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-btf-typecast.tc
Documentation/trace/wprobetrace.rst +8 -0
@@ -47,6 +47,14 @@ Synopsis of wprobe-events (u8/u16/u32/u64/s8/s16/s32/s64), hexadecimal types (x8/x16/x32/x64), "char", "string", "ustring", "symbol", "symstr" and bitfield are supported. + (STRUCT[,ASGN])FETCHARG->MEMBER[->MEMBER] : If BTF is supported, typecast + FETCHARG to a pointer to STRUCT and then dereference the + pointer defined by ->MEMBER. ASGN can be specified optionally. + If ASGN is specified, FETCHARG will be cast to the same offset + position as the ASGN member, rather than to the beginning of + the STRUCT. + (STRUCT[,ASGN])(FETCHARG)->MEMBER[->MEMBER] : typecast can nest, so the above + can also be used with another FETCHARG. (\*1) This is useful for fetching a field of data structures. (\*2) "u" means user-space dereference.
kernel/trace/trace_probe.c +12 -1
@@ -890,6 +890,16 @@ static int query_btf_struct(const char *sname, struct traceprobe_parse_context * ctx->struct_btf =NULL ; } +if (ctx->btf) { + id =btf_find_by_name_kind (ctx->btf, sname,BTF_KIND_STRUCT ); +if (id >0 ) { +btf_get (ctx->btf); + ctx->struct_btf = ctx->btf; + ctx->last_struct =btf_type_by_id (ctx->struct_btf, id); +return 0 ; + } + } + id =bpf_find_btf_id (sname,BTF_KIND_STRUCT , &btf);if (id <0 )return id;
@@ -965,7 +975,8 @@ static int handle_typecast(char *arg, struct traceprobe_parse_context *ctx)if (!(tparg_is_event_probe (ctx->flags) ||tparg_is_function_entry (ctx->flags) || -tparg_is_function_return (ctx->flags))) { +tparg_is_function_return (ctx->flags) || +tparg_is_wprobe (ctx->flags))) {trace_probe_log_err (ctx->offset,NOSUP_BTFARG );return -EOPNOTSUPP ; }
kernel/trace/trace_probe.h +5 -0
@@ -439,6 +439,11 @@ static inline bool tparg_is_event_probe(unsigned int flags)return !!(flags &TPARG_FL_TEVENT ); } +static inline bool tparg_is_wprobe (unsigned int flags) +{ +return !!(flags &TPARG_FL_WPROBE ); +} +/* Each typecast consumes nested level. So the max number of typecast is 8. */ #define TRACEPROBE_MAX_NESTED_LEVEL 8
tools/testing/selftests/ftrace/config +1 -0
@@ -1,5 +1,6 @@ CONFIG_BPF_SYSCALL=y CONFIG_DEBUG_INFO_BTF=y +CONFIG_DEBUG_INFO_BTF_MODULES=y CONFIG_DEBUG_INFO_DWARF4=y CONFIG_EPROBE_EVENTS=y CONFIG_FPROBE=y
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-btf-typecast.tc new file +85 -0
85 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v17 12/13] tracing/wprobe: Support BTF typecast in fetchargs
Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 15 lines
From: Masami Hiramatsu (Google) <[email protected]>
Allow BTF typecast syntax (STRUCT)FETCHARG->MEMBER in wprobe event fetchargs. Previously,
handle_typecast()rejected any probe context that was not a function entry/return or tracepoint event probe.Wprobe events use $addr (the accessed address) and $value (the value at that address). By enabling BTF typecast, users can now cast these to a concrete struct type and access its fields directly. For example:
echo 'w:watch rw@-1:8 dflag=(dentry)$addr->d_flags' >>
dynamic_eventsWith a
set_wprobetrigger pointing the watchpoint at a dentry address, the resulting trace showsd_flagsbeing accessed at that location.
Quoted 6 lines
Note that $addr and $value are restricted to kernel-space memory, which is consistent with the existing
TPARG_FL_KERNELflag used when parsing wprobe fetchargs.Assisted-by Antigravity:gemini-3.8-flashSigned-off-by Masami Hiramatsu (Google) <[email protected]>
Sashiko has reviewed this patch and found no issues. It looks great!
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=12
Masami Hiramatsu (Google)
maintainerPATCH v17 13/13 tracing/wprobe: Support BTF struct offset resolution in set_wprobe trigger
In reply to Masami Hiramatsu (Google)From: Masami Hiramatsu (Google) <[email protected]>
Allow set_wprobe trigger to use BTF struct offset resolution to specify the target address field.
---
Changes in v15:
- Duplicate field string to avoid modifying glob in place in wprobe_trigger_typecast_parse() so tracing_log_err() prints pristine command string.
- Remove leftover offset and adjust debug print in wprobe_trigger_print().
- Document BTF struct offset resolution syntax in wprobetrace.rst.
- Add explicit failure checks with fail helper in trigger-wprobe-btf-offset.tc.
- Declare fprobe README requirement in trigger-wprobe-btf-offset.tc.
Changes in v14:
- Update dummy wprobe event definition to use '-1' instead of '0'.
- Pass member_type to btf_find_struct_member() and check its kflag in get_offset_of_field().
Changes in v13:
- Check for field token before calling wprobe_trigger_field_parse() in clear_wprobe to avoid spurious error log entries on numeric counts.
Changes in v12:
- Refactor field parsing logic into wprobe_trigger_field_parse().
- Remove unused variable count_str in wprobe_trigger_cmd_parse().
--- Documentation/trace/wprobetrace.rst | 7 kernel/trace/trace_wprobe.c | 294 +++++++++++++++----- .../test.d/trigger/trigger-wprobe-btf-offset.tc | 85 ++++++ 3 files changed, 308 insertions(+), 78 deletions(-) create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-btf-offset.tc
Documentation/trace/wprobetrace.rst +7 -0
@@ -90,10 +90,17 @@ Combination with trigger action The event trigger action can extend the utilization of this wprobe. - set_wprobe:WPEVENT:FIELD[+|-ADJUST][:COUNT] +- set_wprobe:WPEVENT:(STRUCT[,ASGN])EVENT_FIELD->MEMBER[+|-ADJUST][:COUNT] - clear_wprobe:WPEVENT[:FIELD[+|-ADJUST][:COUNT]] +- clear_wprobe:WPEVENT[:(STRUCT[,ASGN])EVENT_FIELD->MEMBER[+|-ADJUST][:COUNT]] Set these triggers to the target event, then the WPROBE event will be setup to trace the memory access at FIELD[+|-ADJUST] address. +If BTF is supported, the target address can also be resolved using BTF +struct offset resolution: `(STRUCT[,ASGN])EVENT_FIELD->MEMBER[+|-ADJUST]`. +Here, EVENT_FIELD is an event field containing a pointer to STRUCT (or to +the ASGN member if ASGN is specified), and MEMBER is the struct member whose +offset is resolved automatically via BTF. When clear_wprobe is hit, if FIELD is NOT specified, the WPEVENT is forcibly cleared. If FIELD[+|-ADJUST] is set, it clears WPEVENT only if its watching address is the same as the FIELD[+|-ADJUST] value.
kernel/trace/trace_wprobe.c +216 -78
331 lines not on this page · raw message
tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe-btf-offset.tc new file +85 -0
85 lines not on this page · raw message
[email protected]
AI reviewRe: [PATCH v17 13/13] tracing/wprobe: Support BTF struct offset resolution in set_wprobe trigger
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] trace: incorrect BTF kflag check in get_offset_of_field() allows wild offsets --
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] trace: incorrect BTF kflag check in get_offset_of_field() allows wild offsets --
commit 3bc53bf9a42b7270af7bd91985c43e9cafe48496
Author: Masami Hiramatsu (Google) <[email protected]>
tracing/wprobe: Support BTF struct offset resolution in set_wprobe trigger
This commit allows the set_wprobe trigger to use BTF struct offset resolution to specify the target address field.
Quoted 4 lines
kernel/trace/trace_wprobe.c +0
-0
[ ... ]
Quoted 14 lines
kernel/trace/trace_wprobe.c +10
-0@@ -1165,6 +1166,213 @@ static void wprobe_trigger_free(struct event_trigger_data *data) } } +#ifdef CONFIG_PROBE_EVENTS_BTF_ARGS + +static int get_offset_of_field (struct btf *btf,const struct btf_type *type,char *field_name) +{ +const struct btf_member *field; +const struct btf_type *mtype; +int bitoffs =0 ; +u32 anon_offs; +char *next; +
kernel/trace/trace_wprobe.c static void wprobe_trigger_free(struct event_trigger_data *data) · line 1188
Quoted 10 lines
kernel/trace/trace_wprobe.c +10
-0+ do { + next = strchr(field_name, '.'); + if (next) + *next++ = '\0'; + + field = btf_find_struct_member(btf, type, field_name, &anon_offs, &mtype); + if (IS_ERR_OR_NULL(field)) + return -ENOENT; + + if (btf_type_kflag(mtype)) {
[Severity: Medium]
Is it intentional to check btf_type_kflag() on the member type (mtype) instead of the parent struct type (type)?
If the member's kflag is checked instead of the parent struct's kflag, bitfield members can bypass the explicit rejection check and compute wildly incorrect memory offsets. This happens because field->offset contains the bitfield size in the upper 8 bits when the parent struct's kflag is set.
Quoted 7 lines
kernel/trace/trace_wprobe.c +7
-0+/* Reject bitfield member access */ +if (BTF_MEMBER_BITFIELD_SIZE (field->offset)) +return -EINVAL ; + bitoffs += anon_offs +BTF_MEMBER_BIT_OFFSET (field->offset); + }else { + bitoffs += anon_offs + field->offset; + }
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=13
Masami Hiramatsu (Google)
maintainerRe: [PATCH v17 13/13] tracing/wprobe: Support BTF struct offset resolution in set_wprobe trigger
Quoted 41 lines · On Tue, 22 Sep 2026 04:43:30 +0000 [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] trace: incorrect BTF kflag check inget_offset_of_field()allows wild offsets --commit
3bc53bf9a42b7270af7bd91985c43e9cafe48496
Author: Masami Hiramatsu (Google) <[email protected]>tracing/wprobe: Support BTF struct offset resolution in
set_wprobetriggerThis commit allows the
set_wprobetrigger to use BTF struct offset resolution to specify the target address field.Quoted 4 lines
kernel/trace/trace_wprobe.c +0
-0[ ... ]
Quoted 20 lines
kernel/trace/trace_wprobe.c +16
-0@@ -1165,6 +1166,213 @@ static void wprobe_trigger_free(struct event_trigger_data *data) } } +#ifdef CONFIG_PROBE_EVENTS_BTF_ARGS + +static int get_offset_of_field (struct btf *btf,const struct btf_type *type,char *field_name) +{ +const struct btf_member *field; +const struct btf_type *mtype; +int bitoffs =0 ; +u32 anon_offs; +char *next; + + do { + next = strchr(field_name, '.'); + if (next) + *next++ = '\0'; + + field = btf_find_struct_member(btf, type, field_name, &anon_offs, &mtype);
Quoted 8 lines
kernel/trace/trace_wprobe.c static void wprobe_trigger_free(struct event_trigger_data *data) · line 1188
Quoted 4 lines
kernel/trace/trace_wprobe.c +4
-0+if (IS_ERR_OR_NULL (field)) +return -ENOENT ; + +if (btf_type_kflag (mtype)) {[Severity: Medium]
Is it intentional to checkbtf_type_kflag()on the member type (mtype) instead of the parent struct type (type)?
Oops, I thought I had fixed this issue...
Quoted 4 lines
If the member's kflag is checked instead of the parent struct's kflag, bitfield members can bypass the explicit rejection check and compute wildly incorrect memory offsets. This happens because
field->offsetcontains the bitfield size in the upper 8 bits when the parent struct's kflag is set.
Yeah, kflag is the attribute of the parept structure's type.
Thanks,
Quoted 11 lines
Quoted 8 lines
kernel/trace/trace_wprobe.c +7
-0+/* Reject bitfield member access */ +if (BTF_MEMBER_BITFIELD_SIZE (field->offset)) +return -EINVAL ; + bitoffs += anon_offs +BTF_MEMBER_BIT_OFFSET (field->offset); + }else { + bitoffs += anon_offs + field->offset; + }Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/179005108298.388919.4535333252892590932.stgit@devnote2?part=13
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
Masami Hiramatsu (Google)
maintainerRe: [PATCH v17 13/13] tracing/wprobe: Support BTF struct offset resolution in set_wprobe trigger
In reply to [email protected]Quoted 50 lines · On Tue, 22 Sep 2026 04:43:30 +0000 [email protected] wrote:
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] trace: incorrect BTF kflag check inget_offset_of_field()allows wild offsets --commit
3bc53bf9a42b7270af7bd91985c43e9cafe48496
Author: Masami Hiramatsu (Google) <[email protected]>tracing/wprobe: Support BTF struct offset resolution in
set_wprobetriggerThis commit allows the
set_wprobetrigger to use BTF struct offset resolution to specify the target address field.Quoted 4 lines
kernel/trace/trace_wprobe.c +0
-0[ ... ]
Quoted 14 lines
kernel/trace/trace_wprobe.c +10
-0@@ -1165,6 +1166,213 @@ static void wprobe_trigger_free(struct event_trigger_data *data) } } +#ifdef CONFIG_PROBE_EVENTS_BTF_ARGS + +static int get_offset_of_field (struct btf *btf,const struct btf_type *type,char *field_name) +{ +const struct btf_member *field; +const struct btf_type *mtype; +int bitoffs =0 ; +u32 anon_offs; +char *next; +kernel/trace/trace_wprobe.c static void wprobe_trigger_free(struct event_trigger_data *data) · line 1188
Quoted 10 lines
kernel/trace/trace_wprobe.c +10
-0+ do { + next = strchr(field_name, '.'); + if (next) + *next++ = '\0'; + + field = btf_find_struct_member(btf, type, field_name, &anon_offs, &mtype); + if (IS_ERR_OR_NULL(field)) + return -ENOENT; + + if (btf_type_kflag(mtype)) {[Severity: Medium]
Is it intentional to checkbtf_type_kflag()on the member type (mtype) instead of the parent struct type (type)?
Quoted 4 lines
If the member's kflag is checked instead of the parent struct's kflag, bitfield members can bypass the explicit rejection check and compute wildly incorrect memory offsets. This happens because
field->offsetcontains the bitfield size in the upper 8 bits when the parent struct's kflag is set.
Ah, wait. This names "mtype", but the btf_find_struct_member() returns the container type to the mtype. So the naming is not good. See below.
const struct btf_member *btf_find_struct_member(struct btf *btf,
const struct btf_type *type, const char *member_name, u32 *anon_offset, const struct btf_type **member_type)
{
...
if (!btf_type_is_struct(type)) return ERR_PTR(-EINVAL); anon_stack = kzalloc_objs(*anon_stack, BTF_ANON_STACK_MAX); if (!anon_stack) return ERR_PTR(-ENOMEM);
retry:
for_each_member(i, type, member) {
if (!member->name_off) {
...
} else {
name = btf_name_by_offset(btf, member->name_off);
if (name && !strcmp(member_name, name)) {
if (anon_offset)
*anon_offset = cur_offset;
if (member_type)
*member_type = type;
goto out;
}
}
}member_type does not get the actual type of member, but getting the container structure type. (typically, it is @type)
Thanks,
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
We have made a preliminary ARM64 port of the v17 wprobe series and validated the basic paths on a real Android ARM64 device.
The device is:
Kernel: 6.12.69-android16-6-4k
Architecture: arm64
The relevant configuration includes:
CONFIG_HAVE_POST_BREAKPOINT_HOOK=y
CONFIG_HAVE_MODIFY_LOCAL_HW_BREAKPOINT_ADDR=y
CONFIG_WPROBE_EVENTS=y
CONFIG_WPROBE_TRIGGERS=y
The following paths passed on the real device:
- fixed-address read watchpoint;
- fixed-address write watchpoint;
- tracepoint -> set_wprobe;
- dynamic ARM64 watchpoint address update;
- tracepoint -> clear_wprobe;
- no further wprobe records after clear_wprobe.
For the dynamic test, we used the ptr field from the kmem:kmalloc tracepoint:
set_wprobe:dyn_watch_log:ptr:count=1
The trigger changed the ARM64 hardware watchpoint address to the dynamically obtained pointer and generated 6 wprobe access records. We then used a sched_process_exit trigger to execute:
clear_wprobe:dyn_watch_log:count=1
The wprobe state changed from 1* to 0*. The hit count remained 6 after the clear operation, confirming that no additional wprobe records were generated after clearing. No BUG, Oops, panic, or wprobe-related warning was observed during this test.
We also exercised the basic ARM64 watchpoint hit and post-watchpoint single-step path on QEMU. The real-device result is the more important validation.
There are two limitations worth mentioning:
1. The current Android device does not enable CONFIG_FPROBE_EVENTS, so
the fprobe -> set_wprobe path has not been tested on this device.
2. kprobe -> set_wprobe is currently rejected by design. The device reports:
Wprobe trigger is not supported on kprobe event
We understand and respect this restriction, and we are not proposing to remove it in this series.
Our use case for a possible future extension is more specific than monitoring every kmalloc return value. A selected kernel function may call kmalloc() internally, store the returned pointer in a register, stack slot, local variable, or structure field, and then access fields of the newly allocated object. We would like to monitor the object produced by that particular allocation call site, rather than re-arm wprobe for every kmalloc in the system.
One possible design would be a restricted, call-site-specific kprobe-to-wprobe interface:
- a kprobe is placed at a selected instruction offset in the caller;
- a user-space frontend resolves the pointer source from the matching
vmlinux, BTF/DWARF, and disassembly;
- the frontend supplies an explicit register/stack/field fetch;
- the kernel arms a wprobe on the resolved object or one of its fields.
In this model, the user-space frontend would handle symbol resolution, disassembly, call-site selection, pointer-source analysis, structure-field resolution, and tracefs setup. The kernel would not need to parse arbitrary compiler local variables. It would only need to provide a restricted and safe mechanism for consuming an already-resolved pointer and updating the hardware watchpoint.
We are not suggesting that an arbitrary kprobe handler should directly perform unrestricted set_wprobe operations. We understand that kprobes, ARM64 debug exceptions, single-step handling, tracing recursion, and cross-CPU watchpoint updates require a separate safety design.
As an additional limitation, a high-frequency test that repeatedly re-armed the watchpoint from kmem:kmalloc showed a non-zero missed count. The controlled one-shot set/clear test passed, but the high-frequency case needs further investigation.
The complete real-device log and test script are available if useful.
Best regards,
Pengfei