xref: /openbmc/linux/kernel/events/hw_breakpoint.c (revision 045f77ba)
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15  *
16  * Copyright (C) 2007 Alan Stern
17  * Copyright (C) IBM Corporation, 2009
18  * Copyright (C) 2009, Frederic Weisbecker <fweisbec@gmail.com>
19  *
20  * Thanks to Ingo Molnar for his many suggestions.
21  *
22  * Authors: Alan Stern <stern@rowland.harvard.edu>
23  *          K.Prasad <prasad@linux.vnet.ibm.com>
24  *          Frederic Weisbecker <fweisbec@gmail.com>
25  */
26 
27 /*
28  * HW_breakpoint: a unified kernel/user-space hardware breakpoint facility,
29  * using the CPU's debug registers.
30  * This file contains the arch-independent routines.
31  */
32 
33 #include <linux/irqflags.h>
34 #include <linux/kallsyms.h>
35 #include <linux/notifier.h>
36 #include <linux/kprobes.h>
37 #include <linux/kdebug.h>
38 #include <linux/kernel.h>
39 #include <linux/module.h>
40 #include <linux/percpu.h>
41 #include <linux/sched.h>
42 #include <linux/init.h>
43 #include <linux/slab.h>
44 #include <linux/list.h>
45 #include <linux/cpu.h>
46 #include <linux/smp.h>
47 #include <linux/bug.h>
48 
49 #include <linux/hw_breakpoint.h>
50 /*
51  * Constraints data
52  */
53 struct bp_cpuinfo {
54 	/* Number of pinned cpu breakpoints in a cpu */
55 	unsigned int	cpu_pinned;
56 	/* tsk_pinned[n] is the number of tasks having n+1 breakpoints */
57 	unsigned int	*tsk_pinned;
58 	/* Number of non-pinned cpu/task breakpoints in a cpu */
59 	unsigned int	flexible; /* XXX: placeholder, see fetch_this_slot() */
60 };
61 
62 static DEFINE_PER_CPU(struct bp_cpuinfo, bp_cpuinfo[TYPE_MAX]);
63 static int nr_slots[TYPE_MAX];
64 
65 static struct bp_cpuinfo *get_bp_info(int cpu, enum bp_type_idx type)
66 {
67 	return per_cpu_ptr(bp_cpuinfo + type, cpu);
68 }
69 
70 /* Keep track of the breakpoints attached to tasks */
71 static LIST_HEAD(bp_task_head);
72 
73 static int constraints_initialized;
74 
75 /* Gather the number of total pinned and un-pinned bp in a cpuset */
76 struct bp_busy_slots {
77 	unsigned int pinned;
78 	unsigned int flexible;
79 };
80 
81 /* Serialize accesses to the above constraints */
82 static DEFINE_MUTEX(nr_bp_mutex);
83 
84 __weak int hw_breakpoint_weight(struct perf_event *bp)
85 {
86 	return 1;
87 }
88 
89 static inline enum bp_type_idx find_slot_idx(u64 bp_type)
90 {
91 	if (bp_type & HW_BREAKPOINT_RW)
92 		return TYPE_DATA;
93 
94 	return TYPE_INST;
95 }
96 
97 /*
98  * Report the maximum number of pinned breakpoints a task
99  * have in this cpu
100  */
101 static unsigned int max_task_bp_pinned(int cpu, enum bp_type_idx type)
102 {
103 	unsigned int *tsk_pinned = get_bp_info(cpu, type)->tsk_pinned;
104 	int i;
105 
106 	for (i = nr_slots[type] - 1; i >= 0; i--) {
107 		if (tsk_pinned[i] > 0)
108 			return i + 1;
109 	}
110 
111 	return 0;
112 }
113 
114 /*
115  * Count the number of breakpoints of the same type and same task.
116  * The given event must be not on the list.
117  */
118 static int task_bp_pinned(int cpu, struct perf_event *bp, enum bp_type_idx type)
119 {
120 	struct task_struct *tsk = bp->hw.target;
121 	struct perf_event *iter;
122 	int count = 0;
123 
124 	list_for_each_entry(iter, &bp_task_head, hw.bp_list) {
125 		if (iter->hw.target == tsk &&
126 		    find_slot_idx(iter->attr.bp_type) == type &&
127 		    (iter->cpu < 0 || cpu == iter->cpu))
128 			count += hw_breakpoint_weight(iter);
129 	}
130 
131 	return count;
132 }
133 
134 static const struct cpumask *cpumask_of_bp(struct perf_event *bp)
135 {
136 	if (bp->cpu >= 0)
137 		return cpumask_of(bp->cpu);
138 	return cpu_possible_mask;
139 }
140 
141 /*
142  * Report the number of pinned/un-pinned breakpoints we have in
143  * a given cpu (cpu > -1) or in all of them (cpu = -1).
144  */
145 static void
146 fetch_bp_busy_slots(struct bp_busy_slots *slots, struct perf_event *bp,
147 		    enum bp_type_idx type)
148 {
149 	const struct cpumask *cpumask = cpumask_of_bp(bp);
150 	int cpu;
151 
152 	for_each_cpu(cpu, cpumask) {
153 		struct bp_cpuinfo *info = get_bp_info(cpu, type);
154 		int nr;
155 
156 		nr = info->cpu_pinned;
157 		if (!bp->hw.target)
158 			nr += max_task_bp_pinned(cpu, type);
159 		else
160 			nr += task_bp_pinned(cpu, bp, type);
161 
162 		if (nr > slots->pinned)
163 			slots->pinned = nr;
164 
165 		nr = info->flexible;
166 		if (nr > slots->flexible)
167 			slots->flexible = nr;
168 	}
169 }
170 
171 /*
172  * For now, continue to consider flexible as pinned, until we can
173  * ensure no flexible event can ever be scheduled before a pinned event
174  * in a same cpu.
175  */
176 static void
177 fetch_this_slot(struct bp_busy_slots *slots, int weight)
178 {
179 	slots->pinned += weight;
180 }
181 
182 /*
183  * Add a pinned breakpoint for the given task in our constraint table
184  */
185 static void toggle_bp_task_slot(struct perf_event *bp, int cpu,
186 				enum bp_type_idx type, int weight)
187 {
188 	unsigned int *tsk_pinned = get_bp_info(cpu, type)->tsk_pinned;
189 	int old_idx, new_idx;
190 
191 	old_idx = task_bp_pinned(cpu, bp, type) - 1;
192 	new_idx = old_idx + weight;
193 
194 	if (old_idx >= 0)
195 		tsk_pinned[old_idx]--;
196 	if (new_idx >= 0)
197 		tsk_pinned[new_idx]++;
198 }
199 
200 /*
201  * Add/remove the given breakpoint in our constraint table
202  */
203 static void
204 toggle_bp_slot(struct perf_event *bp, bool enable, enum bp_type_idx type,
205 	       int weight)
206 {
207 	const struct cpumask *cpumask = cpumask_of_bp(bp);
208 	int cpu;
209 
210 	if (!enable)
211 		weight = -weight;
212 
213 	/* Pinned counter cpu profiling */
214 	if (!bp->hw.target) {
215 		get_bp_info(bp->cpu, type)->cpu_pinned += weight;
216 		return;
217 	}
218 
219 	/* Pinned counter task profiling */
220 	for_each_cpu(cpu, cpumask)
221 		toggle_bp_task_slot(bp, cpu, type, weight);
222 
223 	if (enable)
224 		list_add_tail(&bp->hw.bp_list, &bp_task_head);
225 	else
226 		list_del(&bp->hw.bp_list);
227 }
228 
229 /*
230  * Function to perform processor-specific cleanup during unregistration
231  */
232 __weak void arch_unregister_hw_breakpoint(struct perf_event *bp)
233 {
234 	/*
235 	 * A weak stub function here for those archs that don't define
236 	 * it inside arch/.../kernel/hw_breakpoint.c
237 	 */
238 }
239 
240 /*
241  * Contraints to check before allowing this new breakpoint counter:
242  *
243  *  == Non-pinned counter == (Considered as pinned for now)
244  *
245  *   - If attached to a single cpu, check:
246  *
247  *       (per_cpu(info->flexible, cpu) || (per_cpu(info->cpu_pinned, cpu)
248  *           + max(per_cpu(info->tsk_pinned, cpu)))) < HBP_NUM
249  *
250  *       -> If there are already non-pinned counters in this cpu, it means
251  *          there is already a free slot for them.
252  *          Otherwise, we check that the maximum number of per task
253  *          breakpoints (for this cpu) plus the number of per cpu breakpoint
254  *          (for this cpu) doesn't cover every registers.
255  *
256  *   - If attached to every cpus, check:
257  *
258  *       (per_cpu(info->flexible, *) || (max(per_cpu(info->cpu_pinned, *))
259  *           + max(per_cpu(info->tsk_pinned, *)))) < HBP_NUM
260  *
261  *       -> This is roughly the same, except we check the number of per cpu
262  *          bp for every cpu and we keep the max one. Same for the per tasks
263  *          breakpoints.
264  *
265  *
266  * == Pinned counter ==
267  *
268  *   - If attached to a single cpu, check:
269  *
270  *       ((per_cpu(info->flexible, cpu) > 1) + per_cpu(info->cpu_pinned, cpu)
271  *            + max(per_cpu(info->tsk_pinned, cpu))) < HBP_NUM
272  *
273  *       -> Same checks as before. But now the info->flexible, if any, must keep
274  *          one register at least (or they will never be fed).
275  *
276  *   - If attached to every cpus, check:
277  *
278  *       ((per_cpu(info->flexible, *) > 1) + max(per_cpu(info->cpu_pinned, *))
279  *            + max(per_cpu(info->tsk_pinned, *))) < HBP_NUM
280  */
281 static int __reserve_bp_slot(struct perf_event *bp, u64 bp_type)
282 {
283 	struct bp_busy_slots slots = {0};
284 	enum bp_type_idx type;
285 	int weight;
286 
287 	/* We couldn't initialize breakpoint constraints on boot */
288 	if (!constraints_initialized)
289 		return -ENOMEM;
290 
291 	/* Basic checks */
292 	if (bp_type == HW_BREAKPOINT_EMPTY ||
293 	    bp_type == HW_BREAKPOINT_INVALID)
294 		return -EINVAL;
295 
296 	type = find_slot_idx(bp_type);
297 	weight = hw_breakpoint_weight(bp);
298 
299 	fetch_bp_busy_slots(&slots, bp, type);
300 	/*
301 	 * Simulate the addition of this breakpoint to the constraints
302 	 * and see the result.
303 	 */
304 	fetch_this_slot(&slots, weight);
305 
306 	/* Flexible counters need to keep at least one slot */
307 	if (slots.pinned + (!!slots.flexible) > nr_slots[type])
308 		return -ENOSPC;
309 
310 	toggle_bp_slot(bp, true, type, weight);
311 
312 	return 0;
313 }
314 
315 int reserve_bp_slot(struct perf_event *bp)
316 {
317 	int ret;
318 
319 	mutex_lock(&nr_bp_mutex);
320 
321 	ret = __reserve_bp_slot(bp, bp->attr.bp_type);
322 
323 	mutex_unlock(&nr_bp_mutex);
324 
325 	return ret;
326 }
327 
328 static void __release_bp_slot(struct perf_event *bp, u64 bp_type)
329 {
330 	enum bp_type_idx type;
331 	int weight;
332 
333 	type = find_slot_idx(bp_type);
334 	weight = hw_breakpoint_weight(bp);
335 	toggle_bp_slot(bp, false, type, weight);
336 }
337 
338 void release_bp_slot(struct perf_event *bp)
339 {
340 	mutex_lock(&nr_bp_mutex);
341 
342 	arch_unregister_hw_breakpoint(bp);
343 	__release_bp_slot(bp, bp->attr.bp_type);
344 
345 	mutex_unlock(&nr_bp_mutex);
346 }
347 
348 static int __modify_bp_slot(struct perf_event *bp, u64 old_type, u64 new_type)
349 {
350 	int err;
351 
352 	__release_bp_slot(bp, old_type);
353 
354 	err = __reserve_bp_slot(bp, new_type);
355 	if (err) {
356 		/*
357 		 * Reserve the old_type slot back in case
358 		 * there's no space for the new type.
359 		 *
360 		 * This must succeed, because we just released
361 		 * the old_type slot in the __release_bp_slot
362 		 * call above. If not, something is broken.
363 		 */
364 		WARN_ON(__reserve_bp_slot(bp, old_type));
365 	}
366 
367 	return err;
368 }
369 
370 static int modify_bp_slot(struct perf_event *bp, u64 old_type, u64 new_type)
371 {
372 	int ret;
373 
374 	mutex_lock(&nr_bp_mutex);
375 	ret = __modify_bp_slot(bp, old_type, new_type);
376 	mutex_unlock(&nr_bp_mutex);
377 	return ret;
378 }
379 
380 /*
381  * Allow the kernel debugger to reserve breakpoint slots without
382  * taking a lock using the dbg_* variant of for the reserve and
383  * release breakpoint slots.
384  */
385 int dbg_reserve_bp_slot(struct perf_event *bp)
386 {
387 	if (mutex_is_locked(&nr_bp_mutex))
388 		return -1;
389 
390 	return __reserve_bp_slot(bp, bp->attr.bp_type);
391 }
392 
393 int dbg_release_bp_slot(struct perf_event *bp)
394 {
395 	if (mutex_is_locked(&nr_bp_mutex))
396 		return -1;
397 
398 	__release_bp_slot(bp, bp->attr.bp_type);
399 
400 	return 0;
401 }
402 
403 static int hw_breakpoint_parse(struct perf_event *bp,
404 			       const struct perf_event_attr *attr,
405 			       struct arch_hw_breakpoint *hw)
406 {
407 	int err;
408 
409 	err = hw_breakpoint_arch_parse(bp, attr, hw);
410 	if (err)
411 		return err;
412 
413 	if (arch_check_bp_in_kernelspace(hw)) {
414 		if (attr->exclude_kernel)
415 			return -EINVAL;
416 		/*
417 		 * Don't let unprivileged users set a breakpoint in the trap
418 		 * path to avoid trap recursion attacks.
419 		 */
420 		if (!capable(CAP_SYS_ADMIN))
421 			return -EPERM;
422 	}
423 
424 	return 0;
425 }
426 
427 int register_perf_hw_breakpoint(struct perf_event *bp)
428 {
429 	struct arch_hw_breakpoint hw;
430 	int err;
431 
432 	err = reserve_bp_slot(bp);
433 	if (err)
434 		return err;
435 
436 	err = hw_breakpoint_parse(bp, &bp->attr, &hw);
437 	if (err) {
438 		release_bp_slot(bp);
439 		return err;
440 	}
441 
442 	bp->hw.info = hw;
443 
444 	return 0;
445 }
446 
447 /**
448  * register_user_hw_breakpoint - register a hardware breakpoint for user space
449  * @attr: breakpoint attributes
450  * @triggered: callback to trigger when we hit the breakpoint
451  * @tsk: pointer to 'task_struct' of the process to which the address belongs
452  */
453 struct perf_event *
454 register_user_hw_breakpoint(struct perf_event_attr *attr,
455 			    perf_overflow_handler_t triggered,
456 			    void *context,
457 			    struct task_struct *tsk)
458 {
459 	return perf_event_create_kernel_counter(attr, -1, tsk, triggered,
460 						context);
461 }
462 EXPORT_SYMBOL_GPL(register_user_hw_breakpoint);
463 
464 static void hw_breakpoint_copy_attr(struct perf_event_attr *to,
465 				    struct perf_event_attr *from)
466 {
467 	to->bp_addr = from->bp_addr;
468 	to->bp_type = from->bp_type;
469 	to->bp_len  = from->bp_len;
470 	to->disabled = from->disabled;
471 }
472 
473 int
474 modify_user_hw_breakpoint_check(struct perf_event *bp, struct perf_event_attr *attr,
475 			        bool check)
476 {
477 	struct arch_hw_breakpoint hw;
478 	int err;
479 
480 	err = hw_breakpoint_parse(bp, attr, &hw);
481 	if (err)
482 		return err;
483 
484 	if (check) {
485 		struct perf_event_attr old_attr;
486 
487 		old_attr = bp->attr;
488 		hw_breakpoint_copy_attr(&old_attr, attr);
489 		if (memcmp(&old_attr, attr, sizeof(*attr)))
490 			return -EINVAL;
491 	}
492 
493 	if (bp->attr.bp_type != attr->bp_type) {
494 		err = modify_bp_slot(bp, bp->attr.bp_type, attr->bp_type);
495 		if (err)
496 			return err;
497 	}
498 
499 	hw_breakpoint_copy_attr(&bp->attr, attr);
500 	bp->hw.info = hw;
501 
502 	return 0;
503 }
504 
505 /**
506  * modify_user_hw_breakpoint - modify a user-space hardware breakpoint
507  * @bp: the breakpoint structure to modify
508  * @attr: new breakpoint attributes
509  */
510 int modify_user_hw_breakpoint(struct perf_event *bp, struct perf_event_attr *attr)
511 {
512 	/*
513 	 * modify_user_hw_breakpoint can be invoked with IRQs disabled and hence it
514 	 * will not be possible to raise IPIs that invoke __perf_event_disable.
515 	 * So call the function directly after making sure we are targeting the
516 	 * current task.
517 	 */
518 	if (irqs_disabled() && bp->ctx && bp->ctx->task == current)
519 		perf_event_disable_local(bp);
520 	else
521 		perf_event_disable(bp);
522 
523 	if (!attr->disabled) {
524 		int err = modify_user_hw_breakpoint_check(bp, attr, false);
525 
526 		if (err)
527 			return err;
528 		perf_event_enable(bp);
529 		bp->attr.disabled = 0;
530 	}
531 	return 0;
532 }
533 EXPORT_SYMBOL_GPL(modify_user_hw_breakpoint);
534 
535 /**
536  * unregister_hw_breakpoint - unregister a user-space hardware breakpoint
537  * @bp: the breakpoint structure to unregister
538  */
539 void unregister_hw_breakpoint(struct perf_event *bp)
540 {
541 	if (!bp)
542 		return;
543 	perf_event_release_kernel(bp);
544 }
545 EXPORT_SYMBOL_GPL(unregister_hw_breakpoint);
546 
547 /**
548  * register_wide_hw_breakpoint - register a wide breakpoint in the kernel
549  * @attr: breakpoint attributes
550  * @triggered: callback to trigger when we hit the breakpoint
551  *
552  * @return a set of per_cpu pointers to perf events
553  */
554 struct perf_event * __percpu *
555 register_wide_hw_breakpoint(struct perf_event_attr *attr,
556 			    perf_overflow_handler_t triggered,
557 			    void *context)
558 {
559 	struct perf_event * __percpu *cpu_events, *bp;
560 	long err = 0;
561 	int cpu;
562 
563 	cpu_events = alloc_percpu(typeof(*cpu_events));
564 	if (!cpu_events)
565 		return (void __percpu __force *)ERR_PTR(-ENOMEM);
566 
567 	get_online_cpus();
568 	for_each_online_cpu(cpu) {
569 		bp = perf_event_create_kernel_counter(attr, cpu, NULL,
570 						      triggered, context);
571 		if (IS_ERR(bp)) {
572 			err = PTR_ERR(bp);
573 			break;
574 		}
575 
576 		per_cpu(*cpu_events, cpu) = bp;
577 	}
578 	put_online_cpus();
579 
580 	if (likely(!err))
581 		return cpu_events;
582 
583 	unregister_wide_hw_breakpoint(cpu_events);
584 	return (void __percpu __force *)ERR_PTR(err);
585 }
586 EXPORT_SYMBOL_GPL(register_wide_hw_breakpoint);
587 
588 /**
589  * unregister_wide_hw_breakpoint - unregister a wide breakpoint in the kernel
590  * @cpu_events: the per cpu set of events to unregister
591  */
592 void unregister_wide_hw_breakpoint(struct perf_event * __percpu *cpu_events)
593 {
594 	int cpu;
595 
596 	for_each_possible_cpu(cpu)
597 		unregister_hw_breakpoint(per_cpu(*cpu_events, cpu));
598 
599 	free_percpu(cpu_events);
600 }
601 EXPORT_SYMBOL_GPL(unregister_wide_hw_breakpoint);
602 
603 static struct notifier_block hw_breakpoint_exceptions_nb = {
604 	.notifier_call = hw_breakpoint_exceptions_notify,
605 	/* we need to be notified first */
606 	.priority = 0x7fffffff
607 };
608 
609 static void bp_perf_event_destroy(struct perf_event *event)
610 {
611 	release_bp_slot(event);
612 }
613 
614 static int hw_breakpoint_event_init(struct perf_event *bp)
615 {
616 	int err;
617 
618 	if (bp->attr.type != PERF_TYPE_BREAKPOINT)
619 		return -ENOENT;
620 
621 	/*
622 	 * no branch sampling for breakpoint events
623 	 */
624 	if (has_branch_stack(bp))
625 		return -EOPNOTSUPP;
626 
627 	err = register_perf_hw_breakpoint(bp);
628 	if (err)
629 		return err;
630 
631 	bp->destroy = bp_perf_event_destroy;
632 
633 	return 0;
634 }
635 
636 static int hw_breakpoint_add(struct perf_event *bp, int flags)
637 {
638 	if (!(flags & PERF_EF_START))
639 		bp->hw.state = PERF_HES_STOPPED;
640 
641 	if (is_sampling_event(bp)) {
642 		bp->hw.last_period = bp->hw.sample_period;
643 		perf_swevent_set_period(bp);
644 	}
645 
646 	return arch_install_hw_breakpoint(bp);
647 }
648 
649 static void hw_breakpoint_del(struct perf_event *bp, int flags)
650 {
651 	arch_uninstall_hw_breakpoint(bp);
652 }
653 
654 static void hw_breakpoint_start(struct perf_event *bp, int flags)
655 {
656 	bp->hw.state = 0;
657 }
658 
659 static void hw_breakpoint_stop(struct perf_event *bp, int flags)
660 {
661 	bp->hw.state = PERF_HES_STOPPED;
662 }
663 
664 static struct pmu perf_breakpoint = {
665 	.task_ctx_nr	= perf_sw_context, /* could eventually get its own */
666 
667 	.event_init	= hw_breakpoint_event_init,
668 	.add		= hw_breakpoint_add,
669 	.del		= hw_breakpoint_del,
670 	.start		= hw_breakpoint_start,
671 	.stop		= hw_breakpoint_stop,
672 	.read		= hw_breakpoint_pmu_read,
673 };
674 
675 int __init init_hw_breakpoint(void)
676 {
677 	int cpu, err_cpu;
678 	int i;
679 
680 	for (i = 0; i < TYPE_MAX; i++)
681 		nr_slots[i] = hw_breakpoint_slots(i);
682 
683 	for_each_possible_cpu(cpu) {
684 		for (i = 0; i < TYPE_MAX; i++) {
685 			struct bp_cpuinfo *info = get_bp_info(cpu, i);
686 
687 			info->tsk_pinned = kcalloc(nr_slots[i], sizeof(int),
688 							GFP_KERNEL);
689 			if (!info->tsk_pinned)
690 				goto err_alloc;
691 		}
692 	}
693 
694 	constraints_initialized = 1;
695 
696 	perf_pmu_register(&perf_breakpoint, "breakpoint", PERF_TYPE_BREAKPOINT);
697 
698 	return register_die_notifier(&hw_breakpoint_exceptions_nb);
699 
700  err_alloc:
701 	for_each_possible_cpu(err_cpu) {
702 		for (i = 0; i < TYPE_MAX; i++)
703 			kfree(get_bp_info(err_cpu, i)->tsk_pinned);
704 		if (err_cpu == cpu)
705 			break;
706 	}
707 
708 	return -ENOMEM;
709 }
710 
711 
712