Skip to contentSkip to conversation

hw-breakpoints: Rewrite on top of perf events v6

GIT PULL In review Frederic Weisbecker 5 participants 30 messages Nov 8, 2009 – Dec 1, 2009

Subsystems (7)
lore
Share & tools
lore
#0 lore raw

Ingo,

Please pull the tracing/hw-breakpoints branch that can be found at:

git://git.kernel.org/pub/scm/linux/kernel/git/frederic/random-tracing.git
tracing/hw-breakpoints

Changes in v6:

- Fix wrong header inclusion in trace.h (triggered a build error with CONFIG_FTRACE_SELFTEST)

- Currently, events scheduling are done in this order: cpu context pinned + cpu context non-pinned + task context pinned + task context non-pinned events. Then our current constraints are right theoretically but not in practice, because non-pinned counters may be scheduled before we can apply every possible pinned counters. So consider non-pinned counters as pinned for now (thanks Paul for reporting this)

Thanks,
Frederic
---

Frederic Weisbecker (4):
perf/core: Add a callback to perf events
hw-breakpoint: Move asm-generic/hw_breakpoint.h to linux/hw_breakpoint.h
hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events
hw-breakpoints: Arbitrate access to pmu following registers constraints

Arjan van de Ven (1):
perf/core: Provide a kernel-internal interface to get to performance counters

Li Zefan (1):
ksym_tracer: Remove KSYM_SELFTEST_ENTRY

Paul Mundt (1):
x86/hw-breakpoints: Actually flush thread breakpoints in flush_thread().

 arch/Kconfig                         |    3 +
 arch/x86/include/asm/Kbuild          |    1 +
 arch/x86/include/asm/debugreg.h      |   11 +-
 arch/x86/include/asm/hw_breakpoint.h |   58 +++--
 arch/x86/include/asm/processor.h     |   12 +-
 arch/x86/kernel/hw_breakpoint.c      |  391 +++++++++++++++--------
 arch/x86/kernel/process.c            |    9 +-
 arch/x86/kernel/process_32.c         |   26 +--
 arch/x86/kernel/process_64.c         |   26 +--
 arch/x86/kernel/ptrace.c             |  182 ++++++++----
 arch/x86/kernel/smpboot.c            |    3 -
 arch/x86/kvm/x86.c                   |   18 +-
 arch/x86/power/cpu.c                 |    6 -
 include/asm-generic/hw_breakpoint.h  |  139 ---------
 include/linux/hw_breakpoint.h        |  131 ++++++++
 include/linux/perf_event.h           |   37 +++-
 kernel/exit.c                        |    5 +
 kernel/hw_breakpoint.c               |  569 ++++++++++++++++++++--------------
 kernel/perf_event.c                  |  136 ++++++++-
 kernel/trace/trace.h                 |    6 +-
 kernel/trace/trace_entries.h         |    6 +-
 kernel/trace/trace_ksym.c            |  126 ++++----
 kernel/trace/trace_selftest.c        |    4 +-
 23 files changed, 1162 insertions(+), 743 deletions(-)
#1 lore raw

PATCH v6 1/7 perf/core: Provide a kernel-internal interface to get to performance counters

From: Arjan van de Ven <[email protected]>

There are reasons for kernel code to ask for, and use, performance counters.
For example, in CPU freq governors this tends to be a good idea, but there are other examples possible as well of course.

This patch adds the needed bits to do enable this functionality; they have been tested in an experimental cpufreq driver that I'm working on, and the changes are all that I needed to access counters properly.

[[email protected]: added pid to perf_event_create_kernel_counter so that we can profile a particular task too

TODO: Have a better error reporting, don't just return NULL in fail case.]

v2: Remove the wrong comment about the fact
perf_event_create_kernel_counter must be called from a kernel thread.

Cc "K.Prasad" <[email protected]>
Cc Alan Stern <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Jan Kiszka <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Li Zefan <[email protected]>
Cc Avi Kivity <[email protected]>
Cc Paul Mackerras <[email protected]>
Cc Mike Galbraith <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Paul Mundt <[email protected]>
Cc Jan Kiszka <[email protected]>
Cc Avi Kivity <[email protected]>

LKML-Reference: <[email protected]>

---
 include/linux/perf_event.h |    6 +++
 kernel/perf_event.c        |   75 +++++++++++++++++++++++++++++++++++++++++++-
 2 files changed, 80 insertions(+), 1 deletions(-)
include/linux/perf_event.h +6 -0
index df9d964..fa151d4 100644
@@ -744,6 +744,12 @@ extern int hw_perf_group_sched_in(struct perf_event *group_leader,
 	       struct perf_cpu_context *cpuctx,
 	       struct perf_event_context *ctx, int cpu);
 extern void perf_event_update_userpage(struct perf_event *event);
+extern int perf_event_release_kernel(struct perf_event *event);
+extern struct perf_event *
+perf_event_create_kernel_counter(struct perf_event_attr *attr,
+				int cpu,
+				pid_t pid);
+extern u64 perf_event_read_value(struct perf_event *event);
 
 struct perf_sample_data {
 	u64				type;
kernel/perf_event.c +74 -1

99 lines not on this page · raw message

Signature · 1 line
1.6.2.3
#2 lore raw

PATCH v6 2/7 x86/hw-breakpoints: Actually flush thread breakpoints in flush_thread().

In reply to Frederic Weisbecker

From: Paul Mundt <[email protected]>

flush_thread() tries to do a TIF_DEBUG check before calling in to flush_thread_hw_breakpoint() (which subsequently clears the thread flag), but for some reason, the x86 code is manually clearing TIF_DEBUG immediately before the test, so this path will never be taken.

This kills off the erroneous clear_tsk_thread_flag() and lets flush_thread_hw_breakpoint() actually get invoked.

Presumably folks were getting lucky with testing and the free_thread_info() -> free_thread_xstate() path was taking care of the flush there.

LKML-Reference: <[email protected]>

---
 arch/x86/kernel/process.c |    2 --
 1 files changed, 0 insertions(+), 2 deletions(-)
arch/x86/kernel/process.c +0 -2
index 2275ce5..cf8ee00 100644
@@ -107,8 +107,6 @@ void flush_thread(void)
 	}
 #endif
 
-	clear_tsk_thread_flag(tsk, TIF_DEBUG);
-
 	if (unlikely(test_tsk_thread_flag(tsk, TIF_DEBUG)))
 		flush_thread_hw_breakpoint(tsk);
 	memset(tsk->thread.tls_array, 0, sizeof(tsk->thread.tls_array));
Signature · 1 line
1.6.2.3
#3 lore raw

PATCH v6 3/7 perf/core: Add a callback to perf events

In reply to Frederic Weisbecker

A simple callback in a perf event can be used for multiple purposes. For example it is useful for triggered based events like hardware breakpoints that need a callback to dispatch a triggered breakpoint event.

v2: Simplify a bit the callback attribution as suggested by Paul
Mackerras

Cc Peter Zijlstra <[email protected]>
Cc "K.Prasad" <[email protected]>
Cc Alan Stern <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Paul Mackerras <[email protected]>
Cc Mike Galbraith <[email protected]>
Cc Paul Mundt <[email protected]>
---
 include/linux/perf_event.h |    7 ++++++-
 kernel/perf_event.c        |   14 ++++++++++----
 2 files changed, 16 insertions(+), 5 deletions(-)
include/linux/perf_event.h +6 -1
index fa151d4..8d54e6d 100644
@@ -544,6 +544,8 @@ struct perf_pending_entry {
 	void (*func)(struct perf_pending_entry *);
 };
 
+typedef void (*perf_callback_t)(struct perf_event *, void *);
+
 /**
  * struct perf_event - performance event kernel representation:
  */
@@ -639,6 +641,8 @@ struct perf_event {
 	struct event_filter		*filter;
 #endif
 
+	perf_callback_t			callback;
+
 #endif /* CONFIG_PERF_EVENTS */
 };
 
@@ -748,7 +752,8 @@ extern int perf_event_release_kernel(struct perf_event *event);
 extern struct perf_event *
 perf_event_create_kernel_counter(struct perf_event_attr *attr,
 				int cpu,
-				pid_t pid);
+				pid_t pid,
+				perf_callback_t callback);
 extern u64 perf_event_read_value(struct perf_event *event);
 
 struct perf_sample_data {
kernel/perf_event.c +10 -4
index 02d4ff0..5087125 100644
@@ -4293,6 +4293,7 @@ perf_event_alloc(struct perf_event_attr *attr,
 		   struct perf_event_context *ctx,
 		   struct perf_event *group_leader,
 		   struct perf_event *parent_event,
+		   perf_callback_t callback,
 		   gfp_t gfpflags)
 {
 	const struct pmu *pmu;
@@ -4335,6 +4336,11 @@ perf_event_alloc(struct perf_event_attr *attr,
 
 	event->state		= PERF_EVENT_STATE_INACTIVE;
 
+	if (!callback && parent_event)
+		callback = parent_event->callback;
+	
+	event->callback	= callback;
+
 	if (attr->disabled)
 		event->state = PERF_EVENT_STATE_OFF;
 
@@ -4611,7 +4617,7 @@ SYSCALL_DEFINE5(perf_event_open,
 	}
 
 	event = perf_event_alloc(&attr, cpu, ctx, group_leader,
-				     NULL, GFP_KERNEL);
+				     NULL, NULL, GFP_KERNEL);
 	err = PTR_ERR(event);
 	if (IS_ERR(event))
 		goto err_put_context;
@@ -4668,7 +4674,7 @@ err_put_context:
  */
 struct perf_event *
 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
-				 pid_t pid)
+				 pid_t pid, perf_callback_t callback)
 {
 	struct perf_event *event;
 	struct perf_event_context *ctx;
@@ -4683,7 +4689,7 @@ perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
 		return NULL ;
 
 	event = perf_event_alloc(attr, cpu, ctx, NULL,
-				     NULL, GFP_KERNEL);
+				     NULL, callback, GFP_KERNEL);
 	err = PTR_ERR(event);
 	if (IS_ERR(event))
 		goto err_put_context;
@@ -4736,7 +4742,7 @@ inherit_event(struct perf_event *parent_event,
 	child_event = perf_event_alloc(&parent_event->attr,
 					   parent_event->cpu, child_ctx,
 					   group_leader, parent_event,
-					   GFP_KERNEL);
+					   NULL, GFP_KERNEL);
 	if (IS_ERR(child_event))
 		return child_event;
 	get_ctx(child_ctx);
Signature · 1 line
1.6.2.3
maintainer
#4 lore raw

Re: [PATCH 3/7 v6] perf/core: Add a callback to perf events

Quoted 7 lines · Frederic Weisbecker

A simple callback in a perf event can be used for multiple purposes. For example it is useful for triggered based events like hardware breakpoints that need a callback to dispatch a triggered breakpoint event.

v2: Simplify a bit the callback attribution as suggested by Paul
Mackerras

Yuck! So we add an opaque callback without semantics nor usage.

Quoted 97 lines
---
 include/linux/perf_event.h |    7 ++++++-
 kernel/perf_event.c        |   14 ++++++++++----
 2 files changed, 16 insertions(+), 5 deletions(-)
include/linux/perf_event.h +6 -1
index fa151d4..8d54e6d 100644
@@ -544,6 +544,8 @@ struct perf_pending_entry {
 	void (*func)(struct perf_pending_entry *);
 };
 
+typedef void (*perf_callback_t)(struct perf_event *, void *);
+
 /**
  * struct perf_event - performance event kernel representation:
  */
@@ -639,6 +641,8 @@ struct perf_event {
 	struct event_filter		*filter;
 #endif
 
+	perf_callback_t			callback;
+
 #endif /* CONFIG_PERF_EVENTS */
 };
 
@@ -748,7 +752,8 @@ extern int perf_event_release_kernel(struct perf_event *event);
 extern struct perf_event *
 perf_event_create_kernel_counter(struct perf_event_attr *attr,
 				int cpu,
-				pid_t pid);
+				pid_t pid,
+				perf_callback_t callback);
 extern u64 perf_event_read_value(struct perf_event *event);
 
 struct perf_sample_data {
kernel/perf_event.c +10 -4
index 02d4ff0..5087125 100644
@@ -4293,6 +4293,7 @@ perf_event_alloc(struct perf_event_attr *attr,
 		   struct perf_event_context *ctx,
 		   struct perf_event *group_leader,
 		   struct perf_event *parent_event,
+		   perf_callback_t callback,
 		   gfp_t gfpflags)
 {
 	const struct pmu *pmu;
@@ -4335,6 +4336,11 @@ perf_event_alloc(struct perf_event_attr *attr,
 
 	event->state		= PERF_EVENT_STATE_INACTIVE;
 
+	if (!callback && parent_event)
+		callback = parent_event->callback;
+	
+	event->callback	= callback;
+
 	if (attr->disabled)
 		event->state = PERF_EVENT_STATE_OFF;
 
@@ -4611,7 +4617,7 @@ SYSCALL_DEFINE5(perf_event_open,
 	}
 
 	event = perf_event_alloc(&attr, cpu, ctx, group_leader,
-				     NULL, GFP_KERNEL);
+				     NULL, NULL, GFP_KERNEL);
 	err = PTR_ERR(event);
 	if (IS_ERR(event))
 		goto err_put_context;
@@ -4668,7 +4674,7 @@ err_put_context:
  */
 struct perf_event *
 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
-				 pid_t pid)
+				 pid_t pid, perf_callback_t callback)
 {
 	struct perf_event *event;
 	struct perf_event_context *ctx;
@@ -4683,7 +4689,7 @@ perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
 		return NULL ;
 
 	event = perf_event_alloc(attr, cpu, ctx, NULL,
-				     NULL, GFP_KERNEL);
+				     NULL, callback, GFP_KERNEL);
 	err = PTR_ERR(event);
 	if (IS_ERR(event))
 		goto err_put_context;
@@ -4736,7 +4742,7 @@ inherit_event(struct perf_event *parent_event,
 	child_event = perf_event_alloc(&parent_event->attr,
 					   parent_event->cpu, child_ctx,
 					   group_leader, parent_event,
-					   GFP_KERNEL);
+					   NULL, GFP_KERNEL);
 	if (IS_ERR(child_event))
 		return child_event;
 	get_ctx(child_ctx);
#5 lore raw

Re: [PATCH 3/7 v6] perf/core: Add a callback to perf events

Quoted 10 lines · Peter Zijlstra
Quoted 7 lines · Frederic Weisbecker

A simple callback in a perf event can be used for multiple purposes. For example it is useful for triggered based events like hardware breakpoints that need a callback to dispatch a triggered breakpoint event.

v2: Simplify a bit the callback attribution as suggested by Paul
Mackerras

Yuck! So we add an opaque callback without semantics nor usage.

Yeah, this is intended for events that need to be able to trigger events to different channels. In the case of hw-breakpoints, it's either perf buffer, ptrace, etc...

Should I add some comments about it?

maintainer
#6 lore raw

Re: [PATCH 3/7 v6] perf/core: Add a callback to perf events

Quoted 10 lines · Frederic Weisbecker
Quoted 9 lines · Peter Zijlstra
Quoted 7 lines · Frederic Weisbecker

A simple callback in a perf event can be used for multiple purposes. For example it is useful for triggered based events like hardware breakpoints that need a callback to dispatch a triggered breakpoint event.

v2: Simplify a bit the callback attribution as suggested by Paul
Mackerras

Quoted 8 lines
Quoted 1 line

Yuck! So we add an opaque callback without semantics nor usage.

Yeah, this is intended for events that need to be able to trigger events to different channels. In the case of hw-breakpoints, it's either perf buffer, ptrace, etc...

Should I add some comments about it?

At the very least.. describe its semantics and preferably rename the thing.

Currently I've no clue what it does and why, your description above about multiple channels does not at all help me understand how this function pointer is used to make that happen.

#7 lore raw

Re: [PATCH 3/7 v6] perf/core: Add a callback to perf events

Quoted 14 lines · Peter Zijlstra
Quoted 13 lines · Frederic Weisbecker
Quoted 10 lines · Peter Zijlstra
Quoted 7 lines · Frederic Weisbecker

A simple callback in a perf event can be used for multiple purposes. For example it is useful for triggered based events like hardware breakpoints that need a callback to dispatch a triggered breakpoint event.

v2: Simplify a bit the callback attribution as suggested by Paul
Mackerras

Yuck! So we add an opaque callback without semantics nor usage.

Quoted 8 lines
Quoted 5 lines

Yeah, this is intended for events that need to be able to trigger events to different channels. In the case of hw-breakpoints, it's either perf buffer, ptrace, etc...

Should I add some comments about it?

At the very least.. describe its semantics and preferably rename the thing.

May be "event_triggered"?

Quoted 4 lines

Currently I've no clue what it does and why, your description above about multiple channels does not at all help me understand how this function pointer is used to make that happen.

We need it for hardware breakpoints because if we register a breakpoint for perf syscall use, we need to dispatch the event to perf. But if we register it for ptrace, or any in-kernel uses, we need to dispatch the event somewhere else and then we need another callback.

maintainer
#8 lore raw

Re: [PATCH 3/7 v6] perf/core: Add a callback to perf events

Quoted 19 lines · Frederic Weisbecker
Quoted 18 lines · Peter Zijlstra
Quoted 17 lines · Frederic Weisbecker
Quoted 10 lines · Peter Zijlstra
Quoted 7 lines · Frederic Weisbecker

A simple callback in a perf event can be used for multiple purposes. For example it is useful for triggered based events like hardware breakpoints that need a callback to dispatch a triggered breakpoint event.

v2: Simplify a bit the callback attribution as suggested by Paul
Mackerras

Yuck! So we add an opaque callback without semantics nor usage.

Yeah, this is intended for events that need to be able to trigger events to different channels. In the case of hw-breakpoints, it's either perf buffer, ptrace, etc...

Quoted 7 lines
Quoted 4 lines
Quoted 1 line

Should I add some comments about it?

At the very least.. describe its semantics and preferably rename the thing.

May be "event_triggered"?

What event? There is no caller.

Quoted 10 lines
Quoted 4 lines

Currently I've no clue what it does and why, your description above about multiple channels does not at all help me understand how this function pointer is used to make that happen.

We need it for hardware breakpoints because if we register a breakpoint for perf syscall use, we need to dispatch the event to perf. But if we register it for ptrace, or any in-kernel uses, we need to dispatch the event somewhere else and then we need another callback.

So you simply want to have a different overflow/sample handler?

Doesn't something like the below work? We need that anyway for kernel based consumers that want to do anything with the sampling event.

include/linux/perf_event.h +6 -0
Index: linux-2.6/include/linux/perf_event.h
===================================================================
@@ -567,6 +567,8 @@ struct perf_pending_entry {
 
 typedef void (*perf_callback_t)(struct perf_event *, void *);
 
+struct perf_sample_data;
+
 /**
  * struct perf_event - performance event kernel representation:
  */
@@ -658,6 +660,10 @@ struct perf_event {
 	struct pid_namespace		*ns;
 	u64				id;
 
+	void (*overflow_handler)(struct perf_event *event,
+			int nmi, struct perf_sample_data *data,
+			struct pt_regs *regs);
+
 #ifdef CONFIG_EVENT_PROFILE
 	struct event_filter		*filter;
 #endif
kernel/perf_event.c +7 -1
Index: linux-2.6/kernel/perf_event.c
===================================================================
@@ -3710,7 +3710,11 @@ static int __perf_event_overflow(struct 
 			perf_event_disable(event);
 	}
 
-	perf_event_output(event, nmi, data, regs);
+	if (event->overflow_handler)
+		event->overflow_handler(event, nmi, data, regs);
+	else
+		perf_event_output(event, nmi, data, regs);
+
 	return ret;
 }
 
@@ -4836,6 +4849,8 @@ inherit_event(struct perf_event *parent_
 	if (parent_event->attr.freq)
 		child_event->hw.sample_period = parent_event->hw.sample_period;
 
+	child_event->overflow_handler = parent->overflow_handler;
+
 	/*
 	 * Link it up in the child's context:
 	 */
#9 lore raw

PATCH v6 4/7 hw-breakpoint: Move asm-generic/hw_breakpoint.h to linux/hw_breakpoint.h

In reply to Frederic Weisbecker

We plan to make the breakpoints parameters generic among architectures. For that it's better to move the asm-generic header to a generic linux header.

---
 arch/x86/include/asm/hw_breakpoint.h           |    2 +-
 include/{asm-generic => linux}/hw_breakpoint.h |    9 +++------
 2 files changed, 4 insertions(+), 7 deletions(-)
 rename include/{asm-generic => linux}/hw_breakpoint.h (96%)
arch/x86/include/asm/hw_breakpoint.h +1 -1
index 1acb4d4..3cfca8e 100644
@@ -12,7 +12,7 @@ struct arch_hw_breakpoint {
 };
 
 #include <linux/kdebug.h>
-#include <asm-generic/hw_breakpoint.h>
+#include <linux/hw_breakpoint.h>
 
 /* Available HW breakpoint length encodings */
 #define HW_BREAKPOINT_LEN_1		0x40
include/linux/hw_breakpoint.h renamed from include/asm-generic/hw_breakpoint.h +3 -6
similarity index 96%
rename from include/asm-generic/hw_breakpoint.h
rename to include/linux/hw_breakpoint.h
index 9bf2d12..61ccc8f 100644
@@ -1,9 +1,6 @@
-#ifndef	_ASM_GENERIC_HW_BREAKPOINT_H
-#define	_ASM_GENERIC_HW_BREAKPOINT_H
+#ifndef _LINUX_HW_BREAKPOINT_H
+#define _LINUX_HW_BREAKPOINT_H
 
-#ifndef __ARCH_HW_BREAKPOINT_H
-#error "Please don't include this file directly"
-#endif
 
 #ifdef	__KERNEL__
 #include <linux/list.h>
@@ -136,4 +133,4 @@ extern void unregister_kernel_hw_breakpoint(struct hw_breakpoint *bp);
 extern unsigned int hbp_kernel_pos;
 
 #endif	/* __KERNEL__ */
-#endif	/* _ASM_GENERIC_HW_BREAKPOINT_H */
+#endif	/* _LINUX_HW_BREAKPOINT_H */
Signature · 1 line
1.6.2.3
#10 lore raw

PATCH v6 5/7 hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events

In reply to Frederic Weisbecker

This patch rebase the implementation of the breakpoints API on top of perf events instances.

Each breakpoints are now perf events that handle the register scheduling, thread/cpu attachment, etc..

The new layering is now made as follows:

ptrace kgdb ftrace perf syscall
\ | / /
\ | / /
/
Core breakpoint API /
/
| /
| /

Breakpoints perf events

|
|

Breakpoints PMU ---- Debug Register constraints handling
(Part of core breakpoint API)
|
|

Hardware debug registers

Reasons of this rewrite:

- Use the centralized/optimized pmu registers scheduling, implying an easier arch integration
- More powerful register handling: perf attributes (pinned/flexible events, exclusive/non-exclusive, tunable period, etc...)

Impact:

- New perf ABI: the hardware breakpoints counters
- Ptrace breakpoints setting remains tricky and still needs some per thread breakpoints references.

Todo (in the order):

- Support breakpoints perf counter events for perf tools (ie: implement perf_bpcounter_event())
- Support from perf tools

Changes in v2:

- Follow the perf "event " rename
- The ptrace regression have been fixed (ptrace breakpoint perf events weren't released when a task ended)
- Drop the struct hw_breakpoint and store generic fields in perf_event_attr.
- Separate core and arch specific headers, drop asm-generic/hw_breakpoint.h and create linux/hw_breakpoint.h
- Use new generic len/type for breakpoint
- Handle off case: when breakpoints api is not supported by an arch

Changes in v3:

- Fix broken CONFIG_KVM, we need to propagate the breakpoint api changes to kvm when we exit the guest and restore the bp registers to the host.

Changes in v4:

- Drop the hw_breakpoint_restore() stub as it is only used by KVM
- EXPORT_SYMBOL_GPL hw_breakpoint_restore() as KVM can be built as a module
- Restore the breakpoints unconditionally on kvm guest exit:
TIF_DEBUG_THREAD doesn't anymore cover every cases of running breakpoints and vcpu->arch.switch_db_regs might not always be set when the guest used debug registers.
(Waiting for a reliable optimization)

Changes in v5:

- Split-up the asm-generic/hw-breakpoint.h moving to linux/hw_breakpoint.h into a separate patch
- Optimize the breakpoints restoring while switching from kvm guest to host. We only want to restore the state if we have active breakpoints to the host, otherwise we don't care about messed-up address registers.
- Add asm/hw_breakpoint.h to Kbuild
- Fix bad breakpoint type in trace_selftest.c

Changes in v6:

- Fix wrong header inclusion in trace.h (triggered a build error with CONFIG_FTRACE_SELFTEST

Cc Prasad <[email protected]>
Cc Alan Stern <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Jan Kiszka <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Li Zefan <[email protected]>
Cc Avi Kivity <[email protected]>
Cc Paul Mackerras <[email protected]>
Cc Mike Galbraith <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Paul Mundt <[email protected]>
---
 arch/Kconfig                         |    3 +
 arch/x86/include/asm/Kbuild          |    1 +
 arch/x86/include/asm/debugreg.h      |   11 +-
 arch/x86/include/asm/hw_breakpoint.h |   58 +++--
 arch/x86/include/asm/processor.h     |   12 +-
 arch/x86/kernel/hw_breakpoint.c      |  391 ++++++++++++++++++++-----------
 arch/x86/kernel/process.c            |    7 +-
 arch/x86/kernel/process_32.c         |   26 +--
 arch/x86/kernel/process_64.c         |   26 +--
 arch/x86/kernel/ptrace.c             |  182 ++++++++++-----
 arch/x86/kernel/smpboot.c            |    3 -
 arch/x86/kvm/x86.c                   |   18 +-
 arch/x86/power/cpu.c                 |    6 -
 include/linux/hw_breakpoint.h        |  243 ++++++++++----------
 include/linux/perf_event.h           |   26 ++-
 kernel/exit.c                        |    5 +
 kernel/hw_breakpoint.c               |  424 ++++++++++++++--------------------
 kernel/perf_event.c                  |   53 ++++-
 kernel/trace/trace.h                 |    5 +-
 kernel/trace/trace_entries.h         |    6 +-
 kernel/trace/trace_ksym.c            |  126 +++++------
 kernel/trace/trace_selftest.c        |    3 +-
 22 files changed, 885 insertions(+), 750 deletions(-)
arch/Kconfig +3 -0
index acb6643..eef3bbb 100644
@@ -128,6 +128,9 @@ config HAVE_DEFAULT_NO_SPIN_MUTEXES
 
 config HAVE_HW_BREAKPOINT
 	bool
+	depends on HAVE_PERF_EVENTS
+	select ANON_INODES
+	select PERF_EVENTS
 
 
 source "kernel/gcov/Kconfig"
arch/x86/include/asm/Kbuild +1 -0
index 4a8e80c..9f828f8 100644
@@ -10,6 +10,7 @@ header-y += ptrace-abi.h
 header-y += sigcontext32.h
 header-y += ucontext.h
 header-y += processor-flags.h
+header-y += hw_breakpoint.h
 
 unifdef-y += e820.h
 unifdef-y += ist.h
arch/x86/include/asm/debugreg.h +5 -6
index 23439fb..9a3333c 100644
@@ -75,13 +75,8 @@
  */
 #ifdef __KERNEL__
 
-/* For process management */
-extern void flush_thread_hw_breakpoint(struct task_struct *tsk);
-extern int copy_thread_hw_breakpoint(struct task_struct *tsk,
-		struct task_struct *child, unsigned long clone_flags);
+DECLARE_PER_CPU(unsigned long, dr7);
 
-/* For CPU management */
-extern void load_debug_registers(void);
 static inline void hw_breakpoint_disable(void)
 {
 	/* Zero the control register for HW Breakpoint */
@@ -94,6 +89,10 @@ static inline void hw_breakpoint_disable(void)
 	set_debugreg(0UL, 3);
 }
 
+#ifdef CONFIG_KVM
+extern void hw_breakpoint_restore(void);
+#endif
+
 #endif	/* __KERNEL__ */
 
 #endif /* _ASM_X86_DEBUGREG_H */
arch/x86/include/asm/hw_breakpoint.h +38 -20

88 lines not on this page · raw message

arch/x86/include/asm/processor.h +6 -6
index 61aafb7..820f300 100644
@@ -423,6 +423,8 @@ extern unsigned int xstate_size;
 extern void free_thread_xstate(struct task_struct *);
 extern struct kmem_cache *task_xstate_cachep;
 
+struct perf_event;
+
 struct thread_struct {
 	/* Cached TLS descriptors: */
 	struct desc_struct	tls_array[GDT_ENTRY_TLS_ENTRIES];
@@ -444,12 +446,10 @@ struct thread_struct {
 	unsigned long		fs;
 #endif
 	unsigned long		gs;
-	/* Hardware debugging registers: */
-	unsigned long		debugreg[HBP_NUM];
-	unsigned long		debugreg6;
-	unsigned long		debugreg7;
-	/* Hardware breakpoint info */
-	struct hw_breakpoint	*hbp[HBP_NUM];
+	/* Save middle states of ptrace breakpoints */
+	struct perf_event	*ptrace_bps[HBP_NUM];
+	/* Debug status used for traps, single steps, etc... */
+	unsigned long           debugreg6;
 	/* Fault info: */
 	unsigned long		cr2;
 	unsigned long		trap_no;
arch/x86/kernel/hw_breakpoint.c +255 -136

549 lines not on this page · raw message

arch/x86/kernel/process.c +2 -5
index cf8ee00..744508e 100644
@@ -10,6 +10,7 @@
 #include <linux/clockchips.h>
 #include <linux/random.h>
 #include <trace/events/power.h>
+#include <linux/hw_breakpoint.h>
 #include <asm/system.h>
 #include <asm/apic.h>
 #include <asm/syscalls.h>
@@ -18,7 +19,6 @@
 #include <asm/i387.h>
 #include <asm/ds.h>
 #include <asm/debugreg.h>
-#include <asm/hw_breakpoint.h>
 
 unsigned long idle_halt;
 EXPORT_SYMBOL(idle_halt);
@@ -47,8 +47,6 @@ void free_thread_xstate(struct task_struct *tsk)
 		kmem_cache_free(task_xstate_cachep, tsk->thread.xstate);
 		tsk->thread.xstate = NULL;
 	}
-	if (unlikely(test_tsk_thread_flag(tsk, TIF_DEBUG)))
-		flush_thread_hw_breakpoint(tsk);
 
 	WARN(tsk->thread.ds_ctx, "leaking DS context\n");
 }
@@ -107,8 +105,7 @@ void flush_thread(void)
 	}
 #endif
 
-	if (unlikely(test_tsk_thread_flag(tsk, TIF_DEBUG)))
-		flush_thread_hw_breakpoint(tsk);
+	flush_ptrace_hw_breakpoint(tsk);
 	memset(tsk->thread.tls_array, 0, sizeof(tsk->thread.tls_array));
 	/*
 	 * Forget coprocessor state..
arch/x86/kernel/process_32.c +2 -24
index 209e748..d5bd313 100644
@@ -59,7 +59,6 @@
 #include <asm/syscalls.h>
 #include <asm/ds.h>
 #include <asm/debugreg.h>
-#include <asm/hw_breakpoint.h>
 
 asmlinkage void ret_from_fork(void) __asm__("ret_from_fork");
 
@@ -264,9 +263,8 @@ int copy_thread(unsigned long clone_flags, unsigned long sp,
 	p->thread.io_bitmap_ptr = NULL;
 	tsk = current;
 	err = -ENOMEM;
-	if (unlikely(test_tsk_thread_flag(tsk, TIF_DEBUG)))
-		if (copy_thread_hw_breakpoint(tsk, p, clone_flags))
-			goto out;
+
+	memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
 
 	if (unlikely(test_tsk_thread_flag(tsk, TIF_IO_BITMAP))) {
 		p->thread.io_bitmap_ptr = kmemdup(tsk->thread.io_bitmap_ptr,
@@ -287,13 +285,10 @@ int copy_thread(unsigned long clone_flags, unsigned long sp,
 		err = do_set_thread_area(p, -1,
 			(struct user_desc __user *)childregs->si, 0);
 
-out:
 	if (err && p->thread.io_bitmap_ptr) {
 		kfree(p->thread.io_bitmap_ptr);
 		p->thread.io_bitmap_max = 0;
 	}
-	if (err)
-		flush_thread_hw_breakpoint(p);
 
 	clear_tsk_thread_flag(p, TIF_DS_AREA_MSR);
 	p->thread.ds_ctx = NULL;
@@ -437,23 +432,6 @@ __switch_to(struct task_struct *prev_p, struct task_struct *next_p)
 		lazy_load_gs(next->gs);
 
 	percpu_write(current_task, next_p);
-	/*
-	 * There's a problem with moving the arch_install_thread_hw_breakpoint()
-	 * call before current is updated.  Suppose a kernel breakpoint is
-	 * triggered in between the two, the hw-breakpoint handler will see that
-	 * the 'current' task does not have TIF_DEBUG flag set and will think it
-	 * is leftover from an old task (lazy switching) and will erase it. Then
-	 * until the next context switch, no user-breakpoints will be installed.
-	 *
-	 * The real problem is that it's impossible to update both current and
-	 * physical debug registers at the same instant, so there will always be
-	 * a window in which they disagree and a breakpoint might get triggered.
-	 * Since we use lazy switching, we are forced to assume that a
-	 * disagreement means that current is correct and the exception is due
-	 * to lazy debug register switching.
-	 */
-	if (unlikely(test_tsk_thread_flag(next_p, TIF_DEBUG)))
-		arch_install_thread_hw_breakpoint(next_p);
 
 	return prev_p;
 }
arch/x86/kernel/process_64.c +1 -25
index 72edac0..5bafdec 100644
@@ -53,7 +53,6 @@
 #include <asm/syscalls.h>
 #include <asm/ds.h>
 #include <asm/debugreg.h>
-#include <asm/hw_breakpoint.h>
 
 asmlinkage extern void ret_from_fork(void);
 
@@ -244,8 +243,6 @@ void release_thread(struct task_struct *dead_task)
 			BUG();
 		}
 	}
-	if (unlikely(dead_task->thread.debugreg7))
-		flush_thread_hw_breakpoint(dead_task);
 }
 
 static inline void set_32bit_tls(struct task_struct *t, int tls, u32 addr)
@@ -309,9 +306,7 @@ int copy_thread(unsigned long clone_flags, unsigned long sp,
 	savesegment(ds, p->thread.ds);
 
 	err = -ENOMEM;
-	if (unlikely(test_tsk_thread_flag(me, TIF_DEBUG)))
-		if (copy_thread_hw_breakpoint(me, p, clone_flags))
-			goto out;
+	memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps));
 
 	if (unlikely(test_tsk_thread_flag(me, TIF_IO_BITMAP))) {
 		p->thread.io_bitmap_ptr = kmalloc(IO_BITMAP_BYTES, GFP_KERNEL);
@@ -351,8 +346,6 @@ out:
 		kfree(p->thread.io_bitmap_ptr);
 		p->thread.io_bitmap_max = 0;
 	}
-	if (err)
-		flush_thread_hw_breakpoint(p);
 
 	return err;
 }
@@ -508,23 +501,6 @@ __switch_to(struct task_struct *prev_p, struct task_struct *next_p)
 	 */
 	if (preload_fpu)
 		__math_state_restore();
-	/*
-	 * There's a problem with moving the arch_install_thread_hw_breakpoint()
-	 * call before current is updated.  Suppose a kernel breakpoint is
-	 * triggered in between the two, the hw-breakpoint handler will see that
-	 * the 'current' task does not have TIF_DEBUG flag set and will think it
-	 * is leftover from an old task (lazy switching) and will erase it. Then
-	 * until the next context switch, no user-breakpoints will be installed.
-	 *
-	 * The real problem is that it's impossible to update both current and
-	 * physical debug registers at the same instant, so there will always be
-	 * a window in which they disagree and a breakpoint might get triggered.
-	 * Since we use lazy switching, we are forced to assume that a
-	 * disagreement means that current is correct and the exception is due
-	 * to lazy debug register switching.
-	 */
-	if (unlikely(test_tsk_thread_flag(next_p, TIF_DEBUG)))
-		arch_install_thread_hw_breakpoint(next_p);
 
 	return prev_p;
 }
arch/x86/kernel/ptrace.c +125 -57

257 lines not on this page · raw message

arch/x86/kernel/smpboot.c +0 -3
index 213a7a3..565ebc6 100644
@@ -64,7 +64,6 @@
 #include <asm/apic.h>
 #include <asm/setup.h>
 #include <asm/uv/uv.h>
-#include <asm/debugreg.h>
 #include <linux/mc146818rtc.h>
 
 #include <asm/smpboot_hooks.h>
@@ -328,7 +327,6 @@ notrace static void __cpuinit start_secondary(void *unused)
 	x86_cpuinit.setup_percpu_clockev();
 
 	wmb();
-	load_debug_registers();
 	cpu_idle();
 }
 
@@ -1269,7 +1267,6 @@ void cpu_disable_common(void)
 	remove_cpu_from_maps(cpu);
 	unlock_vector_lock();
 	fixup_irqs();
-	hw_breakpoint_disable();
 }
 
 int native_cpu_disable(void)
arch/x86/kvm/x86.c +10 -8
index fc2974a..22dee7a 100644
@@ -42,6 +42,7 @@
 #define CREATE_TRACE_POINTS
 #include "trace.h"
 
+#include <asm/debugreg.h>
 #include <asm/uaccess.h>
 #include <asm/msr.h>
 #include <asm/desc.h>
@@ -3643,14 +3644,15 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
 	trace_kvm_entry(vcpu->vcpu_id);
 	kvm_x86_ops->run(vcpu, kvm_run);
 
-	if (unlikely(vcpu->arch.switch_db_regs || test_thread_flag(TIF_DEBUG))) {
-		set_debugreg(current->thread.debugreg[0], 0);
-		set_debugreg(current->thread.debugreg[1], 1);
-		set_debugreg(current->thread.debugreg[2], 2);
-		set_debugreg(current->thread.debugreg[3], 3);
-		set_debugreg(current->thread.debugreg6, 6);
-		set_debugreg(current->thread.debugreg7, 7);
-	}
+	/*
+	 * If the guest has used debug registers, at least dr7
+	 * will be disabled while returning to the host.
+	 * If we don't have active breakpoints in the host, we don't
+	 * care about the messed up debug address registers. But if
+	 * we have some of them active, restore the old state.
+	 */
+	if (__get_cpu_var(dr7) & DR_GLOBAL_ENABLE_MASK)
+		hw_breakpoint_restore();
 
 	set_bit(KVM_REQ_KICK, &vcpu->requests);
 	local_irq_enable();
arch/x86/power/cpu.c +0 -6
index e09a44f..0a979f3 100644
@@ -105,7 +105,6 @@ static void __save_processor_state(struct saved_context *ctxt)
 	ctxt->cr4 = read_cr4();
 	ctxt->cr8 = read_cr8();
 #endif
-	hw_breakpoint_disable();
 }
 
 /* Needed by apm.c */
@@ -144,11 +143,6 @@ static void fix_processor_context(void)
 #endif
 	load_TR_desc();				/* This does ltr */
 	load_LDT(&current->active_mm->context);	/* This does lldt */
-
-	/*
-	 * Now maybe reload the debug registers
-	 */
-	load_debug_registers();
 }
 
 /**
include/linux/hw_breakpoint.h +119 -124

255 lines not on this page · raw message

include/linux/perf_event.h +25 -1
index 8d54e6d..cead64e 100644
@@ -18,6 +18,10 @@
 #include <linux/ioctl.h>
 #include <asm/byteorder.h>
 
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+#include <asm/hw_breakpoint.h>
+#endif
+
 /*
  * User-space ABI bits:
  */
@@ -31,6 +35,7 @@ enum perf_type_id {
 	PERF_TYPE_TRACEPOINT			= 2,
 	PERF_TYPE_HW_CACHE			= 3,
 	PERF_TYPE_RAW				= 4,
+	PERF_TYPE_BREAKPOINT			= 5,
 
 	PERF_TYPE_MAX,				/* non-ABI */
 };
@@ -207,6 +212,15 @@ struct perf_event_attr {
 		__u32		wakeup_events;	  /* wakeup every n events */
 		__u32		wakeup_watermark; /* bytes before wakeup   */
 	};
+
+	union {
+		struct { /* Hardware breakpoint info */
+			__u64		bp_addr;
+			__u32		bp_type;
+			__u32		bp_len;
+		};
+	};
+
 	__u32			__reserved_2;
 
 	__u64			__reserved_3;
@@ -476,6 +490,11 @@ struct hw_perf_event {
 			atomic64_t	count;
 			struct hrtimer	hrtimer;
 		};
+#ifdef CONFIG_HAVE_HW_BREAKPOINT
+		union { /* breakpoint */
+			struct arch_hw_breakpoint	info;
+		};
+#endif
 	};
 	atomic64_t			prev_count;
 	u64				sample_period;
@@ -588,7 +607,7 @@ struct perf_event {
 	u64				tstamp_running;
 	u64				tstamp_stopped;
 
-	struct perf_event_attr	attr;
+	struct perf_event_attr		attr;
 	struct hw_perf_event		hw;
 
 	struct perf_event_context	*ctx;
@@ -643,6 +662,8 @@ struct perf_event {
 
 	perf_callback_t			callback;
 
+	perf_callback_t			event_callback;
+
 #endif /* CONFIG_PERF_EVENTS */
 };
 
@@ -831,6 +852,7 @@ extern int sysctl_perf_event_sample_rate;
 extern void perf_event_init(void);
 extern void perf_tp_event(int event_id, u64 addr, u64 count,
 				 void *record, int entry_size);
+extern void perf_bp_event(struct perf_event *event, void *data);
 
 #ifndef perf_misc_flags
 #define perf_misc_flags(regs)	(user_mode(regs) ? PERF_RECORD_MISC_USER : \
@@ -865,6 +887,8 @@ static inline int perf_event_task_enable(void)				{ return -EINVAL; }
 static inline void
 perf_sw_event(u32 event_id, u64 nr, int nmi,
 		     struct pt_regs *regs, u64 addr)			{ }
+static inline void
+perf_bp_event(struct perf_event *event, void *data)		{ }
 
 static inline void perf_event_mmap(struct vm_area_struct *vma)		{ }
 static inline void perf_event_comm(struct task_struct *tsk)		{ }
kernel/exit.c +5 -0
index e61891f..266f892 100644
@@ -49,6 +49,7 @@
 #include <linux/init_task.h>
 #include <linux/perf_event.h>
 #include <trace/events/sched.h>
+#include <linux/hw_breakpoint.h>
 
 #include <asm/uaccess.h>
 #include <asm/unistd.h>
@@ -980,6 +981,10 @@ NORET_TYPE void do_exit(long code)
 	proc_exit_connector(tsk);
 
 	/*
+	 * FIXME: do that only when needed, using sched_exit tracepoint
+	 */
+	flush_ptrace_hw_breakpoint(tsk);
+	/*
 	 * Flush inherited counters to the parent - before the parent
 	 * gets woken up by child-exit notifications.
 	 */
kernel/hw_breakpoint.c +170 -254

515 lines not on this page · raw message

kernel/perf_event.c +52 -1

77 lines not on this page · raw message

kernel/trace/trace.h +1 -4
index 91c3d0e..d72f06f 100644
@@ -11,14 +11,11 @@
 #include <linux/ftrace.h>
 #include <trace/boot.h>
 #include <linux/kmemtrace.h>
+#include <linux/hw_breakpoint.h>
 
 #include <linux/trace_seq.h>
 #include <linux/ftrace_event.h>
 
-#ifdef CONFIG_KSYM_TRACER
-#include <asm/hw_breakpoint.h>
-#endif
-
 enum trace_type {
 	__TRACE_FIRST_TYPE = 0,
 
kernel/trace/trace_entries.h +3 -3
index e19747d..c16a08f 100644
@@ -372,11 +372,11 @@ FTRACE_ENTRY(ksym_trace, ksym_trace_entry,
 	F_STRUCT(
 		__field(	unsigned long,	ip			  )
 		__field(	unsigned char,	type			  )
-		__array(	char	     ,	ksym_name, KSYM_NAME_LEN  )
 		__array(	char	     ,	cmd,	   TASK_COMM_LEN  )
+		__field(	unsigned long,  addr			  )
 	),
 
-	F_printk("ip: %pF type: %d ksym_name: %s cmd: %s",
+	F_printk("ip: %pF type: %d ksym_name: %pS cmd: %s",
 		(void *)__entry->ip, (unsigned int)__entry->type,
-		__entry->ksym_name, __entry->cmd)
+		(void *)__entry->addr,  __entry->cmd)
 );
kernel/trace/trace_ksym.c +60 -66

241 lines not on this page · raw message

kernel/trace/trace_selftest.c +2 -1
index 7179c12..27c5072 100644
@@ -828,7 +828,8 @@ trace_selftest_startup_ksym(struct tracer *trace, struct trace_array *tr)
 
 	ksym_selftest_dummy = 0;
 	/* Register the read-write tracing request */
-	ret = process_new_ksym_entry(KSYM_SELFTEST_ENTRY, HW_BREAKPOINT_RW,
+	ret = process_new_ksym_entry(KSYM_SELFTEST_ENTRY,
+				     HW_BREAKPOINT_R | HW_BREAKPOINT_W,
 					(unsigned long)(&ksym_selftest_dummy));
 
 	if (ret < 0) {
Signature · 1 line
1.6.2.3
#11 lore raw

Re: [PATCH 5/7 v6] hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events

Quoted 22 lines · Frederic Weisbecker
arch/x86/kvm/x86.c +1 -6
index fc2974a..22dee7a 100644
@@ -42,6 +42,7 @@
 #define CREATE_TRACE_POINTS
 #include "trace.h"
 
+#include <asm/debugreg.h>
 #include <asm/uaccess.h>
 #include <asm/msr.h>
 #include <asm/desc.h>
@@ -3643,14 +3644,15 @@ static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run)
 	trace_kvm_entry(vcpu->vcpu_id);
 	kvm_x86_ops->run(vcpu, kvm_run);
 
-	if (unlikely(vcpu->arch.switch_db_regs || test_thread_flag(TIF_DEBUG))) {
-		set_debugreg(current->thread.debugreg[0], 0);
-		set_debugreg(current->thread.debugreg[1], 1);
-		set_debugreg(current->thread.debugreg[2], 2);
-		set_debugreg(current->thread.debugreg[3], 3);
-		set_debugreg(current->thread.debugreg6, 6);

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) · line 3654

Quoted 10 lines
arch/x86/kvm/x86.c +8 -2
-		set_debugreg(current->thread.debugreg7, 7);
-	}
+	/*
+	 * If the guest has used debug registers, at least dr7
+	 * will be disabled while returning to the host.
+	 * If we don't have active breakpoints in the host, we don't
+	 * care about the messed up debug address registers. But if
+	 * we have some of them active, restore the old state.
+	 */
+	if (__get_cpu_var(dr7) & DR_GLOBAL_ENABLE_MASK)

Looks good, just a minor remark: Would be cleaner to wrap this into an inline function, say hw_breakpoint_active(), to abstract the precise condition away from KVM.

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) · line 3658

Quoted 4 lines
arch/x86/kvm/x86.c +1 -0
+		hw_breakpoint_restore();
 
 	set_bit(KVM_REQ_KICK, &vcpu->requests);
 	local_irq_enable();

Will see that I can give your series a try the next days, probably debugging qemu-kvm while running a guest that uses breakpoints. But I don't expect surprises.

Jan

#12 lore raw

Re: [PATCH 5/7 v6] hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events

Quoted 8 lines · Jan Kiszka

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) · line 3654

Quoted 4 lines
arch/x86/kvm/x86.c +4 -0
+	 * care about the messed up debug address registers. But if
+	 * we have some of them active, restore the old state.
+	 */
+	if (__get_cpu_var(dr7) & DR_GLOBAL_ENABLE_MASK)

Looks good, just a minor remark: Would be cleaner to wrap this into an inline function, say hw_breakpoint_active(), to abstract the precise condition away from KVM.

Done :)

Quoted 10 lines

arch/x86/kvm/x86.c static int vcpu_enter_guest(struct kvm_vcpu *vcpu, struct kvm_run *kvm_run) · line 3658

Quoted 4 lines
arch/x86/kvm/x86.c +1 -0
+		hw_breakpoint_restore();
 
 	set_bit(KVM_REQ_KICK, &vcpu->requests);
 	local_irq_enable();

Will see that I can give your series a try the next days, probably debugging qemu-kvm while running a guest that uses breakpoints. But I don't expect surprises.

Jan

Thanks!

You can find it at:
git://git.kernel.org/pub/scm/linux/kernel/git/tip/linux-2.6-tip.git
tracing/hw-breakpoints

#13 lore raw

Re: [PATCH 5/7 v6] hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events

In reply to Frederic Weisbecker

On Sun, Nov 08, 2009 at 04:28:59PM +0100, Frederic Weisbecker wrote:

There were a few comments that I posted against version 6 of your patchset (which happened to cross your version 7 posting...) regarding the breakpoint interfaces, reservation of register for unpinned events and such...

By the way, I'm looking at refs/heads/perfevents/hw-breakpoint branch in
git://git.kernel.org/pub/scm/linux/kernel/git/frederic/random-tracing.git
and hope that's correct/latest?

Some more comments about the ptrace implementation here...

static int ptrace_set_breakpoint_addr(struct task_struct *tsk, int nr,
unsigned long addr)

{
	struct perf_event *bp;
	struct thread_struct *t = &tsk->thread;

	if (!t->ptrace_bps[nr]) {
		/*
		 * Put stub len and type to register (reserve) an inactive but
		 * correct bp
		 */
		bp = register_user_hw_breakpoint(addr, HW_BREAKPOINT_LEN_1,
						 HW_BREAKPOINT_W,
						 ptrace_triggered, tsk,
						 false);

..
...
}

Given that a register_user_hw_breakpoint() is done at the time of a write to DR0-DR3, it would needlessly hold onto the debug register until the corresponding DR7 bit is allocated while using up one 'pinned' debug slot. It would be prudent to postpone the breakpoint registration till DR7 is changed to activate it.

static int ptrace_write_dr7(struct task_struct *tsk, unsigned long data) {
..
...

		/*
		 * We shoud have at least an inactive breakpoint at this
		 * slot. It means the user is writing dr7 without having
		 * written the address register first
		 */
		if (!bp) {
			rc = -EINVAL;
			break;
		}

I was just about confused...thinking that the above condition would become true during second_pass, but alas it turns out that you restore "thread->ptrace_bps[i] = bp" again later.

		rc = arch_bp_generic_fields(len, type, &gen_len, &gen_type);
		if (rc)
			break;

		/*
		 * This is a temporary thing as bp is unregistered/registered
		 * to simulate modification
		 */
		bp = modify_user_hw_breakpoint(bp, bp->attr.bp_addr, gen_len,
					       gen_type, bp->callback,
					       tsk, true);

modify_user_hw_breakpoint() is called twice (once per pass) and in its current implementation, it would leave open a window for register grabbing on two occasions. Another reason to change its implementation soon...

		thread->ptrace_bps[i] = NULL;

Why not remove this line from here...

		if (!bp) { /* incorrect bp, or we have a bug in bp API */
			rc = -EINVAL;
			break;
		}
		if (IS_ERR(bp)) {
			rc = PTR_ERR(bp);
			bp = NULL;
			break;
		}
		thread->ptrace_bps[i] = bp;

...and put it here inside a condition "if (second_pass)"?

	}
	/*
	 * Make a second pass to free the remaining unused breakpoints
	 * or to restore the original breakpoints if an error occurred.
	 */
	if (!second_pass) {
		second_pass = 1;
		if (rc < 0) {
			orig_ret = rc;
			data = old_dr7;
		}
		goto restore;
	}
	return ((orig_ret < 0) ? orig_ret : rc);
}

Thanks,
K.Prasad

#14 lore raw

Re: [PATCH 5/7 v6] hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events

Quoted 7 lines · K.Prasad

On Sun, Nov 08, 2009 at 04:28:59PM +0100, Frederic Weisbecker wrote:

There were a few comments that I posted against version 6 of your patchset (which happened to cross your version 7 posting...) regarding the breakpoint interfaces, reservation of register for unpinned events and such...

Quoted 7 lines

By the way, I'm looking at refs/heads/perfevents/hw-breakpoint branch in
git://git.kernel.org/pub/scm/linux/kernel/git/frederic/random-tracing.git
and hope that's correct/latest?

Some more comments about the ptrace implementation here...

I forgot to mention another potential bug here...

static int ptrace_write_dr7(struct task_struct *tsk, unsigned long data) {
..
...
restore:

	/*
	 * Loop through all the hardware breakpoints, making the
	 * appropriate changes to each.
	 */
	for (i = 0; i < HBP_NUM; i++) {
		enabled = decode_dr7(data, i, &len, &type);
		bp = thread->ptrace_bps[i];

		if (!enabled) {
			if (bp) {
				/*
				 * Don't unregister the breakpoints right-away,
				 * unless all register_user_hw_breakpoint()
				 * requests have succeeded. This prevents
				 * any window of opportunity for debug
				 * register grabbing by other users.
				 */
				if (!second_pass)
					continue;
				thread->ptrace_bps[i] = NULL;
				unregister_hw_breakpoint(bp);
			}
			continue;
		}

So, the breakpoint is unregistered whenever bits corresponding to DR0-DR3 are set to a disabled state in DR7.

		/*
		 * We shoud have at least an inactive breakpoint at this
		 * slot. It means the user is writing dr7 without having
		 * written the address register first
		 */
		if (!bp) {
			rc = -EINVAL;
			break;
		}

..
...
}

Now think of the following sequence of write operations through ptrace:
1. Populate address in DRn (where 0 <= n <= 3) (breakpoint registration)
2. Enable corresponding bits in DR7 (modify breakpoint to active state)
3. Disable bits in DR7 (unregister breakpoint)
4. Enable bits in DR7 (returns with failure)

The assumption that every 'enable' operation in DR7 is preceded by a write operation on DR0-DR3 need not be always true.

Thanks,
K.Prasad

#15 lore raw

Re: [PATCH 5/7 v6] hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events

Quoted 49 lines · K.Prasad

I forgot to mention another potential bug here...

static int ptrace_write_dr7(struct task_struct *tsk, unsigned long data) {
..
...
restore:

	/*
	 * Loop through all the hardware breakpoints, making the
	 * appropriate changes to each.
	 */
	for (i = 0; i < HBP_NUM; i++) {
		enabled = decode_dr7(data, i, &len, &type);
		bp = thread->ptrace_bps[i];

		if (!enabled) {
			if (bp) {
				/*
				 * Don't unregister the breakpoints right-away,
				 * unless all register_user_hw_breakpoint()
				 * requests have succeeded. This prevents
				 * any window of opportunity for debug
				 * register grabbing by other users.
				 */
				if (!second_pass)
					continue;
				thread->ptrace_bps[i] = NULL;
				unregister_hw_breakpoint(bp);
			}
			continue;
		}

So, the breakpoint is unregistered whenever bits corresponding to DR0-DR3 are set to a disabled state in DR7.

		/*
		 * We shoud have at least an inactive breakpoint at this
		 * slot. It means the user is writing dr7 without having
		 * written the address register first
		 */
		if (!bp) {
			rc = -EINVAL;
			break;
		}

..
...
}

Quoted 8 lines

Now think of the following sequence of write operations through ptrace:
1. Populate address in DRn (where 0 <= n <= 3) (breakpoint registration)
2. Enable corresponding bits in DR7 (modify breakpoint to active state)
3. Disable bits in DR7 (unregister breakpoint)
4. Enable bits in DR7 (returns with failure)

The assumption that every 'enable' operation in DR7 is preceded by a write operation on DR0-DR3 need not be always true.

Right. It just works with gdb because it usually rewrite the whole sequence while reactivating a breakpoint (addr rewrite + dr7 enable).

But still you're right in that this is buggy. The use of an array of struct arch_hw_breakpoint per thread should solve it.

Thanks.

#16 lore raw

Re: [PATCH 5/7 v6] hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events

In reply to K.Prasad
Quoted 6 lines · K.Prasad

On Sun, Nov 08, 2009 at 04:28:59PM +0100, Frederic Weisbecker wrote:

There were a few comments that I posted against version 6 of your patchset (which happened to cross your version 7 posting...) regarding the breakpoint interfaces, reservation of register for unpinned events and such...

Yep, sorry I replied a bit late.

Quoted 26 lines

By the way, I'm looking at refs/heads/perfevents/hw-breakpoint branch in
git://git.kernel.org/pub/scm/linux/kernel/git/frederic/random-tracing.git
and hope that's correct/latest?

Some more comments about the ptrace implementation here...

static int ptrace_set_breakpoint_addr(struct task_struct *tsk, int nr,
unsigned long addr)

{
	struct perf_event *bp;
	struct thread_struct *t = &tsk->thread;

	if (!t->ptrace_bps[nr]) {
		/*
		 * Put stub len and type to register (reserve) an inactive but
		 * correct bp
		 */
		bp = register_user_hw_breakpoint(addr, HW_BREAKPOINT_LEN_1,
						 HW_BREAKPOINT_W,
						 ptrace_triggered, tsk,
						 false);

..
...
}

Quoted 5 lines

Given that a register_user_hw_breakpoint() is done at the time of a write to DR0-DR3, it would needlessly hold onto the debug register until the corresponding DR7 bit is allocated while using up one 'pinned' debug slot. It would be prudent to postpone the breakpoint registration till DR7 is changed to activate it.

We register it but don't activate it so that we reserve a slot for later. But that may be useless actually. If we don't do that and later gdb fails to activate it trhough dr7 because there are concurrent users, it will just report the returned error.

So I guess I should probably drop this logic.

Quoted 14 lines

static int ptrace_write_dr7(struct task_struct *tsk, unsigned long data) {
..
...

		/*
		 * We shoud have at least an inactive breakpoint at this
		 * slot. It means the user is writing dr7 without having
		 * written the address register first
		 */
		if (!bp) {
			rc = -EINVAL;
			break;
		}
Quoted 3 lines

I was just about confused...thinking that the above condition would become true during second_pass, but alas it turns out that you restore "thread->ptrace_bps[i] = bp" again later.

Yeah, is it a problem?

Quoted 12 lines
		rc = arch_bp_generic_fields(len, type, &gen_len, &gen_type);
		if (rc)
			break;

		/*
		 * This is a temporary thing as bp is unregistered/registered
		 * to simulate modification
		 */
		bp = modify_user_hw_breakpoint(bp, bp->attr.bp_addr, gen_len,
					       gen_type, bp->callback,
					       tsk, true);
Quoted 4 lines

modify_user_hw_breakpoint() is called twice (once per pass) and in its current implementation, it would leave open a window for register grabbing on two occasions. Another reason to change its implementation soon...

Yeah agreed.

Quoted 16 lines
		thread->ptrace_bps[i] = NULL;

Why not remove this line from here...

		if (!bp) { /* incorrect bp, or we have a bug in bp API */
			rc = -EINVAL;
			break;
		}
		if (IS_ERR(bp)) {
			rc = PTR_ERR(bp);
			bp = NULL;
			break;
		}
		thread->ptrace_bps[i] = bp;
Quoted 1 line

...and put it here inside a condition "if (second_pass)"?

Yeah the whole needs a refactoring anyway.
We should have an array of arch breakpoint structure per thread and a pointer to a perf event. I think this will simplify the whole, as we don't need the temporary breakpoint trick.

Or something like that. I'll have a stab at it.

Thanks.

maintainer
#17 lore raw

Re: [PATCH 5/7 v6] hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events

In reply to Frederic Weisbecker

include/linux/perf_event.h struct perf_event { · line 668

Quoted 8 lines · Frederic Weisbecker
include/linux/perf_event.h +2 -0
@@ -643,6 +662,8 @@ struct perf_event {
 
        perf_callback_t                 callback;
 
+       perf_callback_t                 event_callback;
+
 #endif /* CONFIG_PERF_EVENTS */
 }; 

And here you add another one.. which is 100% unused in this patch..

#18 lore raw

Re: [PATCH 5/7 v6] hw-breakpoints: Rewrite the hw-breakpoints layer on top of perf events

Quoted 12 lines · Peter Zijlstra

include/linux/perf_event.h struct perf_event { · line 668

Quoted 8 lines · Frederic Weisbecker
include/linux/perf_event.h +2 -0
@@ -643,6 +662,8 @@ struct perf_event {
 
        perf_callback_t                 callback;
 
+       perf_callback_t                 event_callback;
+
 #endif /* CONFIG_PERF_EVENTS */
 }; 

And here you add another one.. which is 100% unused in this patch..

Oh, that must be a confusion when I rebased the patches. I'll remove it.

Thanks.

#19 lore raw

PATCH v6 6/7 hw-breakpoints: Arbitrate access to pmu following registers constraints

In reply to Frederic Weisbecker

Allow or refuse to build a counter using the breakpoints pmu following given constraints.

We keep track of the pmu users by using three per cpu variables:

- nr_cpu_bp_pinned stores the number of pinned cpu breakpoints counters in the given cpu

- nr_bp_flexible stores the number of non-pinned breakpoints counters in the given cpu.

- task_bp_pinned stores the number of pinned task breakpoints in a cpu

The latter is not a simple counter but gathers the number of tasks that have n pinned breakpoints.
Considering HBP_NUM the number of available breakpoint address registers:
task_bp_pinned[0] is the number of tasks having 1 breakpoint task_bp_pinned[1] is the number of tasks having 2 breakpoints [...]
task_bp_pinned[HBP_NUM - 1] is the number of tasks having the maximum number of registers (HBP_NUM).

When a breakpoint counter is created and wants an access to the pmu, we evaluate the following constraints:

== Non-pinned counter ==

- If attached to a single cpu, check:

(per_cpu(nr_bp_flexible, cpu) || (per_cpu(nr_cpu_bp_pinned, cpu)
+ max(per_cpu(task_bp_pinned, cpu)))) < HBP_NUM

-> If there are already non-pinned counters in this cpu, it
means there is already a free slot for them. Otherwise, we check that the maximum number of per task breakpoints (for this cpu) plus the number of per cpu breakpoint (for this cpu) doesn't cover every registers.

- If attached to every cpus, check:

(per_cpu(nr_bp_flexible, *) || (max(per_cpu(nr_cpu_bp_pinned, *))
+ max(per_cpu(task_bp_pinned, *)))) < HBP_NUM

-> This is roughly the same, except we check the number of per
cpu bp for every cpu and we keep the max one. Same for the per tasks breakpoints.

== Pinned counter ==

- If attached to a single cpu, check:

((per_cpu(nr_bp_flexible, cpu) > 1)
+ per_cpu(nr_cpu_bp_pinned, cpu)
+ max(per_cpu(task_bp_pinned, cpu))) < HBP_NUM

-> Same checks as before. But now the nr_bp_flexible, if any,
must keep one register at least (or flexible breakpoints will never be be fed).

- If attached to every cpus, check:

((per_cpu(nr_bp_flexible, *) > 1)
+ max(per_cpu(nr_cpu_bp_pinned, *))
+ max(per_cpu(task_bp_pinned, *))) < HBP_NUM

Changes in v2:

- Counter -> event rename

Changes in v5:

- Fix unreleased non-pinned task-bound-only counters. We only released it in the first cpu. (Thanks to Paul Mackerras for reporting that)

Changes in v6:

- Currently, events scheduling are done in this order: cpu context pinned + cpu context non-pinned + task context pinned + task context non-pinned events. Then our current constraints are right theoretically but not in practice, because non-pinned counters may be scheduled before we can apply every possible pinned counters. So consider non-pinned counters as pinned for now.

Cc Prasad <[email protected]>
Cc Alan Stern <[email protected]>
Cc Peter Zijlstra <[email protected]>
Cc Arnaldo Carvalho de Melo <[email protected]>
Cc Steven Rostedt <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Jan Kiszka <[email protected]>
Cc Jiri Slaby <[email protected]>
Cc Li Zefan <[email protected]>
Cc Avi Kivity <[email protected]>
Cc Paul Mackerras <[email protected]>
Cc Mike Galbraith <[email protected]>
Cc Masami Hiramatsu <[email protected]>
Cc Paul Mundt <[email protected]>
---
 kernel/hw_breakpoint.c |  211 ++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 205 insertions(+), 6 deletions(-)
kernel/hw_breakpoint.c +205 -6
index 08f6d01..e662dc9 100644
@@ -16,6 +16,8 @@
  * Copyright (C) 2007 Alan Stern
  * Copyright (C) IBM Corporation, 2009
  * Copyright (C) 2009, Frederic Weisbecker <[email protected]>
+ *
+ * Thanks to Ingo Molnar for his many suggestions.
  */
 
 /*
@@ -44,24 +46,221 @@
 #include <asm/debugreg.h>
 #endif
 
-static atomic_t bp_slot;
+/*
+ * Constraints data
+ */
+
+/* Number of pinned cpu breakpoints in a cpu */
+static DEFINE_PER_CPU(unsigned int, nr_cpu_bp_pinned);
 
-int reserve_bp_slot(struct perf_event *bp)
+/* Number of pinned task breakpoints in a cpu */
+static DEFINE_PER_CPU(unsigned int, task_bp_pinned[HBP_NUM]);
+
+/* Number of non-pinned cpu/task breakpoints in a cpu */
+static DEFINE_PER_CPU(unsigned int, nr_bp_flexible);
+
+/* Gather the number of total pinned and un-pinned bp in a cpuset */
+struct bp_busy_slots {
+	unsigned int pinned;
+	unsigned int flexible;
+};
+
+/* Serialize accesses to the above constraints */
+static DEFINE_MUTEX(nr_bp_mutex);
+
+/*
+ * Report the maximum number of pinned breakpoints a task
+ * have in this cpu
+ */
+static unsigned int max_task_bp_pinned(int cpu)
 {
-	if (atomic_inc_return(&bp_slot) == HBP_NUM) {
-		atomic_dec(&bp_slot);
+	int i;
+	unsigned int *tsk_pinned = per_cpu(task_bp_pinned, cpu);
 
-		return -ENOSPC;
+	for (i = HBP_NUM -1; i >= 0; i--) {
+		if (tsk_pinned[i] > 0)
+			return i + 1;
 	}
 
 	return 0;
 }
 
+/*
+ * Report the number of pinned/un-pinned breakpoints we have in
+ * a given cpu (cpu > -1) or in all of them (cpu = -1).
+ */
+static void fetch_bp_busy_slots(struct bp_busy_slots *slots, int cpu)
+{
+	if (cpu >= 0) {
+		slots->pinned = per_cpu(nr_cpu_bp_pinned, cpu);
+		slots->pinned += max_task_bp_pinned(cpu);
+		slots->flexible = per_cpu(nr_bp_flexible, cpu);
+
+		return;
+	}
+
+	for_each_online_cpu(cpu) {
+		unsigned int nr;
+
+		nr = per_cpu(nr_cpu_bp_pinned, cpu);
+		nr += max_task_bp_pinned(cpu);
+
+		if (nr > slots->pinned)
+			slots->pinned = nr;
+
+		nr = per_cpu(nr_bp_flexible, cpu);
+
+		if (nr > slots->flexible)
+			slots->flexible = nr;
+	}
+}
+
+/*
+ * Add a pinned breakpoint for the given task in our constraint table
+ */
+static void toggle_bp_task_slot(struct task_struct *tsk, int cpu, bool enable)
+{
+	int count = 0;
+	struct perf_event *bp;
+	struct perf_event_context *ctx = tsk->perf_event_ctxp;
+	unsigned int *task_bp_pinned;
+	struct list_head *list;
+	unsigned long flags;
+
+	if (WARN_ONCE(!ctx, "No perf context for this task"))
+		return;
+
+	list = &ctx->event_list;
+
+	spin_lock_irqsave(&ctx->lock, flags);
+
+	/*
+	 * The current breakpoint counter is not included in the list
+	 * at the open() callback time
+	 */
+	list_for_each_entry(bp, list, event_entry) {
+		if (bp->attr.type == PERF_TYPE_BREAKPOINT)
+			count++;
+	}
+
+	spin_unlock_irqrestore(&ctx->lock, flags);
+
+	if (WARN_ONCE(count < 0, "No breakpoint counter found in the counter list"))
+		return;
+
+	task_bp_pinned = per_cpu(task_bp_pinned, cpu);
+	if (enable) {
+		task_bp_pinned[count]++;
+		if (count > 0)
+			task_bp_pinned[count-1]--;
+	} else {
+		task_bp_pinned[count]--;
+		if (count > 0)
+			task_bp_pinned[count-1]++;
+	}
+}
+
+/*
+ * Add/remove the given breakpoint in our constraint table
+ */
+static void toggle_bp_slot(struct perf_event *bp, bool enable)
+{
+	int cpu = bp->cpu;
+	struct task_struct *tsk = bp->ctx->task;
+
+	/* Pinned counter task profiling */
+	if (tsk) {
+		if (cpu >= 0) {
+			toggle_bp_task_slot(tsk, cpu, enable);
+			return;
+		}
+
+		for_each_online_cpu(cpu)
+			toggle_bp_task_slot(tsk, cpu, enable);
+		return;
+	}
+
+	/* Pinned counter cpu profiling */
+	if (enable)
+		per_cpu(nr_cpu_bp_pinned, bp->cpu)++;
+	else
+		per_cpu(nr_cpu_bp_pinned, bp->cpu)--;
+}
+
+/*
+ * Contraints to check before allowing this new breakpoint counter:
+ *
+ *  == Non-pinned counter == (Considered as pinned for now)
+ *
+ *   - If attached to a single cpu, check:
+ *
+ *       (per_cpu(nr_bp_flexible, cpu) || (per_cpu(nr_cpu_bp_pinned, cpu)
+ *           + max(per_cpu(task_bp_pinned, cpu)))) < HBP_NUM
+ *
+ *       -> If there are already non-pinned counters in this cpu, it means
+ *          there is already a free slot for them.
+ *          Otherwise, we check that the maximum number of per task
+ *          breakpoints (for this cpu) plus the number of per cpu breakpoint
+ *          (for this cpu) doesn't cover every registers.
+ *
+ *   - If attached to every cpus, check:
+ *
+ *       (per_cpu(nr_bp_flexible, *) || (max(per_cpu(nr_cpu_bp_pinned, *))
+ *           + max(per_cpu(task_bp_pinned, *)))) < HBP_NUM
+ *
+ *       -> This is roughly the same, except we check the number of per cpu
+ *          bp for every cpu and we keep the max one. Same for the per tasks
+ *          breakpoints.
+ *
+ *
+ * == Pinned counter ==
+ *
+ *   - If attached to a single cpu, check:
+ *
+ *       ((per_cpu(nr_bp_flexible, cpu) > 1) + per_cpu(nr_cpu_bp_pinned, cpu)
+ *            + max(per_cpu(task_bp_pinned, cpu))) < HBP_NUM
+ *
+ *       -> Same checks as before. But now the nr_bp_flexible, if any, must keep
+ *          one register at least (or they will never be fed).
+ *
+ *   - If attached to every cpus, check:
+ *
+ *       ((per_cpu(nr_bp_flexible, *) > 1) + max(per_cpu(nr_cpu_bp_pinned, *))
+ *            + max(per_cpu(task_bp_pinned, *))) < HBP_NUM
+ */
+int reserve_bp_slot(struct perf_event *bp)
+{
+	struct bp_busy_slots slots = {0};
+	int ret = 0;
+
+	mutex_lock(&nr_bp_mutex);
+
+	fetch_bp_busy_slots(&slots, bp->cpu);
+
+	/* Flexible counters need to keep at least one slot */
+	if (slots.pinned + (!!slots.flexible) == HBP_NUM) {
+		ret = -ENOSPC;
+		goto end;
+	}
+
+	toggle_bp_slot(bp, true);
+
+end:
+	mutex_unlock(&nr_bp_mutex);
+
+	return ret;
+}
+
 void release_bp_slot(struct perf_event *bp)
 {
-	atomic_dec(&bp_slot);
+	mutex_lock(&nr_bp_mutex);
+
+	toggle_bp_slot(bp, false);
+
+	mutex_unlock(&nr_bp_mutex);
 }
 
+
 int __register_perf_hw_breakpoint(struct perf_event *bp)
 {
 	int ret;
Signature · 1 line
1.6.2.3
#20 lore raw

PATCH v6 7/7 ksym_tracer: Remove KSYM_SELFTEST_ENTRY

In reply to Frederic Weisbecker

From: Li Zefan <[email protected]>

The macro used to be used in both trace_selftest.c and trace_ksym.c, but no longer, so remove it from header file.

---
 kernel/trace/trace.h          |    1 -
 kernel/trace/trace_selftest.c |    3 ++-
 2 files changed, 2 insertions(+), 2 deletions(-)
kernel/trace/trace.h +0 -1
index d72f06f..ee00475 100644
@@ -367,7 +367,6 @@ int register_tracer(struct tracer *type);
 void unregister_tracer(struct tracer *type);
 int is_tracing_stopped(void);
 
-#define KSYM_SELFTEST_ENTRY "ksym_selftest_dummy"
 extern int process_new_ksym_entry(char *ksymname, int op, unsigned long addr);
 
 extern unsigned long nsecs_to_usecs(unsigned long nsecs);
kernel/trace/trace_selftest.c +2 -1
index 27c5072..dc98309 100644
@@ -828,7 +828,8 @@ trace_selftest_startup_ksym(struct tracer *trace, struct trace_array *tr)
 
 	ksym_selftest_dummy = 0;
 	/* Register the read-write tracing request */
-	ret = process_new_ksym_entry(KSYM_SELFTEST_ENTRY,
+
+	ret = process_new_ksym_entry("ksym_selftest_dummy",
 				     HW_BREAKPOINT_R | HW_BREAKPOINT_W,
 					(unsigned long)(&ksym_selftest_dummy));
 
Signature · 1 line
1.6.2.3
#21 lore raw
In reply to Frederic Weisbecker
Quoted 6 lines · Frederic Weisbecker

Ingo,

Please pull the tracing/hw-breakpoints branch that can be found at:

git://git.kernel.org/pub/scm/linux/kernel/git/frederic/random-tracing.git
tracing/hw-breakpoints

FYI, -tip testing found a build failure (64-bit allmodcofig):

/home/mingo/tip/arch/x86/include/asm/a.out-core.h:35: error: struct thread_struct has no member named debugreg

Ingo

#22 lore raw
In reply to Frederic Weisbecker
Quoted 7 lines · Frederic Weisbecker

Ingo,

Please pull the tracing/hw-breakpoints branch that can be found at:

git://git.kernel.org/pub/scm/linux/kernel/git/frederic/random-tracing.git
tracing/hw-breakpoints

Hi Frederic, Ingo,
Here are a few concerns (roughly in decreasing order of
priority) about the perf-events integrated hw-breakpoint feature.

- Freeze the breakpoint interfaces: Owing to the many current/potential users of hw-breakpoint feature it is important to provide a stable interface to the end-user. Changes underneath the interface can be done in due course in a manner that does not affect the end-user's behaviour or function signature. The present breakpoint interface requires parameters that are best embedded in a structure for extensibility.

- Proposed migration of register allocation logic to arch-specific files from kernel/hw_breakpoint.c. This is best done early to help easy porting of code to other architectures (we have an active interest in bringing support for PPC64 and S390). If done later, it will entail additional effort in porting for each architecture.

- Fix ptrace bugs that potentially alter the semantics of ptrace.

- Bring either true system_wide support or atleast workaround the side-effects of iterative per-cpu registration using single atomic enablement of all per-cpu breakpoints. This can avoid stray exceptions which would get delivered to the end-user even for failed breakpoint requests.

Thanks,
K.Prasad

#23 lore raw
Quoted 13 lines · K.Prasad
Quoted 7 lines · Frederic Weisbecker

Ingo,

Please pull the tracing/hw-breakpoints branch that can be found at:

git://git.kernel.org/pub/scm/linux/kernel/git/frederic/random-tracing.git
tracing/hw-breakpoints

Hi Frederic, Ingo,
Here are a few concerns (roughly in decreasing order of
priority) about the perf-events integrated hw-breakpoint feature.

Quoted 7 lines

- Freeze the breakpoint interfaces: Owing to the many current/potential users of hw-breakpoint feature it is important to provide a stable interface to the end-user. Changes underneath the interface can be done in due course in a manner that does not affect the end-user's behaviour or function signature. The present breakpoint interface requires parameters that are best embedded in a structure for extensibility.

Well we have PERF_TYPE_BREAKPOINT right now. I agree that it should be finalized in some sort of extensible ABI real soon - we dont want (and dont need to) add all features that might be possible in the future.

Quoted 5 lines

- Proposed migration of register allocation logic to arch-specific files from kernel/hw_breakpoint.c. This is best done early to help easy porting of code to other architectures (we have an active interest in bringing support for PPC64 and S390). If done later, it will entail additional effort in porting for each architecture.

I think the general direction should be towards librarized common frameworks.

If an architecture wants to do something special it should either extend the core code, or, if it's too weird to be added to the core, override it via its own implementation.

Quoted 1 line

- Fix ptrace bugs that potentially alter the semantics of ptrace.

Is there a specific list of these bugs?

Quoted 5 lines

- Bring either true system_wide support or atleast workaround the side-effects of iterative per-cpu registration using single atomic enablement of all per-cpu breakpoints. This can avoid stray exceptions which would get delivered to the end-user even for failed breakpoint requests.

That can certainly be done when users of such facilities emerge. Right now we have perf and ptrace as the two users - are they affected by these problems?

Thanks,

Ingo

#24 lore raw
Quoted 16 lines · Ingo Molnar
Quoted 5 lines · K.Prasad

Hi Frederic, Ingo,
Here are a few concerns (roughly in decreasing order of
priority) about the perf-events integrated hw-breakpoint feature.

Quoted 7 lines

- Freeze the breakpoint interfaces: Owing to the many current/potential users of hw-breakpoint feature it is important to provide a stable interface to the end-user. Changes underneath the interface can be done in due course in a manner that does not affect the end-user's behaviour or function signature. The present breakpoint interface requires parameters that are best embedded in a structure for extensibility.

Quoted 4 lines

Well we have PERF_TYPE_BREAKPOINT right now. I agree that it should be finalized in some sort of extensible ABI real soon - we dont want (and dont need to) add all features that might be possible in the future.

It is not about implementing futuristic features, but provide an interface which we know isn't going to change in the near future and will be flexible to accommodate arch-specific requirements. For instance the register_wide_hw_breakpoint() has an interface as below:

struct perf_event ** register_wide_hw_breakpoint(unsigned long addr,
int len,
int type, perf_callback_t triggered, bool active)

Given the diversity seen in debug registers across processors, it isn't prudent to demand/limit the parameters required to those seen above. It can be made a part of one of perf-events' structures (with some fields in arch-specific structures) and the ABI can accept a pointer to one such structure.

In this way it would be easy to bring-in arch-specific quirks without altering the interface's signature.

Quoted 6 lines
Quoted 5 lines

- Proposed migration of register allocation logic to arch-specific files from kernel/hw_breakpoint.c. This is best done early to help easy porting of code to other architectures (we have an active interest in bringing support for PPC64 and S390). If done later, it will entail additional effort in porting for each architecture.

Quoted 7 lines

I think the general direction should be towards librarized common frameworks.

If an architecture wants to do something special it should either extend the core code, or, if it's too weird to be added to the core, override it via its own implementation.

Given the feeling that the generic set of constraints in the re-written kernel/hw_breakpoint.c cannot accommodate the needs of various processors (LKML ref:20091117013959.GG5293@nowher) and that the register allocation logic should move to arch-specific code, it is best done early to help easy porting for other archs. For instance there's already a port to PPC64 against the layered hw-breakpoint (found here: [email protected]) and one from the community for SH ([email protected]).

If such code migration is done while porting of a new architecture, then it involves making changes to every other arch on which it is previously implemented (or workaround using #ifdef).

Quoted 4 lines
Quoted 1 line

- Fix ptrace bugs that potentially alter the semantics of ptrace.

Is there a specific list of these bugs?

As pointed out in [email protected] and [email protected], ptrace requests can a) lose register slots when modifying the breakpoint addresses and b) new implementation assumes that every DR7 write to be preceded by a write on DR0-DR3 which need not be true.

Quoted 10 lines
Quoted 5 lines

- Bring either true system_wide support or atleast workaround the side-effects of iterative per-cpu registration using single atomic enablement of all per-cpu breakpoints. This can avoid stray exceptions which would get delivered to the end-user even for failed breakpoint requests.

That can certainly be done when users of such facilities emerge. Right now we have perf and ptrace as the two users - are they affected by these problems?

ksym_tracer - the ftrace plugin (kernel/trace/trace_ksym.c) using hw-breakpoints will be affected. Spurious exceptions due to partially registered breakpoint requests can be dangerous here.

Thanks,
K.Prasad

#25 lore raw
Quoted 34 lines · K.Prasad
Quoted 16 lines · Ingo Molnar
Quoted 5 lines · K.Prasad

Hi Frederic, Ingo,
Here are a few concerns (roughly in decreasing order of
priority) about the perf-events integrated hw-breakpoint feature.

Quoted 7 lines

- Freeze the breakpoint interfaces: Owing to the many current/potential users of hw-breakpoint feature it is important to provide a stable interface to the end-user. Changes underneath the interface can be done in due course in a manner that does not affect the end-user's behaviour or function signature. The present breakpoint interface requires parameters that are best embedded in a structure for extensibility.

Quoted 4 lines

Well we have PERF_TYPE_BREAKPOINT right now. I agree that it should be finalized in some sort of extensible ABI real soon - we dont want (and dont need to) add all features that might be possible in the future.

It is not about implementing futuristic features, but provide an interface which we know isn't going to change in the near future and will be flexible to accommodate arch-specific requirements. For instance the register_wide_hw_breakpoint() has an interface as below:

struct perf_event ** register_wide_hw_breakpoint(unsigned long addr,
int len,
int type, perf_callback_t triggered, bool active)

Quoted 8 lines

Given the diversity seen in debug registers across processors, it isn't prudent to demand/limit the parameters required to those seen above. It can be made a part of one of perf-events' structures (with some fields in arch-specific structures) and the ABI can accept a pointer to one such structure.

In this way it would be easy to bring-in arch-specific quirks without altering the interface's signature.

Sure, I plan to convert all these parameters into a single one:
perf_event_attr.

Quoted 23 lines
Quoted 6 lines
Quoted 5 lines

- Proposed migration of register allocation logic to arch-specific files from kernel/hw_breakpoint.c. This is best done early to help easy porting of code to other architectures (we have an active interest in bringing support for PPC64 and S390). If done later, it will entail additional effort in porting for each architecture.

Quoted 7 lines

I think the general direction should be towards librarized common frameworks.

If an architecture wants to do something special it should either extend the core code, or, if it's too weird to be added to the core, override it via its own implementation.

Given the feeling that the generic set of constraints in the re-written kernel/hw_breakpoint.c cannot accommodate the needs of various processors (LKML ref:20091117013959.GG5293@nowher) and that the register allocation logic should move to arch-specific code, it is best done early to help easy porting for other archs. For instance there's already a port to PPC64 against the layered hw-breakpoint (found here: [email protected]) and one from the community for SH ([email protected]).

Quoted 3 lines

If such code migration is done while porting of a new architecture, then it involves making changes to every other arch on which it is previously implemented (or workaround using #ifdef).

As I said, we can probably workaround it by keeping the most part in the generic code and delegate special arch things to arch constraints.

Quoted 10 lines
Quoted 4 lines
Quoted 1 line

- Fix ptrace bugs that potentially alter the semantics of ptrace.

Is there a specific list of these bugs?

As pointed out in [email protected] and [email protected], ptrace requests can a) lose register slots when modifying the breakpoint addresses and b) new implementation assumes that every DR7 write to be preceded by a write on DR0-DR3 which need not be true.

The a) case is going to be fixed.
But the b) situation must be reported as a user mistake (which is what is done currently): -EINVAL, -EIO or whatever. Enabling a breakpoint without having given an address is a userland bug.

Quoted 6 lines
Quoted 6 lines
Quoted 5 lines

- Bring either true system_wide support or atleast workaround the side-effects of iterative per-cpu registration using single atomic enablement of all per-cpu breakpoints. This can avoid stray exceptions which would get delivered to the end-user even for failed breakpoint requests.

Quoted 8 lines
Quoted 4 lines

That can certainly be done when users of such facilities emerge. Right now we have perf and ptrace as the two users - are they affected by these problems?

ksym_tracer - the ftrace plugin (kernel/trace/trace_ksym.c) using hw-breakpoints will be affected. Spurious exceptions due to partially registered breakpoint requests can be dangerous here.

Will be fixed too.

#26 lore raw
Quoted 5 lines · Frederic Weisbecker
Quoted 4 lines · K.Prasad
Quoted 3 lines · Ingo Molnar

* K.Prasad <[email protected]> wrote:

<snipped>

Quoted 22 lines
Quoted 22 lines
Quoted 6 lines
Quoted 5 lines

- Proposed migration of register allocation logic to arch-specific files from kernel/hw_breakpoint.c. This is best done early to help easy porting of code to other architectures (we have an active interest in bringing support for PPC64 and S390). If done later, it will entail additional effort in porting for each architecture.

Quoted 7 lines

I think the general direction should be towards librarized common frameworks.

If an architecture wants to do something special it should either extend the core code, or, if it's too weird to be added to the core, override it via its own implementation.

Given the feeling that the generic set of constraints in the re-written kernel/hw_breakpoint.c cannot accommodate the needs of various processors (LKML ref:20091117013959.GG5293@nowher) and that the register allocation logic should move to arch-specific code, it is best done early to help easy porting for other archs. For instance there's already a port to PPC64 against the layered hw-breakpoint (found here: [email protected]) and one from the community for SH ([email protected]).

Quoted 8 lines
Quoted 3 lines

If such code migration is done while porting of a new architecture, then it involves making changes to every other arch on which it is previously implemented (or workaround using #ifdef).

As I said, we can probably workaround it by keeping the most part in the generic code and delegate special arch things to arch constraints.

I think the register_<> interfaces can become wrappers around functions that do the following:

- arch_validate(): Validate request by invoking an arch-dependant routine. Proceed if returned valid.
- arch-specific debugreg availability: Do something like if (arch_hw_breakpoint_availabile())

	bp = perf_event_create_kernel_counter();
  perf_event_create_kernel_counter()--->arch_install_hw_breakpoint();

This way, all book-keeping related work (no. of pinned/flexible/per-cpu) will be moved to arch-specific files (will be helpful for PPC Book-E implementation having two types of debug registers). Every new architecture that intends to port to the new hw-breakpoint implementation must define their arch_validate(), arch_hw_breakpoint_available() and an arch_install_hw_breakpoint(), while the hw-breakpoint code will be flexible enough to extend itself to each of these archs.

This implementation would be even superior (in terms of extensibility) to even the older hw-breakpoint layer implementation (despite it providing a working layer for x86 and PPC64).

Quoted 11 lines
Quoted 10 lines
Quoted 4 lines
Quoted 1 line

- Fix ptrace bugs that potentially alter the semantics of ptrace.

Is there a specific list of these bugs?

As pointed out in [email protected] and [email protected], ptrace requests can a) lose register slots when modifying the breakpoint addresses and b) new implementation assumes that every DR7 write to be preceded by a write on DR0-DR3 which need not be true.

Quoted 5 lines

The a) case is going to be fixed.
But the b) situation must be reported as a user mistake (which is what is done currently): -EINVAL, -EIO or whatever. Enabling a breakpoint without having given an address is a userland bug.

b) need not be a user mistake always (except perhaps the first time). As I mentioned here [email protected], DR7 enable/disable without a DR0-DR3 write can be done by the user through ptrace for optimising the number of write operations (and hence ptrace syscalls).

Consider the following steps which is entirely valid (in mainline ptrace) but which would fail if assumed that a DR0-DR3 write precedes a DR7 write:
i) Set address on DR0
ii) Enable bits corresponding to DR0 in DR7
iii) Disable DR0 bits in DR7
iv) Re-enable DR0 bits in DR7

Thanks,
K.Prasad

#27 lore raw
Quoted 8 lines · K.Prasad

I think the register_<> interfaces can become wrappers around functions that do the following:

- arch_validate(): Validate request by invoking an arch-dependant routine. Proceed if returned valid.
- arch-specific debugreg availability: Do something like if (arch_hw_breakpoint_availabile())

	bp = perf_event_create_kernel_counter();

The current state is settled for Bp Api clients (perf_event_create_kernel_counter()) and perf clients (perf syscall) to have the same endpoint, which is the arch_validate() + reg reservation. This is already what is done. It's just done at the pmu level.

I don't understand your point.

Quoted 1 line
  perf_event_create_kernel_counter()--->arch_install_hw_breakpoint();

But this is what is done, when perf_event_alloc() get the breakpoint pmu.

Quoted 8 lines

This way, all book-keeping related work (no. of pinned/flexible/per-cpu) will be moved to arch-specific files (will be helpful for PPC Book-E implementation having two types of debug registers). Every new architecture that intends to port to the new hw-breakpoint implementation must define their arch_validate(), arch_hw_breakpoint_available() and an arch_install_hw_breakpoint(), while the hw-breakpoint code will be flexible enough to extend itself to each of these archs.

We just need to move reserve_bp_slot() and release_bp_slot() in arch code then.

But I would prefer to move more efforts in generalizing what can generalized in the register reservation topic, and have the smallest possible part in arch code.

Quoted 3 lines

This implementation would be even superior (in terms of extensibility) to even the older hw-breakpoint layer implementation (despite it providing a working layer for x86 and PPC64).

The older breakpoint API was very tight to x86. It had a single linear breakpoint refcounting that wasn't handling different natures of breakpoint registers (different registers between instruction and data). Neither was this linear refcounting handling the fact a single cpu could share a single breakpoint register between hardware threads.

So, no I don't think it was providing a working layer for PPC64.

That said the current state of the constraints sucks :) as it is too much tight to x86 too.

But I want to avoid the trap of moving all the constraint checks to the arch. If possible, I would like to extract the arch specificity only.
It's possible that in the case of PPC64, we want a totally different constraint check, but what about other archs? Do they have very close needs than x86 or another bunck of tricky constraints? In the former case, I would prefer to have the current constraints defined as __weak and let the tricky archs implement their own constraints. That will only work if the _tricky_ arch are a minority of course.

Quoted 12 lines
Quoted 11 lines
Quoted 5 lines

As pointed out in [email protected] and [email protected], ptrace requests can a) lose register slots when modifying the breakpoint addresses and b) new implementation assumes that every DR7 write to be preceded by a write on DR0-DR3 which need not be true.

The a) case is going to be fixed.
But the b) situation must be reported as a user mistake (which is what is done currently): -EINVAL, -EIO or whatever. Enabling a breakpoint without having given an address is a userland bug.

Quoted 4 lines

b) need not be a user mistake always (except perhaps the first time). As I mentioned here [email protected], DR7 enable/disable without a DR0-DR3 write can be done by the user through ptrace for optimising the number of write operations (and hence ptrace syscalls).

I really think this is a wrong workflow as the address register is undefined.

I think this is a user bug. In the current upstream state, I guess the addr debugreg are initialized to 0. So is this going to set a breakpoint to 0?

I doubt there are much user app that rely on such buggy behaviour, but I can probably support that by creating a temporary disabled breakpoint in this case.

Quoted 6 lines

Consider the following steps which is entirely valid (in mainline ptrace) but which would fail if assumed that a DR0-DR3 write precedes a DR7 write:
i) Set address on DR0
ii) Enable bits corresponding to DR0 in DR7
iii) Disable DR0 bits in DR7
iv) Re-enable DR0 bits in DR7

Agreed. I need to fix this. I thought you were talking about enabling dr0 in dr7 without having ever set dr0.

Ok I'll fix this case.

Thanks.

#28 lore raw
In reply to Ingo Molnar
Quoted 24 lines · Ingo Molnar
Quoted 13 lines · K.Prasad
Quoted 7 lines · Frederic Weisbecker

Ingo,

Please pull the tracing/hw-breakpoints branch that can be found at:

git://git.kernel.org/pub/scm/linux/kernel/git/frederic/random-tracing.git
tracing/hw-breakpoints

Hi Frederic, Ingo,
Here are a few concerns (roughly in decreasing order of
priority) about the perf-events integrated hw-breakpoint feature.

Quoted 7 lines

- Freeze the breakpoint interfaces: Owing to the many current/potential users of hw-breakpoint feature it is important to provide a stable interface to the end-user. Changes underneath the interface can be done in due course in a manner that does not affect the end-user's behaviour or function signature. The present breakpoint interface requires parameters that are best embedded in a structure for extensibility.

Quoted 3 lines

Well we have PERF_TYPE_BREAKPOINT right now. I agree that it should be finalized in some sort of extensible ABI real soon - we dont want (and dont need to) add all features that might be possible in the future.

Concerning in-kernel users, it's not a worry. The in-kernel api is not supposed to be stable and shouldn't, especially for such a very young facility like generic breakpoints.

But you're right, I don't want it to be a pain to port in other architectures and the current breakpoint api function signatures are too tight to the x86 needs. I'm going to change the signature of the register_* functions so that they actually take a perf_event_attr struct (and this one must be generic for breakpoints across archs).

But the emergency is really in the struct perf_event_attr structure interface.
We need to define a generic interface for it soon as it will be exposed to userland and then fixed on the rock, although the current existing fields seem to be mandatory and if this interface needs to be changed, it should be about new fields to append, but still, and we never know...

I would really appreciate any help in this regard as I don't know the implementation of breakpoints in other architectures. Obviously, I could parse the others $(ls arch/ | wc -l) archs documentations about debug registers. But that won't just scale as it is going to give me a global and erratic view of the whole needs, and I believe the archs maintainers would point me out the subtle things I'm going to miss, as Benjamin, Paul and you did lately concerning shared address registers among hardware threads in a single cpu, separate registers between watchpoints and exec-breakpoint... in ppc.

First of all, I guess we should split out the address field into start and end (both should be equal in the x86 version) so that we can support breakpoints in address ranges.

There is also a "compare" thing in power-pc.

Quoted 6 lines
Quoted 5 lines

- Proposed migration of register allocation logic to arch-specific files from kernel/hw_breakpoint.c. This is best done early to help easy porting of code to other architectures (we have an active interest in bringing support for PPC64 and S390). If done later, it will entail additional effort in porting for each architecture.

Quoted 6 lines

I think the general direction should be towards librarized common frameworks.

If an architecture wants to do something special it should either extend the core code, or, if it's too weird to be added to the core, override it via its own implementation.

The power pc implementation is really completely different from x86, to the point that it would be hard to gather a common library of constraints for both.

In ppc, address registers are shared among hardware threads in a same cpu (which is seen as several cpus by the core), but can be enabled in the hardware threads of our choice. Exec and Read/write breakpoint registers are not the same, etc...

Well, perhaps we can do something generic by putting a part of the constraints to the arch code.

Quoted 4 lines
Quoted 2 lines

- Fix ptrace bugs that potentially alter the semantics of ptrace.

Is there a specific list of these bugs?

Prasad, I still have your reviews in mind :)
I will fix these soon.

Thanks.

Quoted 9 lines
Quoted 5 lines

- Bring either true system_wide support or atleast workaround the side-effects of iterative per-cpu registration using single atomic enablement of all per-cpu breakpoints. This can avoid stray exceptions which would get delivered to the end-user even for failed breakpoint requests.

That can certainly be done when users of such facilities emerge. Right now we have perf and ptrace as the two users - are they affected by these problems?

#29 lore raw
Quoted 8 lines · Frederic Weisbecker
Quoted 4 lines

Well we have PERF_TYPE_BREAKPOINT right now. I agree that it should be finalized in some sort of extensible ABI real soon - we dont want (and dont need to) add all features that might be possible in the future.

Concerning in-kernel users, it's not a worry. The in-kernel api is not supposed to be stable and shouldn't, especially for such a very young facility like generic breakpoints.

in-kernel we dont worry about indeed (we can change and iterate APIs freely there) - it is PERF_TYPE_BREAKPOINT that we need to make sure is extensible enough.

Thanks,

Ingo