Skip to contentSkip to conversation

tracing: wprobe: x86: Add wprobe for watchpoint

PATCH Superseded Masami Hiramatsu (Google) 3 participants 31 messages Sep 14 – Sep 22

Subsystems (8)
Documentation x86 KVM Kselftest +4 more subsystems

v16 of 21 Superseded Latest is v21 →

lore
Share & tools
lore

Masami Hiramatsu (Google)

author maintainer
#0 lore raw

v16 cover tracing: wprobe: x86: Add wprobe for watchpoint

Hi,

Here is the 16th 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/178875277830.93794.14247844688761142429.stgit@devnote2/

In this version, a new patch is added to prevent host DR7 debug register leaks into KVM guest OSes upon NMI, isolating guest debug state with a dedicated per-CPU flag (cpu_dr_in_guest) and memory barriers. Furthermore, this version addresses reviewer feedback on v15:
- Removed hypervisor check in local_db_save() so all paths go through the sequence retry loop, preventing race windows on return instructions.
- Fixed arch_modify_local_hw_breakpoint_addr() to clear the breakpoint enable bit in shadow cpu_dr7 before touching hardware DR7, preventing intervening NMIs from prematurely re-enabling breakpoints and triggering spurious #DB exceptions.
- Updated wprobe triggers to program local debug registers directly when a trigger fires, eliminating workqueue latency on the local CPU, while kicking irq_work only for other CPUs.
- Corrected "unlimited" count keyword matching in clear_wprobe and removed the non-existent wprobe_events file from readme_msg.

Detailed changes are here.

Changes in v16:
[02/13]
- Newly added to prevent host DR7 debug register leak into guest OS on NMI using a cpu_dr_in_guest per-CPU flag.
[03/13]
- In local_db_save(), remove the hypervisor check so all paths go through the sequence retry loop.
- Check cpu_dr7_seq before clearing hardware DR7 and reload from shadow cpu_dr7 on sequence retry to avoid clobbering NMI breakpoint updates.
- In local_db_restore(), restore from shadow cpu_dr7 whenever cpu_dr7_seq changed instead of evaluating dr7 ? cpu_dr7 : 0.
[04/13]
- Clear breakpoint in shadow cpu_dr7 before setting hardware DR7 in arch_modify_local_hw_breakpoint_addr() to prevent spurious #DB exceptions from intervening NMIs.
- Reject modifying local breakpoints with -EBUSY while cpu_dr_in_guest is set.
[06/13]
- Remove non-existent wprobe_events file description from readme_msg in kernel/trace/trace.c.
[10/13]
- 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" in wprobe_trigger_cmd_parse() to avoid misinterpreting field names starting with "unlimited" as the count keyword.
- Normalize "unlimited" and "count=" parameters before creating trigger data.

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=0xffff888004ad6618

Thank 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
KVM: x86: Prevent host DR7 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 testcase 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                    |   79 +
 arch/x86/include/asm/hw_breakpoint.h               |    2 
 arch/x86/kernel/cpu/mce/core.c                     |   29 
 arch/x86/kernel/hw_breakpoint.c                    |  166 ++
 arch/x86/kernel/nmi.c                              |    7 
 arch/x86/kernel/traps.c                            |   10 
 arch/x86/kvm/x86.c                                 |    7 
 include/linux/hw_breakpoint.h                      |    6 
 include/linux/trace_events.h                       |    3 
 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                        | 1541 ++++++++++++++++++++
 tools/testing/selftests/ftrace/config              |    3 
 .../ftrace/test.d/dynevent/add_remove_wprobe.tc    |   63 +
 .../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-syntax-errors.tc |   37 
 .../ftrace/test.d/trigger/trigger-wprobe.tc        |  107 +
 29 files changed, 2526 insertions(+), 96 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-syntax-errors.tc
 create mode 100644 tools/testing/selftests/ftrace/test.d/trigger/trigger-wprobe.tc

--
Masami Hiramatsu (Google) <[email protected]>

author maintainer
#1 lore raw

PATCH v16 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.

Fixes cd840e424f27 ("x86/entry, mce: Disallow #DB during #MC")
Assisted-by Antigravity:gemini-3.8-flash

---
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
index ab469605fc89..39f238952e14 100644
@@ -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
 
#2 lore raw

Re: [PATCH v16 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() 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.

Quoted 3 lines
Fixes cd840e424f27 ("x86/entry, mce: Disallow #DB during #MC")
Assisted-by Antigravity:gemini-3.8-flash

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=1
author maintainer
#3 lore raw

PATCH v16 2/13 KVM: x86: Prevent host DR7 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 during guest execution, where local_db_save() or arch_install_hw_breakpoint() can be invoked.

In particular, if local_db_save() or arch_install_hw_breakpoint() is executed from NMI, hardware DR7 can be modified or restored with host breakpoint settings, leaking host breakpoints into the guest OS or clobbering the guest's debug registers.

Introduce a per-CPU flag, cpu_dr_in_guest, to indicate that the CPU is executing in guest mode. Set this flag in vcpu_enter_guest() during entering the guest with disabling host breakpoints. If this flag is set, local_db_save() and local_db_restore() return immediately, and arch_install_hw_breakpoint() returns an error. In addition, protect cpu_dr_in_guest in within_cpu_entry() to prevent recursive #DB exceptions.

Fixes f85d40160691 ("KVM: X86: Disable hardware breakpoints unconditionally before kvm_x86->run()")
Assisted-by Antigravity:gemini-3.8-flash

---
Changes in v16:
- Newly added.

---
 arch/x86/include/asm/debugreg.h |    6 ++++++
 arch/x86/kernel/hw_breakpoint.c |   10 ++++++++++
 arch/x86/kvm/x86.c              |    7 +++++++
 3 files changed, 23 insertions(+)
arch/x86/include/asm/debugreg.h +6 -0
index 854d82b88ff4..50f830972698 100644
@@ -18,6 +18,7 @@
 #define DR7_FIXED_1	0x00000400
 
 DECLARE_PER_CPU(unsigned long, cpu_dr7);
+DECLARE_PER_CPU(bool, cpu_dr_in_guest);
 
 #ifndef CONFIG_PARAVIRT_XXL
 /*
@@ -129,6 +130,9 @@ static __always_inline unsigned long local_db_save(void)
 {
 	unsigned long dr7;
 
+	if (this_cpu_read(cpu_dr_in_guest))
+		return 0;
+
 	if (cpu_feature_enabled(X86_FEATURE_HYPERVISOR) && !hw_breakpoint_active())
 		return 0;
 
@@ -157,6 +161,8 @@ static __always_inline void local_db_restore(unsigned long dr7)
 	 * not be good.
 	 */
 	barrier();
+	if (this_cpu_read(cpu_dr_in_guest))
+		return;
 	if (dr7)
 		set_debugreg(dr7, 7);
 }
arch/x86/kernel/hw_breakpoint.c +10 -0
index f846c15f21ca..68de7ed79d88 100644
@@ -40,6 +40,9 @@
 DEFINE_PER_CPU(unsigned long, cpu_dr7);
 EXPORT_PER_CPU_SYMBOL(cpu_dr7);
 
+DEFINE_PER_CPU(bool, cpu_dr_in_guest);
+EXPORT_PER_CPU_SYMBOL_GPL(cpu_dr_in_guest);
+
 /* Per cpu debug address registers values */
 static DEFINE_PER_CPU(unsigned long, cpu_debugreg[HBP_NUM]);
 
@@ -102,6 +105,9 @@ int arch_install_hw_breakpoint(struct perf_event *bp)
 
 	lockdep_assert_irqs_disabled();
 
+	if (this_cpu_read(cpu_dr_in_guest))
+		return -EBUSY;
+
 	for (i = 0; i < HBP_NUM; i++) {
 		struct perf_event **slot = this_cpu_ptr(&bp_per_reg[i]);
 
@@ -316,6 +322,10 @@ static inline bool within_cpu_entry(unsigned long addr, unsigned long end)
 		if (within_area(addr, end, (unsigned long)&per_cpu(cpu_dr7, cpu),
 				sizeof(cpu_dr7)))
 			return true;
+		if (within_area(addr, end,
+				(unsigned long)&per_cpu(cpu_dr_in_guest, cpu),
+				sizeof(cpu_dr_in_guest)))
+			return true;
 	}
 
 	return false;
arch/x86/kvm/x86.c +7 -0
index 79468ddfe473..5e046924ab76 100644
@@ -8318,6 +8318,9 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 
 	kvm_load_xfeatures(vcpu, true);
 
+	this_cpu_write(cpu_dr_in_guest, true);
+	barrier();
+
 	if (unlikely(vcpu->arch.switch_db_regs &&
 		     !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
 		set_debugreg(DR7_FIXED_1, 7);
@@ -8400,6 +8403,10 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu)
 		kvm_update_dr7(vcpu);
 	}
 
+	barrier();
+	this_cpu_write(cpu_dr_in_guest, false);
+	barrier();
+
 	/*
 	 * If the guest has used debug registers, at least dr7
 	 * will be disabled while returning to the host.
#4 lore raw

Re: [PATCH v16 02/13] KVM: x86: Prevent host DR7 debug register leak into guest OS on NMI

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 20 lines

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 during guest execution, where local_db_save() or arch_install_hw_breakpoint() can be invoked.

In particular, if local_db_save() or arch_install_hw_breakpoint() is executed from NMI, hardware DR7 can be modified or restored with host breakpoint settings, leaking host breakpoints into the guest OS or clobbering the guest's debug registers.

Introduce a per-CPU flag, cpu_dr_in_guest, to indicate that the CPU is executing in guest mode. Set this flag in vcpu_enter_guest() during entering the guest with disabling host breakpoints. If this flag is set, local_db_save() and local_db_restore() return immediately, and arch_install_hw_breakpoint() returns an error. In addition, protect cpu_dr_in_guest in within_cpu_entry() to prevent recursive #DB exceptions.

Quoted 3 lines
Fixes f85d40160691 ("KVM: X86: Disable hardware breakpoints unconditionally before kvm_x86->run()")
Assisted-by Antigravity:gemini-3.8-flash

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=2
#5 lore raw

Re: [PATCH v16 02/13] KVM: x86: Prevent host DR7 debug register leak into guest OS on NMI

In reply to Masami Hiramatsu (Google)
Quoted 11 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 during guest execution, where local_db_save() or arch_install_hw_breakpoint() can be invoked.

In particular, if local_db_save() or arch_install_hw_breakpoint() is executed from NMI, hardware DR7 can be modified or restored with host breakpoint settings, leaking host breakpoints into the guest OS or clobbering the guest's debug registers.

Not for local_db_save(), at least not AFAICT. On VM-Exit, both Intel and AMD purge DR7, i.e. load 0x400, so local_db_save() => local_db_restore() is more or less a nop. Even if that weren't the case, actually saving/restoring DR7 would be the right thing to do, in any context.

Quoted 33 lines

Introduce a per-CPU flag, cpu_dr_in_guest, to indicate that the CPU is executing in guest mode. Set this flag in vcpu_enter_guest() during entering the guest with disabling host breakpoints. If this flag is set, local_db_save() and local_db_restore() return immediately, and arch_install_hw_breakpoint() returns an error. In addition, protect cpu_dr_in_guest in within_cpu_entry() to prevent recursive #DB exceptions.

Fixes f85d40160691 ("KVM: X86: Disable hardware breakpoints unconditionally before kvm_x86->run()")
Assisted-by Antigravity:gemini-3.8-flash

---
Changes in v16:
- Newly added.

---
 arch/x86/include/asm/debugreg.h |    6 ++++++
 arch/x86/kernel/hw_breakpoint.c |   10 ++++++++++
 arch/x86/kvm/x86.c              |    7 +++++++
 3 files changed, 23 insertions(+)
arch/x86/include/asm/debugreg.h +1 -0
index 854d82b88ff4..50f830972698 100644
@@ -18,6 +18,7 @@
 #define DR7_FIXED_1	0x00000400
 
 DECLARE_PER_CPU(unsigned long, cpu_dr7);
+DECLARE_PER_CPU(bool, cpu_dr_in_guest);
 
 #ifndef CONFIG_PARAVIRT_XXL
 /*

arch/x86/include/asm/debugreg.h static __always_inline unsigned long local_db_save(void) · line 134

Quoted 5 lines
arch/x86/include/asm/debugreg.h +2 -0
@@ -129,6 +130,9 @@ static __always_inline unsigned long local_db_save(void)
 {
 	unsigned long dr7;
 
+	if (this_cpu_read(cpu_dr_in_guest))
+		return 0;

This is broken. If an NMI hits between KVM writing cpu_dr_in_guest and clearing DR7, and there are active breakpoints, then local_db_save() won't disable breakpoints as it should, and the relevant code in exc_nmi() will run with breakpoints enabled.

	kvm_load_xfeatures(vcpu, true);

	this_cpu_write(cpu_dr_in_guest, true);
	barrier();

<NMI here is problematic>

	if (unlikely(vcpu->arch.switch_db_regs &&
		     !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
		set_debugreg(DR7_FIXED_1, 7);
		set_debugreg(vcpu->arch.eff_db[0], 0);
Quoted 28 lines
arch/x86/include/asm/debugreg.h +3 -0
+
 	if (cpu_feature_enabled(X86_FEATURE_HYPERVISOR) && !hw_breakpoint_active())
 		return 0;
 
@@ -157,6 +161,8 @@ static __always_inline void local_db_restore(unsigned long dr7)
 	 * not be good.
 	 */
 	barrier();
+	if (this_cpu_read(cpu_dr_in_guest))
+		return;
 	if (dr7)
 		set_debugreg(dr7, 7);
 }
arch/x86/kernel/hw_breakpoint.c +3 -0
index f846c15f21ca..68de7ed79d88 100644
@@ -40,6 +40,9 @@
 DEFINE_PER_CPU(unsigned long, cpu_dr7);
 EXPORT_PER_CPU_SYMBOL(cpu_dr7);
 
+DEFINE_PER_CPU(bool, cpu_dr_in_guest);
+EXPORT_PER_CPU_SYMBOL_GPL(cpu_dr_in_guest);
+
 /* Per cpu debug address registers values */
 static DEFINE_PER_CPU(unsigned long, cpu_debugreg[HBP_NUM]);
 

arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 109

Quoted 5 lines
arch/x86/kernel/hw_breakpoint.c +2 -0
@@ -102,6 +105,9 @@ int arch_install_hw_breakpoint(struct perf_event *bp)
 
 	lockdep_assert_irqs_disabled();
 
+	if (this_cpu_read(cpu_dr_in_guest))
+		return -EBUSY;

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:

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

author maintainer
#6 lore raw

Re: [PATCH v16 02/13] KVM: x86: Prevent host DR7 debug register leak into guest OS on NMI

Hi Sean,

Thanks for your review!

Quoted 13 lines · On Mon, 14 Sep 2026 07:35:48 -0700 Sean Christopherson <[email protected]>…
Quoted 11 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 during guest execution, where local_db_save() or arch_install_hw_breakpoint() can be invoked.

In particular, if local_db_save() or arch_install_hw_breakpoint() is executed from NMI, hardware DR7 can be modified or restored with host breakpoint settings, leaking host breakpoints into the guest OS or clobbering the guest's debug registers.

Quoted 4 lines

Not for local_db_save(), at least not AFAICT. On VM-Exit, both Intel and AMD purge DR7, i.e. load 0x400, so local_db_save() => local_db_restore() is more or less a nop. Even if that weren't the case, actually saving/restoring DR7 would be the right thing to do, in any context.

OK.

Quoted 49 lines
Quoted 34 lines

Introduce a per-CPU flag, cpu_dr_in_guest, to indicate that the CPU is executing in guest mode. Set this flag in vcpu_enter_guest() during entering the guest with disabling host breakpoints. If this flag is set, local_db_save() and local_db_restore() return immediately, and arch_install_hw_breakpoint() returns an error. In addition, protect cpu_dr_in_guest in within_cpu_entry() to prevent recursive #DB exceptions.

Fixes f85d40160691 ("KVM: X86: Disable hardware breakpoints unconditionally before kvm_x86->run()")
Assisted-by Antigravity:gemini-3.8-flash

---
Changes in v16:
- Newly added.

---
 arch/x86/include/asm/debugreg.h |    6 ++++++
 arch/x86/kernel/hw_breakpoint.c |   10 ++++++++++
 arch/x86/kvm/x86.c              |    7 +++++++
 3 files changed, 23 insertions(+)
arch/x86/include/asm/debugreg.h +1 -0
index 854d82b88ff4..50f830972698 100644
@@ -18,6 +18,7 @@
 #define DR7_FIXED_1	0x00000400
 
 DECLARE_PER_CPU(unsigned long, cpu_dr7);
+DECLARE_PER_CPU(bool, cpu_dr_in_guest);
 
 #ifndef CONFIG_PARAVIRT_XXL
 /*

arch/x86/include/asm/debugreg.h static __always_inline unsigned long local_db_save(void) · line 134

Quoted 5 lines
arch/x86/include/asm/debugreg.h +2 -0
@@ -129,6 +130,9 @@ static __always_inline unsigned long local_db_save(void)
 {
 	unsigned long dr7;
 
+	if (this_cpu_read(cpu_dr_in_guest))
+		return 0;

This is broken. If an NMI hits between KVM writing cpu_dr_in_guest and clearing DR7, and there are active breakpoints, then local_db_save() won't disable breakpoints as it should, and the relevant code in exc_nmi() will run with breakpoints enabled.

	kvm_load_xfeatures(vcpu, true);

	this_cpu_write(cpu_dr_in_guest, true);
	barrier();
Quoted 6 lines

<NMI here is problematic>

	if (unlikely(vcpu->arch.switch_db_regs &&
		     !(vcpu->arch.switch_db_regs & KVM_DEBUGREG_AUTO_SWITCH))) {
		set_debugreg(DR7_FIXED_1, 7);
		set_debugreg(vcpu->arch.eff_db[0], 0);

Oops, indeed! OK, so local_db_save/restore will just work as it is, but modifying DR7 should directly be prohibited.

Quoted 40 lines
Quoted 29 lines
arch/x86/include/asm/debugreg.h +3 -0
+
 	if (cpu_feature_enabled(X86_FEATURE_HYPERVISOR) && !hw_breakpoint_active())
 		return 0;
 
@@ -157,6 +161,8 @@ static __always_inline void local_db_restore(unsigned long dr7)
 	 * not be good.
 	 */
 	barrier();
+	if (this_cpu_read(cpu_dr_in_guest))
+		return;
 	if (dr7)
 		set_debugreg(dr7, 7);
 }
arch/x86/kernel/hw_breakpoint.c +3 -0
index f846c15f21ca..68de7ed79d88 100644
@@ -40,6 +40,9 @@
 DEFINE_PER_CPU(unsigned long, cpu_dr7);
 EXPORT_PER_CPU_SYMBOL(cpu_dr7);
 
+DEFINE_PER_CPU(bool, cpu_dr_in_guest);
+EXPORT_PER_CPU_SYMBOL_GPL(cpu_dr_in_guest);
+
 /* Per cpu debug address registers values */
 static DEFINE_PER_CPU(unsigned long, cpu_debugreg[HBP_NUM]);
 

arch/x86/kernel/hw_breakpoint.c int arch_install_hw_breakpoint(struct perf_event *bp) · line 109

Quoted 5 lines
arch/x86/kernel/hw_breakpoint.c +2 -0
@@ -102,6 +105,9 @@ int arch_install_hw_breakpoint(struct perf_event *bp)
 
 	lockdep_assert_irqs_disabled();
 
+	if (this_cpu_read(cpu_dr_in_guest))
+		return -EBUSY;

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 1 line

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

OK, so introducing a new (someting like) cpu_in_trans_guest flag and check it from all affected places?

Thank you,

Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
author maintainer
#7 lore raw

PATCH v16 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.

Assisted-by Antigravity:gemini-3.8-flash

---
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 |   77 ++++++++++++++++++++++--------
 arch/x86/kernel/cpu/mce/core.c  |   10 ++--
 arch/x86/kernel/hw_breakpoint.c |  101 ++++++++++++++++++++-------------------
 arch/x86/kernel/nmi.c           |    7 ++-
 arch/x86/kernel/traps.c         |   10 +++-
 5 files changed, 124 insertions(+), 81 deletions(-)
arch/x86/include/asm/debugreg.h +56 -21
index 50f830972698..ac1607eeefb7 100644
@@ -19,6 +19,7 @@
 
 DECLARE_PER_CPU(unsigned long, cpu_dr7);
 DECLARE_PER_CPU(bool, cpu_dr_in_guest);
+DECLARE_PER_CPU(unsigned int, cpu_dr7_seq);
 
 #ifndef CONFIG_PARAVIRT_XXL
 /*
@@ -126,45 +127,79 @@ 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 (this_cpu_read(cpu_dr_in_guest))
-		return 0;
+	if (this_cpu_read(cpu_dr_in_guest)) {
+		*dr7 = 0;
+		*dr7_seq = 0;
+		return;
+	}
 
-	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;
+		}
 
-	return dr7;
+		/* Outer loop: clear DR7 and retry if sequence number is updated. */
+		if (*dr7)
+			set_debugreg(DR7_FIXED_1, 7);
+
+		/*
+		 * 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 (this_cpu_read(cpu_dr_in_guest))
 		return;
-	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
index 39f238952e14..b3669d6f88d4 100644
@@ -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 +51 -50

160 lines not on this page · raw message

arch/x86/kernel/nmi.c +4 -3
index 3c9f60d6ca5a..c3806f7bd3e8 100644
@@ -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
index 30aa8369957e..018abe736285 100644
@@ -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)
#8 lore raw

Re: [PATCH v16 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_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.

Quoted 5 lines
Assisted-by Antigravity:gemini-3.8-flash

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=3
author maintainer
#9 lore raw

PATCH v16 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.

Assisted-by Antigravity:gemini-3.8-flash

---
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
index 0bc931cd0698..f35ec491f6dd 100644
@@ -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

#10 lore raw

Re: [PATCH v16 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 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.

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-flash

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=4
author maintainer
#11 lore raw

PATCH v16 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.

Assisted-by Antigravity:gemini-3.8-flash

---
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
index 45c657772362..d021bc31ef14 100644
@@ -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
index 15fd9ec5ecac..38e29e465022 100644
@@ -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
index db199d653dd1..bf65c7fffd99 100644
@@ -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

#12 lore raw

Re: [PATCH v16 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 selects CONFIG_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-flash

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=5
author maintainer
#13 lore raw

PATCH v16 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.

Assisted-by Antigravity:gemini-3.8-flash

---
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
index f4058e8e92e3..4f3fa60e4ecd 100644
@@ -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
index 5cbd09c8be8d..43ffd9a76d88 100644
@@ -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
index 0ab5916575a9..b58c2565024f 100644
@@ -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
index f934ff586bd4..141c8323de20 100644
@@ -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
index a946e0183fd1..da85e2568c41 100644
@@ -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
index 74a7a50d1e78..18588c550a98 100644
@@ -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		1024
 
 struct trace_array;
kernel/trace/trace_probe.c +19 -2
index 804442b2f7d2..64e7e363e8e2 100644
@@ -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
index d1fb3520700f..f20cafb87cc6 100644
@@ -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

#14 lore raw

Re: [PATCH v16 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-flash

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=6
author maintainer
#15 lore raw

PATCH v16 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
index d021bc31ef14..5292bd05d5d4 100644
@@ -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
index 38e29e465022..e4eaf0b607d3 100644
@@ -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
index b58c2565024f..d9b6fa5c35d9 100644
@@ -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
#16 lore raw

Re: [PATCH v16 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_HOOK which indicates the hw_breakpoint on that architecture fires after the target memory has been modified. This is currently x86 only behavior.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=7
author maintainer
#17 lore raw

PATCH v16 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 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    |   63 ++++++++++++++++++++
 2 files changed, 64 insertions(+)
 create mode 100644 tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc
tools/testing/selftests/ftrace/config +1 -0
index 544de0db5f58..d2f503722020 100644
@@ -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 +63 -0

63 lines not on this page · raw message

#18 lore raw

Re: [PATCH v16 08/13] selftests: tracing: Add a basic testcase for wprobe

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] Unhandled error from `echo 1 > enable` causes false test failure under `set -e` when hardware…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Unhandled error from echo 1 > enable causes false test failure under set -e when hardware watchpoints are unsupported. --

commit 70eb02867fbc0203498e0161a5c4b437b562d025
Author: Masami Hiramatsu (Google) <[email protected]>

selftests: tracing: Add a basic testcase for wprobe

Add 'add_remove_wprobe.tc' testcase for testing wprobe event that tests adding and removing operations of the wprobe event.

Quoted 5 lines
tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc new file +0 -0
new file mode 100644
index 0000000000000..647c37d5e4c84

[ ... ]

tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc line 24

Quoted 6 lines
tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc new file +6 -0
+if [ ! -d events/wprobes/my_wprobe ]; then
+    echo "Failed to create wprobe event directory"
+    exit_fail
+fi
+
+echo 1 > events/wprobes/my_wprobe/enable

[Severity: Medium]
Will this script falsely report a failure if hardware watchpoints are exhausted or unsupported on the platform?

Writing to the enable file triggers enable_trace_wprobe() and eventually register_wide_hw_breakpoint(), which allocates physical hardware debug registers. If this allocation fails (e.g., returning -ENOSPC or -EOPNOTSUPP), the echo command will return a non-zero exit status.

Because ftracetest runs test scripts with 'set -e' (errexit) active, this error will abort the script immediately and fail the test instead of safely skipping it.

Should this write be guarded with something like "|| exit_unsupported" to handle expected hardware limitations?

Quoted 6 lines
tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc new file +6 -0
+
+# Check if the event is enabled
+if ! grep -q 1 events/wprobes/my_wprobe/enable; then
+    echo "Failed to enable wprobe event"
+    exit_fail
+fi
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=8
author maintainer
#19 lore raw

Re: [PATCH v16 08/13] selftests: tracing: Add a basic testcase for wprobe

Quoted 36 lines · On Mon, 14 Sep 2026 14:30:11 +0000 [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] Unhandled error from echo 1 > enable causes false test failure under set -e when hardware watchpoints are unsupported. --

commit 70eb02867fbc0203498e0161a5c4b437b562d025
Author: Masami Hiramatsu (Google) <[email protected]>

selftests: tracing: Add a basic testcase for wprobe

Add 'add_remove_wprobe.tc' testcase for testing wprobe event that tests adding and removing operations of the wprobe event.

Quoted 5 lines
tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc new file +0 -0
new file mode 100644
index 0000000000000..647c37d5e4c84

[ ... ]

tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc line 24

Quoted 6 lines
tools/testing/selftests/ftrace/test.d/dynevent/add_remove_wprobe.tc new file +6 -0
+if [ ! -d events/wprobes/my_wprobe ]; then
+    echo "Failed to create wprobe event directory"
+    exit_fail
+fi
+
+echo 1 > events/wprobes/my_wprobe/enable

[Severity: Medium]
Will this script falsely report a failure if hardware watchpoints are exhausted or unsupported on the platform?

Writing to the enable file triggers enable_trace_wprobe() and eventually register_wide_hw_breakpoint(), which allocates physical hardware debug registers. If this allocation fails (e.g., returning -ENOSPC or -EOPNOTSUPP), the echo command will return a non-zero exit status.

Quoted 6 lines

Because ftracetest runs test scripts with 'set -e' (errexit) active, this error will abort the script immediately and fail the test instead of safely skipping it.

Should this write be guarded with something like "|| exit_unsupported" to handle expected hardware limitations?

Hmm, this is not unsupported, but unresolved (environmental test failure case).

Thanks,

Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
author maintainer
#20 lore raw

PATCH v16 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
new file mode 100644
index 000000000000..e0df58fe7aa3
@@ -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
#21 lore raw

Re: [PATCH v16 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.

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=9
author maintainer
#22 lore raw

PATCH v16 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.

Assisted-by Antigravity:gemini-3.8-flash

---
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         |  628 +++++++++++++++++++++++++++++++++++
 9 files changed, 761 insertions(+), 3 deletions(-)
Documentation/trace/wprobetrace.rst +107 -0
index 31cc68b464e9..df8985283312 100644
@@ -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
index 43ffd9a76d88..f81a5308c116 100644
@@ -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
index d9b6fa5c35d9..5fd8ed63c516 100644
@@ -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
index da85e2568c41..61d7d8bfb157 100644
@@ -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
index 18588c550a98..a61f840b18bd 100644
@@ -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
index 149300cc5e8a..120e6ec634b7 100644
@@ -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
index 64e7e363e8e2..77266e042418 100644
@@ -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
index f20cafb87cc6..1e11077ead67 100644
@@ -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 +628 -0

694 lines not on this page · raw message

#23 lore raw

Re: [PATCH v16 10/13] tracing/wprobe: Add set_wprobe and clear_wprobe event triggers

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [High] Missing RCU synchronization in the error path of wprobe trigger registration leads to a…

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Missing RCU synchronization in the error path of wprobe trigger registration leads to a Use-After-Free of hardware breakpoint perf_event structures.
- [High] Hardware breakpoint addresses are not updated for offline CPUs, leading to stale addresses when CPUs come online.
- [Medium] The 'count' parameter is decremented on trigger evaluation misses, causing the trigger to exhaust its count without actually modifying the watchpoint.
- [Medium] The wprobe event permanently leaks as enabled when the trigger is unregistered because EVENT_FILE_FL_SOFT_DISABLED_BIT is manually cleared.
- [Low] A field named 'unlimited' is silently ignored by clear_wprobe if no count keyword is provided.
--

commit 146ca411781d7203b266aa3745d30641c87b97d2
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 4 lines
kernel/trace/trace_wprobe.c +0 -0
index 9c6100b63e8d9..55a201504bb0b 100644

[ ... ]

kernel/trace/trace_wprobe.c static struct trace_wprobe *alloc_trace_wprobe(const char *group, · line 308

Quoted 7 lines
kernel/trace/trace_wprobe.c +5 -0
@@ -231,6 +303,12 @@ static struct trace_wprobe *alloc_trace_wprobe(const char *group,
 
+static void wprobe_work_func(struct work_struct *work)
+{
+	struct trace_wprobe *tw = container_of(work, struct trace_wprobe, work);
+
+	on_each_cpu(wprobe_smp_update_func, tw, true);

[Severity: High]
Could this leave hardware breakpoints with stale addresses on offline CPUs?

on_each_cpu() only broadcasts to currently online CPUs, so offline CPUs won't execute trace_wprobe_update_local(). When an offline CPU comes online, won't the perf event core reinstall the hardware breakpoint using the old, stale address since it wasn't updated here?

[ ... ]

Quoted 1 line
kernel/trace/trace_wprobe.c +0 -0
@@ -773,3 +866,538 @@ static __init int init_wprobe_trace(void)

[ ... ]

Quoted 8 lines
kernel/trace/trace_wprobe.c +8 -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 addr = 0, flags;
+	bool changed = false;

[ ... ]

Quoted 6 lines
kernel/trace/trace_wprobe.c +6 -0
+	raw_spin_lock_irqsave(&tw->lock, flags);
+
+	if (!wprobe_data->clear) {
+		if (!trace_wprobe_is_valid_addr(addr, tw->len)) {
+			atomic_inc(&tw->missed);
+			goto out;

kernel/trace/trace_wprobe.c static __init int init_wprobe_trace(void) · line 921

Quoted 10 lines
kernel/trace/trace_wprobe.c +10 -0
+		}
+		if (tw->addr == WPROBE_DEFAULT_CLEAR_ADDRESS) {
+			/* Skip if a previous work is still propagating the address */
+			if (atomic_read(&tw->work_pending)) {
+				atomic_inc(&tw->missed);
+				goto out;
+			}
+			WRITE_ONCE(tw->addr, addr);
+			changed = true;
+			clear_bit(EVENT_FILE_FL_SOFT_DISABLED_BIT, &wprobe_data->file->flags);

[Severity: Medium]
Does manually clearing EVENT_FILE_FL_SOFT_DISABLED_BIT cause the event to leak as enabled?

When the trigger is unregistered, wprobe_trigger_free() calls trace_event_enable_disable(file, 0, 1). Because the soft-disabled bit was cleared here, won't the core event logic skip the unregister step, leaving the wprobe tracepoint permanently enabled in the kernel?

[ ... ]

Quoted 5 lines
kernel/trace/trace_wprobe.c +5 -0
+static int wprobe_trigger_cmd_parse(struct event_command *cmd_ops,
+				    struct trace_event_file *file,
+				    char *glob, char *cmd,
+				    char *param_and_filter)
+{

[ ... ]

kernel/trace/trace_wprobe.c static __init int init_wprobe_trace(void) · line 1163

Quoted 3 lines
kernel/trace/trace_wprobe.c +3 -0
+	} else if (param && (isalpha(param[0]) || param[0] == '_')) {
+		if (strncmp(param, "count=", 6) != 0 &&
+		    strcmp(param, "unlimited") != 0) {

[Severity: Low]
Is this intended to skip fields named "unlimited"?

If a user configures a clear_wprobe trigger on an event that happens to have a field named "unlimited", this parser matches the keyword and skips parsing it as a field, which defaults to an unconditional clear action.

[ ... ]

Quoted 18 lines
kernel/trace/trace_wprobe.c +18 -0
+static int wprobe_register_trigger(char *glob,
+				   struct event_trigger_data *data,
+				   struct trace_event_file *file)
+{
+	int ret = 0;
+
+	lockdep_assert_held(&event_mutex);
+
+	/* The same wprobe is not accept on the same file (event) */
+	if (wprobe_trigger_find_same(data, file))
+		return -EEXIST;
+
+	if (data->cmd_ops->init) {
+		ret = data->cmd_ops->init(data);
+		if (ret < 0)
+			return ret;
+	}
+

kernel/trace/trace_wprobe.c static __init int init_wprobe_trace(void) · line 1333

Quoted 10 lines
kernel/trace/trace_wprobe.c +10 -0
+	list_add_rcu(&data->list, &file->triggers);
+
+	update_cond_flag(file);
+	ret = trace_event_trigger_enable_disable(file, 1);
+	if (ret < 0) {
+		list_del_rcu(&data->list);
+		update_cond_flag(file);
+		if (data->cmd_ops->free)
+			data->cmd_ops->free(data);
+	}

[Severity: High]
Does this error path need RCU synchronization?

If trace_event_trigger_enable_disable() fails, list_del_rcu() is called without a subsequent synchronize_rcu(). The cmd_ops->free callback (wprobe_trigger_free) will then synchronously disable the wprobe, which frees the tw->bp_event array.

Could a concurrent tracepoint reader still observe the trigger data, execute wprobe_trigger(), and dereference the freed tw->bp_event via this_cpu_ptr() inside trace_wprobe_update_local()?

[ ... ]

kernel/trace/trace_wprobe.c static __init int init_wprobe_trace(void) · line 1367

Quoted 11 lines
kernel/trace/trace_wprobe.c +11 -0
+static struct event_command trigger_wprobe_set_cmd = {
+	.name			= SET_WPROBE_STR,
+	.trigger_type		= ETT_EVENT_WPROBE,
+	/* This triggers after when the event is recorded. */
+	.flags			= EVENT_CMD_FL_NEEDS_REC,
+	.parse			= wprobe_trigger_cmd_parse,
+	.reg			= wprobe_register_trigger,
+	.unreg			= wprobe_unregister_trigger,
+	.set_filter		= set_trigger_filter,
+	.trigger		= wprobe_trigger,
+	.count_func		= event_trigger_count,

[Severity: Medium]
Will this unconditionally exhaust the trigger's count parameter even on misses?

Because .count_func is set to event_trigger_count, the count is decremented before wprobe_trigger() runs. If the trigger fails its implicit checks inside wprobe_trigger() (such as checking if the field matches the watched address), the count has already been consumed.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=10
author maintainer
#24 lore raw

Re: [PATCH v16 10/13] tracing/wprobe: Add set_wprobe and clear_wprobe event triggers

Quoted 37 lines · On Mon, 14 Sep 2026 14:58:44 +0000 [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Missing RCU synchronization in the error path of wprobe trigger registration leads to a Use-After-Free of hardware breakpoint perf_event structures.
- [High] Hardware breakpoint addresses are not updated for offline CPUs, leading to stale addresses when CPUs come online.
- [Medium] The 'count' parameter is decremented on trigger evaluation misses, causing the trigger to exhaust its count without actually modifying the watchpoint.
- [Medium] The wprobe event permanently leaks as enabled when the trigger is unregistered because EVENT_FILE_FL_SOFT_DISABLED_BIT is manually cleared.
- [Low] A field named 'unlimited' is silently ignored by clear_wprobe if no count keyword is provided.
--

commit 146ca411781d7203b266aa3745d30641c87b97d2
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 4 lines
kernel/trace/trace_wprobe.c +0 -0
index 9c6100b63e8d9..55a201504bb0b 100644

[ ... ]

kernel/trace/trace_wprobe.c static struct trace_wprobe *alloc_trace_wprobe(const char *group, · line 308

Quoted 7 lines
kernel/trace/trace_wprobe.c +5 -0
@@ -231,6 +303,12 @@ static struct trace_wprobe *alloc_trace_wprobe(const char *group,
 
+static void wprobe_work_func(struct work_struct *work)
+{
+	struct trace_wprobe *tw = container_of(work, struct trace_wprobe, work);
+
+	on_each_cpu(wprobe_smp_update_func, tw, true);

[Severity: High]
Could this leave hardware breakpoints with stale addresses on offline CPUs?

Quoted 4 lines

on_each_cpu() only broadcasts to currently online CPUs, so offline CPUs won't execute trace_wprobe_update_local(). When an offline CPU comes online, won't the perf event core reinstall the hardware breakpoint using the old, stale address since it wasn't updated here?

OK, introduce cpu hotplug callback to handle it.

Quoted 39 lines

[ ... ]

Quoted 1 line
kernel/trace/trace_wprobe.c +0 -0
@@ -773,3 +866,538 @@ static __init int init_wprobe_trace(void)

[ ... ]

Quoted 8 lines
kernel/trace/trace_wprobe.c +8 -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 addr = 0, flags;
+	bool changed = false;

[ ... ]

Quoted 6 lines
kernel/trace/trace_wprobe.c +6 -0
+	raw_spin_lock_irqsave(&tw->lock, flags);
+
+	if (!wprobe_data->clear) {
+		if (!trace_wprobe_is_valid_addr(addr, tw->len)) {
+			atomic_inc(&tw->missed);
+			goto out;

kernel/trace/trace_wprobe.c static __init int init_wprobe_trace(void) · line 921

Quoted 10 lines
kernel/trace/trace_wprobe.c +10 -0
+		}
+		if (tw->addr == WPROBE_DEFAULT_CLEAR_ADDRESS) {
+			/* Skip if a previous work is still propagating the address */
+			if (atomic_read(&tw->work_pending)) {
+				atomic_inc(&tw->missed);
+				goto out;
+			}
+			WRITE_ONCE(tw->addr, addr);
+			changed = true;
+			clear_bit(EVENT_FILE_FL_SOFT_DISABLED_BIT, &wprobe_data->file->flags);

[Severity: Medium]
Does manually clearing EVENT_FILE_FL_SOFT_DISABLED_BIT cause the event to leak as enabled?

Quoted 4 lines

When the trigger is unregistered, wprobe_trigger_free() calls trace_event_enable_disable(file, 0, 1). Because the soft-disabled bit was cleared here, won't the core event logic skip the unregister step, leaving the wprobe tracepoint permanently enabled in the kernel?

Good catch!
Hmm, we should set EVENT_FILE_FL_SOFT_DISABLED_BIT when removing a wprobe_trigger.

Quoted 18 lines

[ ... ]

Quoted 5 lines
kernel/trace/trace_wprobe.c +5 -0
+static int wprobe_trigger_cmd_parse(struct event_command *cmd_ops,
+				    struct trace_event_file *file,
+				    char *glob, char *cmd,
+				    char *param_and_filter)
+{

[ ... ]

kernel/trace/trace_wprobe.c static __init int init_wprobe_trace(void) · line 1163

Quoted 3 lines
kernel/trace/trace_wprobe.c +3 -0
+	} else if (param && (isalpha(param[0]) || param[0] == '_')) {
+		if (strncmp(param, "count=", 6) != 0 &&
+		    strcmp(param, "unlimited") != 0) {

[Severity: Low]
Is this intended to skip fields named "unlimited"?

Quoted 3 lines

If a user configures a clear_wprobe trigger on an event that happens to have a field named "unlimited", this parser matches the keyword and skips parsing it as a field, which defaults to an unconditional clear action.

Hmm, OK. Let's check the event has "unlimited" field or not.

Quoted 35 lines

[ ... ]

Quoted 18 lines
kernel/trace/trace_wprobe.c +18 -0
+static int wprobe_register_trigger(char *glob,
+				   struct event_trigger_data *data,
+				   struct trace_event_file *file)
+{
+	int ret = 0;
+
+	lockdep_assert_held(&event_mutex);
+
+	/* The same wprobe is not accept on the same file (event) */
+	if (wprobe_trigger_find_same(data, file))
+		return -EEXIST;
+
+	if (data->cmd_ops->init) {
+		ret = data->cmd_ops->init(data);
+		if (ret < 0)
+			return ret;
+	}
+

kernel/trace/trace_wprobe.c static __init int init_wprobe_trace(void) · line 1333

Quoted 10 lines
kernel/trace/trace_wprobe.c +10 -0
+	list_add_rcu(&data->list, &file->triggers);
+
+	update_cond_flag(file);
+	ret = trace_event_trigger_enable_disable(file, 1);
+	if (ret < 0) {
+		list_del_rcu(&data->list);
+		update_cond_flag(file);
+		if (data->cmd_ops->free)
+			data->cmd_ops->free(data);
+	}

[Severity: High]
Does this error path need RCU synchronization?

Quoted 8 lines

If trace_event_trigger_enable_disable() fails, list_del_rcu() is called without a subsequent synchronize_rcu(). The cmd_ops->free callback (wprobe_trigger_free) will then synchronously disable the wprobe, which frees the tw->bp_event array.

Could a concurrent tracepoint reader still observe the trigger data, execute wprobe_trigger(), and dereference the freed tw->bp_event via this_cpu_ptr() inside trace_wprobe_update_local()?

Yes. Let me add tracepoint_synchronize_unregister() here for waiting RCU.

Quoted 18 lines

[ ... ]

kernel/trace/trace_wprobe.c static __init int init_wprobe_trace(void) · line 1367

Quoted 11 lines
kernel/trace/trace_wprobe.c +11 -0
+static struct event_command trigger_wprobe_set_cmd = {
+	.name			= SET_WPROBE_STR,
+	.trigger_type		= ETT_EVENT_WPROBE,
+	/* This triggers after when the event is recorded. */
+	.flags			= EVENT_CMD_FL_NEEDS_REC,
+	.parse			= wprobe_trigger_cmd_parse,
+	.reg			= wprobe_register_trigger,
+	.unreg			= wprobe_unregister_trigger,
+	.set_filter		= set_trigger_filter,
+	.trigger		= wprobe_trigger,
+	.count_func		= event_trigger_count,

[Severity: Medium]
Will this unconditionally exhaust the trigger's count parameter even on misses?

Quoted 4 lines

Because .count_func is set to event_trigger_count, the count is decremented before wprobe_trigger() runs. If the trigger fails its implicit checks inside wprobe_trigger() (such as checking if the field matches the watched address), the count has already been consumed.

Hmm, OK. Let me add wprobe_count_func() to check the condition.

Thank you,

Quoted 3 lines
Signature · 2 lines
-- 
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=10
Signature · 1 line
Masami Hiramatsu (Google) <[email protected]>
author maintainer
#25 lore raw

PATCH v16 11/13 selftests: tracing: Add wprobe trigger testcase

In reply to Masami Hiramatsu (Google)

From: Masami Hiramatsu (Google) <[email protected]>

Add a testcase for checking wprobe trigger. 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 trigger syntax error logging.

Assisted-by Antigravity:gemini-3.8-flash

---
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-syntax-errors.tc |   37 +++++++
 .../ftrace/test.d/trigger/trigger-wprobe.tc        |  107 ++++++++++++++++++++
 3 files changed, 145 insertions(+)
 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
index d2f503722020..ecdee77f360f 100644
@@ -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-syntax-errors.tc new file +37 -0
new file mode 100644
index 000000000000..dd1ce4baa62b
@@ -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

#26 lore raw

Re: [PATCH v16 11/13] selftests: tracing: Add wprobe trigger testcase

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 11 lines

From: Masami Hiramatsu (Google) <[email protected]>

Add a testcase for checking wprobe trigger. 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 trigger syntax error logging.

Assisted-by Antigravity:gemini-3.8-flash

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=11
author maintainer
#27 lore raw

PATCH v16 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.

Assisted-by Antigravity:gemini-3.8-flash

---
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
index df8985283312..20a11443c6db 100644
@@ -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
index 77266e042418..ccf489635ad7 100644
@@ -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
index 1e11077ead67..c54c554b1949 100644
@@ -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
index ecdee77f360f..f067874902ed 100644
@@ -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

#28 lore raw

Re: [PATCH v16 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_events

With a set_wprobe trigger pointing the watchpoint at a dentry address, the resulting trace shows d_flags being 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_KERNEL flag used when parsing wprobe fetchargs.

Assisted-by Antigravity:gemini-3.8-flash

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=12
author maintainer
#29 lore raw

PATCH v16 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.

Assisted-by Antigravity:gemini-3.8-flash

---
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
index 20a11443c6db..1d9b32d02d53 100644
@@ -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

330 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

#30 lore raw

Re: [PATCH v16 13/13] tracing/wprobe: Support BTF struct offset resolution in set_wprobe trigger

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 9 lines

From: Masami Hiramatsu (Google) <[email protected]>

Allow set_wprobe trigger to use BTF struct offset resolution to specify the target address field.

Assisted-by Antigravity:gemini-3.8-flash

Sashiko has reviewed this patch and found no issues. It looks great!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/178939017565.94750.9431053336761330458.stgit@devnote2?part=13