Merge branch 'for-linus' into for-next
[deliverable/linux.git] / arch / x86 / kernel / cpu / perf_event.c
1 /*
2 * Performance events x86 architecture code
3 *
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2009 Jaswinder Singh Rajput
7 * Copyright (C) 2009 Advanced Micro Devices, Inc., Robert Richter
8 * Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
9 * Copyright (C) 2009 Intel Corporation, <markus.t.metzger@intel.com>
10 * Copyright (C) 2009 Google, Inc., Stephane Eranian
11 *
12 * For licencing details see kernel-base/COPYING
13 */
14
15 #include <linux/perf_event.h>
16 #include <linux/capability.h>
17 #include <linux/notifier.h>
18 #include <linux/hardirq.h>
19 #include <linux/kprobes.h>
20 #include <linux/module.h>
21 #include <linux/kdebug.h>
22 #include <linux/sched.h>
23 #include <linux/uaccess.h>
24 #include <linux/slab.h>
25 #include <linux/cpu.h>
26 #include <linux/bitops.h>
27 #include <linux/device.h>
28
29 #include <asm/apic.h>
30 #include <asm/stacktrace.h>
31 #include <asm/nmi.h>
32 #include <asm/smp.h>
33 #include <asm/alternative.h>
34 #include <asm/timer.h>
35 #include <asm/desc.h>
36 #include <asm/ldt.h>
37
38 #include "perf_event.h"
39
40 struct x86_pmu x86_pmu __read_mostly;
41
42 DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
43 .enabled = 1,
44 };
45
46 u64 __read_mostly hw_cache_event_ids
47 [PERF_COUNT_HW_CACHE_MAX]
48 [PERF_COUNT_HW_CACHE_OP_MAX]
49 [PERF_COUNT_HW_CACHE_RESULT_MAX];
50 u64 __read_mostly hw_cache_extra_regs
51 [PERF_COUNT_HW_CACHE_MAX]
52 [PERF_COUNT_HW_CACHE_OP_MAX]
53 [PERF_COUNT_HW_CACHE_RESULT_MAX];
54
55 /*
56 * Propagate event elapsed time into the generic event.
57 * Can only be executed on the CPU where the event is active.
58 * Returns the delta events processed.
59 */
60 u64 x86_perf_event_update(struct perf_event *event)
61 {
62 struct hw_perf_event *hwc = &event->hw;
63 int shift = 64 - x86_pmu.cntval_bits;
64 u64 prev_raw_count, new_raw_count;
65 int idx = hwc->idx;
66 s64 delta;
67
68 if (idx == INTEL_PMC_IDX_FIXED_BTS)
69 return 0;
70
71 /*
72 * Careful: an NMI might modify the previous event value.
73 *
74 * Our tactic to handle this is to first atomically read and
75 * exchange a new raw count - then add that new-prev delta
76 * count to the generic event atomically:
77 */
78 again:
79 prev_raw_count = local64_read(&hwc->prev_count);
80 rdpmcl(hwc->event_base_rdpmc, new_raw_count);
81
82 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
83 new_raw_count) != prev_raw_count)
84 goto again;
85
86 /*
87 * Now we have the new raw value and have updated the prev
88 * timestamp already. We can now calculate the elapsed delta
89 * (event-)time and add that to the generic event.
90 *
91 * Careful, not all hw sign-extends above the physical width
92 * of the count.
93 */
94 delta = (new_raw_count << shift) - (prev_raw_count << shift);
95 delta >>= shift;
96
97 local64_add(delta, &event->count);
98 local64_sub(delta, &hwc->period_left);
99
100 return new_raw_count;
101 }
102
103 /*
104 * Find and validate any extra registers to set up.
105 */
106 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
107 {
108 struct hw_perf_event_extra *reg;
109 struct extra_reg *er;
110
111 reg = &event->hw.extra_reg;
112
113 if (!x86_pmu.extra_regs)
114 return 0;
115
116 for (er = x86_pmu.extra_regs; er->msr; er++) {
117 if (er->event != (config & er->config_mask))
118 continue;
119 if (event->attr.config1 & ~er->valid_mask)
120 return -EINVAL;
121
122 reg->idx = er->idx;
123 reg->config = event->attr.config1;
124 reg->reg = er->msr;
125 break;
126 }
127 return 0;
128 }
129
130 static atomic_t active_events;
131 static DEFINE_MUTEX(pmc_reserve_mutex);
132
133 #ifdef CONFIG_X86_LOCAL_APIC
134
135 static bool reserve_pmc_hardware(void)
136 {
137 int i;
138
139 for (i = 0; i < x86_pmu.num_counters; i++) {
140 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
141 goto perfctr_fail;
142 }
143
144 for (i = 0; i < x86_pmu.num_counters; i++) {
145 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
146 goto eventsel_fail;
147 }
148
149 return true;
150
151 eventsel_fail:
152 for (i--; i >= 0; i--)
153 release_evntsel_nmi(x86_pmu_config_addr(i));
154
155 i = x86_pmu.num_counters;
156
157 perfctr_fail:
158 for (i--; i >= 0; i--)
159 release_perfctr_nmi(x86_pmu_event_addr(i));
160
161 return false;
162 }
163
164 static void release_pmc_hardware(void)
165 {
166 int i;
167
168 for (i = 0; i < x86_pmu.num_counters; i++) {
169 release_perfctr_nmi(x86_pmu_event_addr(i));
170 release_evntsel_nmi(x86_pmu_config_addr(i));
171 }
172 }
173
174 #else
175
176 static bool reserve_pmc_hardware(void) { return true; }
177 static void release_pmc_hardware(void) {}
178
179 #endif
180
181 static bool check_hw_exists(void)
182 {
183 u64 val, val_new = ~0;
184 int i, reg, ret = 0;
185
186 /*
187 * Check to see if the BIOS enabled any of the counters, if so
188 * complain and bail.
189 */
190 for (i = 0; i < x86_pmu.num_counters; i++) {
191 reg = x86_pmu_config_addr(i);
192 ret = rdmsrl_safe(reg, &val);
193 if (ret)
194 goto msr_fail;
195 if (val & ARCH_PERFMON_EVENTSEL_ENABLE)
196 goto bios_fail;
197 }
198
199 if (x86_pmu.num_counters_fixed) {
200 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
201 ret = rdmsrl_safe(reg, &val);
202 if (ret)
203 goto msr_fail;
204 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
205 if (val & (0x03 << i*4))
206 goto bios_fail;
207 }
208 }
209
210 /*
211 * Now write a value and read it back to see if it matches,
212 * this is needed to detect certain hardware emulators (qemu/kvm)
213 * that don't trap on the MSR access and always return 0s.
214 */
215 val = 0xabcdUL;
216 reg = x86_pmu_event_addr(0);
217 ret = wrmsrl_safe(reg, val);
218 ret |= rdmsrl_safe(reg, &val_new);
219 if (ret || val != val_new)
220 goto msr_fail;
221
222 return true;
223
224 bios_fail:
225 /*
226 * We still allow the PMU driver to operate:
227 */
228 printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
229 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg, val);
230
231 return true;
232
233 msr_fail:
234 printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
235 printk(KERN_ERR "Failed to access perfctr msr (MSR %x is %Lx)\n", reg, val_new);
236
237 return false;
238 }
239
240 static void hw_perf_event_destroy(struct perf_event *event)
241 {
242 if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
243 release_pmc_hardware();
244 release_ds_buffers();
245 mutex_unlock(&pmc_reserve_mutex);
246 }
247 }
248
249 static inline int x86_pmu_initialized(void)
250 {
251 return x86_pmu.handle_irq != NULL;
252 }
253
254 static inline int
255 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
256 {
257 struct perf_event_attr *attr = &event->attr;
258 unsigned int cache_type, cache_op, cache_result;
259 u64 config, val;
260
261 config = attr->config;
262
263 cache_type = (config >> 0) & 0xff;
264 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
265 return -EINVAL;
266
267 cache_op = (config >> 8) & 0xff;
268 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
269 return -EINVAL;
270
271 cache_result = (config >> 16) & 0xff;
272 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
273 return -EINVAL;
274
275 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
276
277 if (val == 0)
278 return -ENOENT;
279
280 if (val == -1)
281 return -EINVAL;
282
283 hwc->config |= val;
284 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
285 return x86_pmu_extra_regs(val, event);
286 }
287
288 int x86_setup_perfctr(struct perf_event *event)
289 {
290 struct perf_event_attr *attr = &event->attr;
291 struct hw_perf_event *hwc = &event->hw;
292 u64 config;
293
294 if (!is_sampling_event(event)) {
295 hwc->sample_period = x86_pmu.max_period;
296 hwc->last_period = hwc->sample_period;
297 local64_set(&hwc->period_left, hwc->sample_period);
298 } else {
299 /*
300 * If we have a PMU initialized but no APIC
301 * interrupts, we cannot sample hardware
302 * events (user-space has to fall back and
303 * sample via a hrtimer based software event):
304 */
305 if (!x86_pmu.apic)
306 return -EOPNOTSUPP;
307 }
308
309 if (attr->type == PERF_TYPE_RAW)
310 return x86_pmu_extra_regs(event->attr.config, event);
311
312 if (attr->type == PERF_TYPE_HW_CACHE)
313 return set_ext_hw_attr(hwc, event);
314
315 if (attr->config >= x86_pmu.max_events)
316 return -EINVAL;
317
318 /*
319 * The generic map:
320 */
321 config = x86_pmu.event_map(attr->config);
322
323 if (config == 0)
324 return -ENOENT;
325
326 if (config == -1LL)
327 return -EINVAL;
328
329 /*
330 * Branch tracing:
331 */
332 if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
333 !attr->freq && hwc->sample_period == 1) {
334 /* BTS is not supported by this architecture. */
335 if (!x86_pmu.bts_active)
336 return -EOPNOTSUPP;
337
338 /* BTS is currently only allowed for user-mode. */
339 if (!attr->exclude_kernel)
340 return -EOPNOTSUPP;
341 }
342
343 hwc->config |= config;
344
345 return 0;
346 }
347
348 /*
349 * check that branch_sample_type is compatible with
350 * settings needed for precise_ip > 1 which implies
351 * using the LBR to capture ALL taken branches at the
352 * priv levels of the measurement
353 */
354 static inline int precise_br_compat(struct perf_event *event)
355 {
356 u64 m = event->attr.branch_sample_type;
357 u64 b = 0;
358
359 /* must capture all branches */
360 if (!(m & PERF_SAMPLE_BRANCH_ANY))
361 return 0;
362
363 m &= PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_USER;
364
365 if (!event->attr.exclude_user)
366 b |= PERF_SAMPLE_BRANCH_USER;
367
368 if (!event->attr.exclude_kernel)
369 b |= PERF_SAMPLE_BRANCH_KERNEL;
370
371 /*
372 * ignore PERF_SAMPLE_BRANCH_HV, not supported on x86
373 */
374
375 return m == b;
376 }
377
378 int x86_pmu_hw_config(struct perf_event *event)
379 {
380 if (event->attr.precise_ip) {
381 int precise = 0;
382
383 /* Support for constant skid */
384 if (x86_pmu.pebs_active && !x86_pmu.pebs_broken) {
385 precise++;
386
387 /* Support for IP fixup */
388 if (x86_pmu.lbr_nr)
389 precise++;
390 }
391
392 if (event->attr.precise_ip > precise)
393 return -EOPNOTSUPP;
394 /*
395 * check that PEBS LBR correction does not conflict with
396 * whatever the user is asking with attr->branch_sample_type
397 */
398 if (event->attr.precise_ip > 1) {
399 u64 *br_type = &event->attr.branch_sample_type;
400
401 if (has_branch_stack(event)) {
402 if (!precise_br_compat(event))
403 return -EOPNOTSUPP;
404
405 /* branch_sample_type is compatible */
406
407 } else {
408 /*
409 * user did not specify branch_sample_type
410 *
411 * For PEBS fixups, we capture all
412 * the branches at the priv level of the
413 * event.
414 */
415 *br_type = PERF_SAMPLE_BRANCH_ANY;
416
417 if (!event->attr.exclude_user)
418 *br_type |= PERF_SAMPLE_BRANCH_USER;
419
420 if (!event->attr.exclude_kernel)
421 *br_type |= PERF_SAMPLE_BRANCH_KERNEL;
422 }
423 }
424 }
425
426 /*
427 * Generate PMC IRQs:
428 * (keep 'enabled' bit clear for now)
429 */
430 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
431
432 /*
433 * Count user and OS events unless requested not to
434 */
435 if (!event->attr.exclude_user)
436 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
437 if (!event->attr.exclude_kernel)
438 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
439
440 if (event->attr.type == PERF_TYPE_RAW)
441 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
442
443 return x86_setup_perfctr(event);
444 }
445
446 /*
447 * Setup the hardware configuration for a given attr_type
448 */
449 static int __x86_pmu_event_init(struct perf_event *event)
450 {
451 int err;
452
453 if (!x86_pmu_initialized())
454 return -ENODEV;
455
456 err = 0;
457 if (!atomic_inc_not_zero(&active_events)) {
458 mutex_lock(&pmc_reserve_mutex);
459 if (atomic_read(&active_events) == 0) {
460 if (!reserve_pmc_hardware())
461 err = -EBUSY;
462 else
463 reserve_ds_buffers();
464 }
465 if (!err)
466 atomic_inc(&active_events);
467 mutex_unlock(&pmc_reserve_mutex);
468 }
469 if (err)
470 return err;
471
472 event->destroy = hw_perf_event_destroy;
473
474 event->hw.idx = -1;
475 event->hw.last_cpu = -1;
476 event->hw.last_tag = ~0ULL;
477
478 /* mark unused */
479 event->hw.extra_reg.idx = EXTRA_REG_NONE;
480 event->hw.branch_reg.idx = EXTRA_REG_NONE;
481
482 return x86_pmu.hw_config(event);
483 }
484
485 void x86_pmu_disable_all(void)
486 {
487 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
488 int idx;
489
490 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
491 u64 val;
492
493 if (!test_bit(idx, cpuc->active_mask))
494 continue;
495 rdmsrl(x86_pmu_config_addr(idx), val);
496 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
497 continue;
498 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
499 wrmsrl(x86_pmu_config_addr(idx), val);
500 }
501 }
502
503 static void x86_pmu_disable(struct pmu *pmu)
504 {
505 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
506
507 if (!x86_pmu_initialized())
508 return;
509
510 if (!cpuc->enabled)
511 return;
512
513 cpuc->n_added = 0;
514 cpuc->enabled = 0;
515 barrier();
516
517 x86_pmu.disable_all();
518 }
519
520 void x86_pmu_enable_all(int added)
521 {
522 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
523 int idx;
524
525 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
526 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
527
528 if (!test_bit(idx, cpuc->active_mask))
529 continue;
530
531 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
532 }
533 }
534
535 static struct pmu pmu;
536
537 static inline int is_x86_event(struct perf_event *event)
538 {
539 return event->pmu == &pmu;
540 }
541
542 /*
543 * Event scheduler state:
544 *
545 * Assign events iterating over all events and counters, beginning
546 * with events with least weights first. Keep the current iterator
547 * state in struct sched_state.
548 */
549 struct sched_state {
550 int weight;
551 int event; /* event index */
552 int counter; /* counter index */
553 int unassigned; /* number of events to be assigned left */
554 unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
555 };
556
557 /* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
558 #define SCHED_STATES_MAX 2
559
560 struct perf_sched {
561 int max_weight;
562 int max_events;
563 struct event_constraint **constraints;
564 struct sched_state state;
565 int saved_states;
566 struct sched_state saved[SCHED_STATES_MAX];
567 };
568
569 /*
570 * Initialize interator that runs through all events and counters.
571 */
572 static void perf_sched_init(struct perf_sched *sched, struct event_constraint **c,
573 int num, int wmin, int wmax)
574 {
575 int idx;
576
577 memset(sched, 0, sizeof(*sched));
578 sched->max_events = num;
579 sched->max_weight = wmax;
580 sched->constraints = c;
581
582 for (idx = 0; idx < num; idx++) {
583 if (c[idx]->weight == wmin)
584 break;
585 }
586
587 sched->state.event = idx; /* start with min weight */
588 sched->state.weight = wmin;
589 sched->state.unassigned = num;
590 }
591
592 static void perf_sched_save_state(struct perf_sched *sched)
593 {
594 if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
595 return;
596
597 sched->saved[sched->saved_states] = sched->state;
598 sched->saved_states++;
599 }
600
601 static bool perf_sched_restore_state(struct perf_sched *sched)
602 {
603 if (!sched->saved_states)
604 return false;
605
606 sched->saved_states--;
607 sched->state = sched->saved[sched->saved_states];
608
609 /* continue with next counter: */
610 clear_bit(sched->state.counter++, sched->state.used);
611
612 return true;
613 }
614
615 /*
616 * Select a counter for the current event to schedule. Return true on
617 * success.
618 */
619 static bool __perf_sched_find_counter(struct perf_sched *sched)
620 {
621 struct event_constraint *c;
622 int idx;
623
624 if (!sched->state.unassigned)
625 return false;
626
627 if (sched->state.event >= sched->max_events)
628 return false;
629
630 c = sched->constraints[sched->state.event];
631
632 /* Prefer fixed purpose counters */
633 if (c->idxmsk64 & (~0ULL << INTEL_PMC_IDX_FIXED)) {
634 idx = INTEL_PMC_IDX_FIXED;
635 for_each_set_bit_from(idx, c->idxmsk, X86_PMC_IDX_MAX) {
636 if (!__test_and_set_bit(idx, sched->state.used))
637 goto done;
638 }
639 }
640 /* Grab the first unused counter starting with idx */
641 idx = sched->state.counter;
642 for_each_set_bit_from(idx, c->idxmsk, INTEL_PMC_IDX_FIXED) {
643 if (!__test_and_set_bit(idx, sched->state.used))
644 goto done;
645 }
646
647 return false;
648
649 done:
650 sched->state.counter = idx;
651
652 if (c->overlap)
653 perf_sched_save_state(sched);
654
655 return true;
656 }
657
658 static bool perf_sched_find_counter(struct perf_sched *sched)
659 {
660 while (!__perf_sched_find_counter(sched)) {
661 if (!perf_sched_restore_state(sched))
662 return false;
663 }
664
665 return true;
666 }
667
668 /*
669 * Go through all unassigned events and find the next one to schedule.
670 * Take events with the least weight first. Return true on success.
671 */
672 static bool perf_sched_next_event(struct perf_sched *sched)
673 {
674 struct event_constraint *c;
675
676 if (!sched->state.unassigned || !--sched->state.unassigned)
677 return false;
678
679 do {
680 /* next event */
681 sched->state.event++;
682 if (sched->state.event >= sched->max_events) {
683 /* next weight */
684 sched->state.event = 0;
685 sched->state.weight++;
686 if (sched->state.weight > sched->max_weight)
687 return false;
688 }
689 c = sched->constraints[sched->state.event];
690 } while (c->weight != sched->state.weight);
691
692 sched->state.counter = 0; /* start with first counter */
693
694 return true;
695 }
696
697 /*
698 * Assign a counter for each event.
699 */
700 int perf_assign_events(struct event_constraint **constraints, int n,
701 int wmin, int wmax, int *assign)
702 {
703 struct perf_sched sched;
704
705 perf_sched_init(&sched, constraints, n, wmin, wmax);
706
707 do {
708 if (!perf_sched_find_counter(&sched))
709 break; /* failed */
710 if (assign)
711 assign[sched.state.event] = sched.state.counter;
712 } while (perf_sched_next_event(&sched));
713
714 return sched.state.unassigned;
715 }
716
717 int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
718 {
719 struct event_constraint *c, *constraints[X86_PMC_IDX_MAX];
720 unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
721 int i, wmin, wmax, num = 0;
722 struct hw_perf_event *hwc;
723
724 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
725
726 for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
727 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
728 constraints[i] = c;
729 wmin = min(wmin, c->weight);
730 wmax = max(wmax, c->weight);
731 }
732
733 /*
734 * fastpath, try to reuse previous register
735 */
736 for (i = 0; i < n; i++) {
737 hwc = &cpuc->event_list[i]->hw;
738 c = constraints[i];
739
740 /* never assigned */
741 if (hwc->idx == -1)
742 break;
743
744 /* constraint still honored */
745 if (!test_bit(hwc->idx, c->idxmsk))
746 break;
747
748 /* not already used */
749 if (test_bit(hwc->idx, used_mask))
750 break;
751
752 __set_bit(hwc->idx, used_mask);
753 if (assign)
754 assign[i] = hwc->idx;
755 }
756
757 /* slow path */
758 if (i != n)
759 num = perf_assign_events(constraints, n, wmin, wmax, assign);
760
761 /*
762 * scheduling failed or is just a simulation,
763 * free resources if necessary
764 */
765 if (!assign || num) {
766 for (i = 0; i < n; i++) {
767 if (x86_pmu.put_event_constraints)
768 x86_pmu.put_event_constraints(cpuc, cpuc->event_list[i]);
769 }
770 }
771 return num ? -EINVAL : 0;
772 }
773
774 /*
775 * dogrp: true if must collect siblings events (group)
776 * returns total number of events and error code
777 */
778 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
779 {
780 struct perf_event *event;
781 int n, max_count;
782
783 max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
784
785 /* current number of events already accepted */
786 n = cpuc->n_events;
787
788 if (is_x86_event(leader)) {
789 if (n >= max_count)
790 return -EINVAL;
791 cpuc->event_list[n] = leader;
792 n++;
793 }
794 if (!dogrp)
795 return n;
796
797 list_for_each_entry(event, &leader->sibling_list, group_entry) {
798 if (!is_x86_event(event) ||
799 event->state <= PERF_EVENT_STATE_OFF)
800 continue;
801
802 if (n >= max_count)
803 return -EINVAL;
804
805 cpuc->event_list[n] = event;
806 n++;
807 }
808 return n;
809 }
810
811 static inline void x86_assign_hw_event(struct perf_event *event,
812 struct cpu_hw_events *cpuc, int i)
813 {
814 struct hw_perf_event *hwc = &event->hw;
815
816 hwc->idx = cpuc->assign[i];
817 hwc->last_cpu = smp_processor_id();
818 hwc->last_tag = ++cpuc->tags[i];
819
820 if (hwc->idx == INTEL_PMC_IDX_FIXED_BTS) {
821 hwc->config_base = 0;
822 hwc->event_base = 0;
823 } else if (hwc->idx >= INTEL_PMC_IDX_FIXED) {
824 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
825 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - INTEL_PMC_IDX_FIXED);
826 hwc->event_base_rdpmc = (hwc->idx - INTEL_PMC_IDX_FIXED) | 1<<30;
827 } else {
828 hwc->config_base = x86_pmu_config_addr(hwc->idx);
829 hwc->event_base = x86_pmu_event_addr(hwc->idx);
830 hwc->event_base_rdpmc = hwc->idx;
831 }
832 }
833
834 static inline int match_prev_assignment(struct hw_perf_event *hwc,
835 struct cpu_hw_events *cpuc,
836 int i)
837 {
838 return hwc->idx == cpuc->assign[i] &&
839 hwc->last_cpu == smp_processor_id() &&
840 hwc->last_tag == cpuc->tags[i];
841 }
842
843 static void x86_pmu_start(struct perf_event *event, int flags);
844
845 static void x86_pmu_enable(struct pmu *pmu)
846 {
847 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
848 struct perf_event *event;
849 struct hw_perf_event *hwc;
850 int i, added = cpuc->n_added;
851
852 if (!x86_pmu_initialized())
853 return;
854
855 if (cpuc->enabled)
856 return;
857
858 if (cpuc->n_added) {
859 int n_running = cpuc->n_events - cpuc->n_added;
860 /*
861 * apply assignment obtained either from
862 * hw_perf_group_sched_in() or x86_pmu_enable()
863 *
864 * step1: save events moving to new counters
865 * step2: reprogram moved events into new counters
866 */
867 for (i = 0; i < n_running; i++) {
868 event = cpuc->event_list[i];
869 hwc = &event->hw;
870
871 /*
872 * we can avoid reprogramming counter if:
873 * - assigned same counter as last time
874 * - running on same CPU as last time
875 * - no other event has used the counter since
876 */
877 if (hwc->idx == -1 ||
878 match_prev_assignment(hwc, cpuc, i))
879 continue;
880
881 /*
882 * Ensure we don't accidentally enable a stopped
883 * counter simply because we rescheduled.
884 */
885 if (hwc->state & PERF_HES_STOPPED)
886 hwc->state |= PERF_HES_ARCH;
887
888 x86_pmu_stop(event, PERF_EF_UPDATE);
889 }
890
891 for (i = 0; i < cpuc->n_events; i++) {
892 event = cpuc->event_list[i];
893 hwc = &event->hw;
894
895 if (!match_prev_assignment(hwc, cpuc, i))
896 x86_assign_hw_event(event, cpuc, i);
897 else if (i < n_running)
898 continue;
899
900 if (hwc->state & PERF_HES_ARCH)
901 continue;
902
903 x86_pmu_start(event, PERF_EF_RELOAD);
904 }
905 cpuc->n_added = 0;
906 perf_events_lapic_init();
907 }
908
909 cpuc->enabled = 1;
910 barrier();
911
912 x86_pmu.enable_all(added);
913 }
914
915 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
916
917 /*
918 * Set the next IRQ period, based on the hwc->period_left value.
919 * To be called with the event disabled in hw:
920 */
921 int x86_perf_event_set_period(struct perf_event *event)
922 {
923 struct hw_perf_event *hwc = &event->hw;
924 s64 left = local64_read(&hwc->period_left);
925 s64 period = hwc->sample_period;
926 int ret = 0, idx = hwc->idx;
927
928 if (idx == INTEL_PMC_IDX_FIXED_BTS)
929 return 0;
930
931 /*
932 * If we are way outside a reasonable range then just skip forward:
933 */
934 if (unlikely(left <= -period)) {
935 left = period;
936 local64_set(&hwc->period_left, left);
937 hwc->last_period = period;
938 ret = 1;
939 }
940
941 if (unlikely(left <= 0)) {
942 left += period;
943 local64_set(&hwc->period_left, left);
944 hwc->last_period = period;
945 ret = 1;
946 }
947 /*
948 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
949 */
950 if (unlikely(left < 2))
951 left = 2;
952
953 if (left > x86_pmu.max_period)
954 left = x86_pmu.max_period;
955
956 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
957
958 /*
959 * The hw event starts counting from this event offset,
960 * mark it to be able to extra future deltas:
961 */
962 local64_set(&hwc->prev_count, (u64)-left);
963
964 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
965
966 /*
967 * Due to erratum on certan cpu we need
968 * a second write to be sure the register
969 * is updated properly
970 */
971 if (x86_pmu.perfctr_second_write) {
972 wrmsrl(hwc->event_base,
973 (u64)(-left) & x86_pmu.cntval_mask);
974 }
975
976 perf_event_update_userpage(event);
977
978 return ret;
979 }
980
981 void x86_pmu_enable_event(struct perf_event *event)
982 {
983 if (__this_cpu_read(cpu_hw_events.enabled))
984 __x86_pmu_enable_event(&event->hw,
985 ARCH_PERFMON_EVENTSEL_ENABLE);
986 }
987
988 /*
989 * Add a single event to the PMU.
990 *
991 * The event is added to the group of enabled events
992 * but only if it can be scehduled with existing events.
993 */
994 static int x86_pmu_add(struct perf_event *event, int flags)
995 {
996 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
997 struct hw_perf_event *hwc;
998 int assign[X86_PMC_IDX_MAX];
999 int n, n0, ret;
1000
1001 hwc = &event->hw;
1002
1003 perf_pmu_disable(event->pmu);
1004 n0 = cpuc->n_events;
1005 ret = n = collect_events(cpuc, event, false);
1006 if (ret < 0)
1007 goto out;
1008
1009 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1010 if (!(flags & PERF_EF_START))
1011 hwc->state |= PERF_HES_ARCH;
1012
1013 /*
1014 * If group events scheduling transaction was started,
1015 * skip the schedulability test here, it will be performed
1016 * at commit time (->commit_txn) as a whole
1017 */
1018 if (cpuc->group_flag & PERF_EVENT_TXN)
1019 goto done_collect;
1020
1021 ret = x86_pmu.schedule_events(cpuc, n, assign);
1022 if (ret)
1023 goto out;
1024 /*
1025 * copy new assignment, now we know it is possible
1026 * will be used by hw_perf_enable()
1027 */
1028 memcpy(cpuc->assign, assign, n*sizeof(int));
1029
1030 done_collect:
1031 cpuc->n_events = n;
1032 cpuc->n_added += n - n0;
1033 cpuc->n_txn += n - n0;
1034
1035 ret = 0;
1036 out:
1037 perf_pmu_enable(event->pmu);
1038 return ret;
1039 }
1040
1041 static void x86_pmu_start(struct perf_event *event, int flags)
1042 {
1043 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1044 int idx = event->hw.idx;
1045
1046 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1047 return;
1048
1049 if (WARN_ON_ONCE(idx == -1))
1050 return;
1051
1052 if (flags & PERF_EF_RELOAD) {
1053 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1054 x86_perf_event_set_period(event);
1055 }
1056
1057 event->hw.state = 0;
1058
1059 cpuc->events[idx] = event;
1060 __set_bit(idx, cpuc->active_mask);
1061 __set_bit(idx, cpuc->running);
1062 x86_pmu.enable(event);
1063 perf_event_update_userpage(event);
1064 }
1065
1066 void perf_event_print_debug(void)
1067 {
1068 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1069 u64 pebs;
1070 struct cpu_hw_events *cpuc;
1071 unsigned long flags;
1072 int cpu, idx;
1073
1074 if (!x86_pmu.num_counters)
1075 return;
1076
1077 local_irq_save(flags);
1078
1079 cpu = smp_processor_id();
1080 cpuc = &per_cpu(cpu_hw_events, cpu);
1081
1082 if (x86_pmu.version >= 2) {
1083 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1084 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1085 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1086 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1087 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1088
1089 pr_info("\n");
1090 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1091 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1092 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1093 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
1094 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
1095 }
1096 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1097
1098 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1099 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1100 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1101
1102 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1103
1104 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
1105 cpu, idx, pmc_ctrl);
1106 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
1107 cpu, idx, pmc_count);
1108 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
1109 cpu, idx, prev_left);
1110 }
1111 for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1112 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1113
1114 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1115 cpu, idx, pmc_count);
1116 }
1117 local_irq_restore(flags);
1118 }
1119
1120 void x86_pmu_stop(struct perf_event *event, int flags)
1121 {
1122 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1123 struct hw_perf_event *hwc = &event->hw;
1124
1125 if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1126 x86_pmu.disable(event);
1127 cpuc->events[hwc->idx] = NULL;
1128 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1129 hwc->state |= PERF_HES_STOPPED;
1130 }
1131
1132 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1133 /*
1134 * Drain the remaining delta count out of a event
1135 * that we are disabling:
1136 */
1137 x86_perf_event_update(event);
1138 hwc->state |= PERF_HES_UPTODATE;
1139 }
1140 }
1141
1142 static void x86_pmu_del(struct perf_event *event, int flags)
1143 {
1144 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1145 int i;
1146
1147 /*
1148 * If we're called during a txn, we don't need to do anything.
1149 * The events never got scheduled and ->cancel_txn will truncate
1150 * the event_list.
1151 */
1152 if (cpuc->group_flag & PERF_EVENT_TXN)
1153 return;
1154
1155 x86_pmu_stop(event, PERF_EF_UPDATE);
1156
1157 for (i = 0; i < cpuc->n_events; i++) {
1158 if (event == cpuc->event_list[i]) {
1159
1160 if (x86_pmu.put_event_constraints)
1161 x86_pmu.put_event_constraints(cpuc, event);
1162
1163 while (++i < cpuc->n_events)
1164 cpuc->event_list[i-1] = cpuc->event_list[i];
1165
1166 --cpuc->n_events;
1167 break;
1168 }
1169 }
1170 perf_event_update_userpage(event);
1171 }
1172
1173 int x86_pmu_handle_irq(struct pt_regs *regs)
1174 {
1175 struct perf_sample_data data;
1176 struct cpu_hw_events *cpuc;
1177 struct perf_event *event;
1178 int idx, handled = 0;
1179 u64 val;
1180
1181 cpuc = &__get_cpu_var(cpu_hw_events);
1182
1183 /*
1184 * Some chipsets need to unmask the LVTPC in a particular spot
1185 * inside the nmi handler. As a result, the unmasking was pushed
1186 * into all the nmi handlers.
1187 *
1188 * This generic handler doesn't seem to have any issues where the
1189 * unmasking occurs so it was left at the top.
1190 */
1191 apic_write(APIC_LVTPC, APIC_DM_NMI);
1192
1193 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1194 if (!test_bit(idx, cpuc->active_mask)) {
1195 /*
1196 * Though we deactivated the counter some cpus
1197 * might still deliver spurious interrupts still
1198 * in flight. Catch them:
1199 */
1200 if (__test_and_clear_bit(idx, cpuc->running))
1201 handled++;
1202 continue;
1203 }
1204
1205 event = cpuc->events[idx];
1206
1207 val = x86_perf_event_update(event);
1208 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1209 continue;
1210
1211 /*
1212 * event overflow
1213 */
1214 handled++;
1215 perf_sample_data_init(&data, 0, event->hw.last_period);
1216
1217 if (!x86_perf_event_set_period(event))
1218 continue;
1219
1220 if (perf_event_overflow(event, &data, regs))
1221 x86_pmu_stop(event, 0);
1222 }
1223
1224 if (handled)
1225 inc_irq_stat(apic_perf_irqs);
1226
1227 return handled;
1228 }
1229
1230 void perf_events_lapic_init(void)
1231 {
1232 if (!x86_pmu.apic || !x86_pmu_initialized())
1233 return;
1234
1235 /*
1236 * Always use NMI for PMU
1237 */
1238 apic_write(APIC_LVTPC, APIC_DM_NMI);
1239 }
1240
1241 static int __kprobes
1242 perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
1243 {
1244 if (!atomic_read(&active_events))
1245 return NMI_DONE;
1246
1247 return x86_pmu.handle_irq(regs);
1248 }
1249
1250 struct event_constraint emptyconstraint;
1251 struct event_constraint unconstrained;
1252
1253 static int __cpuinit
1254 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1255 {
1256 unsigned int cpu = (long)hcpu;
1257 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1258 int ret = NOTIFY_OK;
1259
1260 switch (action & ~CPU_TASKS_FROZEN) {
1261 case CPU_UP_PREPARE:
1262 cpuc->kfree_on_online = NULL;
1263 if (x86_pmu.cpu_prepare)
1264 ret = x86_pmu.cpu_prepare(cpu);
1265 break;
1266
1267 case CPU_STARTING:
1268 if (x86_pmu.attr_rdpmc)
1269 set_in_cr4(X86_CR4_PCE);
1270 if (x86_pmu.cpu_starting)
1271 x86_pmu.cpu_starting(cpu);
1272 break;
1273
1274 case CPU_ONLINE:
1275 kfree(cpuc->kfree_on_online);
1276 break;
1277
1278 case CPU_DYING:
1279 if (x86_pmu.cpu_dying)
1280 x86_pmu.cpu_dying(cpu);
1281 break;
1282
1283 case CPU_UP_CANCELED:
1284 case CPU_DEAD:
1285 if (x86_pmu.cpu_dead)
1286 x86_pmu.cpu_dead(cpu);
1287 break;
1288
1289 default:
1290 break;
1291 }
1292
1293 return ret;
1294 }
1295
1296 static void __init pmu_check_apic(void)
1297 {
1298 if (cpu_has_apic)
1299 return;
1300
1301 x86_pmu.apic = 0;
1302 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1303 pr_info("no hardware sampling interrupt available.\n");
1304 }
1305
1306 static struct attribute_group x86_pmu_format_group = {
1307 .name = "format",
1308 .attrs = NULL,
1309 };
1310
1311 static int __init init_hw_perf_events(void)
1312 {
1313 struct x86_pmu_quirk *quirk;
1314 int err;
1315
1316 pr_info("Performance Events: ");
1317
1318 switch (boot_cpu_data.x86_vendor) {
1319 case X86_VENDOR_INTEL:
1320 err = intel_pmu_init();
1321 break;
1322 case X86_VENDOR_AMD:
1323 err = amd_pmu_init();
1324 break;
1325 default:
1326 return 0;
1327 }
1328 if (err != 0) {
1329 pr_cont("no PMU driver, software events only.\n");
1330 return 0;
1331 }
1332
1333 pmu_check_apic();
1334
1335 /* sanity check that the hardware exists or is emulated */
1336 if (!check_hw_exists())
1337 return 0;
1338
1339 pr_cont("%s PMU driver.\n", x86_pmu.name);
1340
1341 for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
1342 quirk->func();
1343
1344 if (!x86_pmu.intel_ctrl)
1345 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1346
1347 perf_events_lapic_init();
1348 register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
1349
1350 unconstrained = (struct event_constraint)
1351 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1352 0, x86_pmu.num_counters, 0);
1353
1354 x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
1355 x86_pmu_format_group.attrs = x86_pmu.format_attrs;
1356
1357 pr_info("... version: %d\n", x86_pmu.version);
1358 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
1359 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
1360 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
1361 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
1362 pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
1363 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
1364
1365 perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1366 perf_cpu_notifier(x86_pmu_notifier);
1367
1368 return 0;
1369 }
1370 early_initcall(init_hw_perf_events);
1371
1372 static inline void x86_pmu_read(struct perf_event *event)
1373 {
1374 x86_perf_event_update(event);
1375 }
1376
1377 /*
1378 * Start group events scheduling transaction
1379 * Set the flag to make pmu::enable() not perform the
1380 * schedulability test, it will be performed at commit time
1381 */
1382 static void x86_pmu_start_txn(struct pmu *pmu)
1383 {
1384 perf_pmu_disable(pmu);
1385 __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1386 __this_cpu_write(cpu_hw_events.n_txn, 0);
1387 }
1388
1389 /*
1390 * Stop group events scheduling transaction
1391 * Clear the flag and pmu::enable() will perform the
1392 * schedulability test.
1393 */
1394 static void x86_pmu_cancel_txn(struct pmu *pmu)
1395 {
1396 __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1397 /*
1398 * Truncate the collected events.
1399 */
1400 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1401 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1402 perf_pmu_enable(pmu);
1403 }
1404
1405 /*
1406 * Commit group events scheduling transaction
1407 * Perform the group schedulability test as a whole
1408 * Return 0 if success
1409 */
1410 static int x86_pmu_commit_txn(struct pmu *pmu)
1411 {
1412 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1413 int assign[X86_PMC_IDX_MAX];
1414 int n, ret;
1415
1416 n = cpuc->n_events;
1417
1418 if (!x86_pmu_initialized())
1419 return -EAGAIN;
1420
1421 ret = x86_pmu.schedule_events(cpuc, n, assign);
1422 if (ret)
1423 return ret;
1424
1425 /*
1426 * copy new assignment, now we know it is possible
1427 * will be used by hw_perf_enable()
1428 */
1429 memcpy(cpuc->assign, assign, n*sizeof(int));
1430
1431 cpuc->group_flag &= ~PERF_EVENT_TXN;
1432 perf_pmu_enable(pmu);
1433 return 0;
1434 }
1435 /*
1436 * a fake_cpuc is used to validate event groups. Due to
1437 * the extra reg logic, we need to also allocate a fake
1438 * per_core and per_cpu structure. Otherwise, group events
1439 * using extra reg may conflict without the kernel being
1440 * able to catch this when the last event gets added to
1441 * the group.
1442 */
1443 static void free_fake_cpuc(struct cpu_hw_events *cpuc)
1444 {
1445 kfree(cpuc->shared_regs);
1446 kfree(cpuc);
1447 }
1448
1449 static struct cpu_hw_events *allocate_fake_cpuc(void)
1450 {
1451 struct cpu_hw_events *cpuc;
1452 int cpu = raw_smp_processor_id();
1453
1454 cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
1455 if (!cpuc)
1456 return ERR_PTR(-ENOMEM);
1457
1458 /* only needed, if we have extra_regs */
1459 if (x86_pmu.extra_regs) {
1460 cpuc->shared_regs = allocate_shared_regs(cpu);
1461 if (!cpuc->shared_regs)
1462 goto error;
1463 }
1464 cpuc->is_fake = 1;
1465 return cpuc;
1466 error:
1467 free_fake_cpuc(cpuc);
1468 return ERR_PTR(-ENOMEM);
1469 }
1470
1471 /*
1472 * validate that we can schedule this event
1473 */
1474 static int validate_event(struct perf_event *event)
1475 {
1476 struct cpu_hw_events *fake_cpuc;
1477 struct event_constraint *c;
1478 int ret = 0;
1479
1480 fake_cpuc = allocate_fake_cpuc();
1481 if (IS_ERR(fake_cpuc))
1482 return PTR_ERR(fake_cpuc);
1483
1484 c = x86_pmu.get_event_constraints(fake_cpuc, event);
1485
1486 if (!c || !c->weight)
1487 ret = -EINVAL;
1488
1489 if (x86_pmu.put_event_constraints)
1490 x86_pmu.put_event_constraints(fake_cpuc, event);
1491
1492 free_fake_cpuc(fake_cpuc);
1493
1494 return ret;
1495 }
1496
1497 /*
1498 * validate a single event group
1499 *
1500 * validation include:
1501 * - check events are compatible which each other
1502 * - events do not compete for the same counter
1503 * - number of events <= number of counters
1504 *
1505 * validation ensures the group can be loaded onto the
1506 * PMU if it was the only group available.
1507 */
1508 static int validate_group(struct perf_event *event)
1509 {
1510 struct perf_event *leader = event->group_leader;
1511 struct cpu_hw_events *fake_cpuc;
1512 int ret = -EINVAL, n;
1513
1514 fake_cpuc = allocate_fake_cpuc();
1515 if (IS_ERR(fake_cpuc))
1516 return PTR_ERR(fake_cpuc);
1517 /*
1518 * the event is not yet connected with its
1519 * siblings therefore we must first collect
1520 * existing siblings, then add the new event
1521 * before we can simulate the scheduling
1522 */
1523 n = collect_events(fake_cpuc, leader, true);
1524 if (n < 0)
1525 goto out;
1526
1527 fake_cpuc->n_events = n;
1528 n = collect_events(fake_cpuc, event, false);
1529 if (n < 0)
1530 goto out;
1531
1532 fake_cpuc->n_events = n;
1533
1534 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1535
1536 out:
1537 free_fake_cpuc(fake_cpuc);
1538 return ret;
1539 }
1540
1541 static int x86_pmu_event_init(struct perf_event *event)
1542 {
1543 struct pmu *tmp;
1544 int err;
1545
1546 switch (event->attr.type) {
1547 case PERF_TYPE_RAW:
1548 case PERF_TYPE_HARDWARE:
1549 case PERF_TYPE_HW_CACHE:
1550 break;
1551
1552 default:
1553 return -ENOENT;
1554 }
1555
1556 err = __x86_pmu_event_init(event);
1557 if (!err) {
1558 /*
1559 * we temporarily connect event to its pmu
1560 * such that validate_group() can classify
1561 * it as an x86 event using is_x86_event()
1562 */
1563 tmp = event->pmu;
1564 event->pmu = &pmu;
1565
1566 if (event->group_leader != event)
1567 err = validate_group(event);
1568 else
1569 err = validate_event(event);
1570
1571 event->pmu = tmp;
1572 }
1573 if (err) {
1574 if (event->destroy)
1575 event->destroy(event);
1576 }
1577
1578 return err;
1579 }
1580
1581 static int x86_pmu_event_idx(struct perf_event *event)
1582 {
1583 int idx = event->hw.idx;
1584
1585 if (!x86_pmu.attr_rdpmc)
1586 return 0;
1587
1588 if (x86_pmu.num_counters_fixed && idx >= INTEL_PMC_IDX_FIXED) {
1589 idx -= INTEL_PMC_IDX_FIXED;
1590 idx |= 1 << 30;
1591 }
1592
1593 return idx + 1;
1594 }
1595
1596 static ssize_t get_attr_rdpmc(struct device *cdev,
1597 struct device_attribute *attr,
1598 char *buf)
1599 {
1600 return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
1601 }
1602
1603 static void change_rdpmc(void *info)
1604 {
1605 bool enable = !!(unsigned long)info;
1606
1607 if (enable)
1608 set_in_cr4(X86_CR4_PCE);
1609 else
1610 clear_in_cr4(X86_CR4_PCE);
1611 }
1612
1613 static ssize_t set_attr_rdpmc(struct device *cdev,
1614 struct device_attribute *attr,
1615 const char *buf, size_t count)
1616 {
1617 unsigned long val;
1618 ssize_t ret;
1619
1620 ret = kstrtoul(buf, 0, &val);
1621 if (ret)
1622 return ret;
1623
1624 if (!!val != !!x86_pmu.attr_rdpmc) {
1625 x86_pmu.attr_rdpmc = !!val;
1626 smp_call_function(change_rdpmc, (void *)val, 1);
1627 }
1628
1629 return count;
1630 }
1631
1632 static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
1633
1634 static struct attribute *x86_pmu_attrs[] = {
1635 &dev_attr_rdpmc.attr,
1636 NULL,
1637 };
1638
1639 static struct attribute_group x86_pmu_attr_group = {
1640 .attrs = x86_pmu_attrs,
1641 };
1642
1643 static const struct attribute_group *x86_pmu_attr_groups[] = {
1644 &x86_pmu_attr_group,
1645 &x86_pmu_format_group,
1646 NULL,
1647 };
1648
1649 static void x86_pmu_flush_branch_stack(void)
1650 {
1651 if (x86_pmu.flush_branch_stack)
1652 x86_pmu.flush_branch_stack();
1653 }
1654
1655 void perf_check_microcode(void)
1656 {
1657 if (x86_pmu.check_microcode)
1658 x86_pmu.check_microcode();
1659 }
1660 EXPORT_SYMBOL_GPL(perf_check_microcode);
1661
1662 static struct pmu pmu = {
1663 .pmu_enable = x86_pmu_enable,
1664 .pmu_disable = x86_pmu_disable,
1665
1666 .attr_groups = x86_pmu_attr_groups,
1667
1668 .event_init = x86_pmu_event_init,
1669
1670 .add = x86_pmu_add,
1671 .del = x86_pmu_del,
1672 .start = x86_pmu_start,
1673 .stop = x86_pmu_stop,
1674 .read = x86_pmu_read,
1675
1676 .start_txn = x86_pmu_start_txn,
1677 .cancel_txn = x86_pmu_cancel_txn,
1678 .commit_txn = x86_pmu_commit_txn,
1679
1680 .event_idx = x86_pmu_event_idx,
1681 .flush_branch_stack = x86_pmu_flush_branch_stack,
1682 };
1683
1684 void arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
1685 {
1686 userpg->cap_usr_time = 0;
1687 userpg->cap_usr_rdpmc = x86_pmu.attr_rdpmc;
1688 userpg->pmc_width = x86_pmu.cntval_bits;
1689
1690 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
1691 return;
1692
1693 if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC))
1694 return;
1695
1696 userpg->cap_usr_time = 1;
1697 userpg->time_mult = this_cpu_read(cyc2ns);
1698 userpg->time_shift = CYC2NS_SCALE_FACTOR;
1699 userpg->time_offset = this_cpu_read(cyc2ns_offset) - now;
1700 }
1701
1702 /*
1703 * callchain support
1704 */
1705
1706 static int backtrace_stack(void *data, char *name)
1707 {
1708 return 0;
1709 }
1710
1711 static void backtrace_address(void *data, unsigned long addr, int reliable)
1712 {
1713 struct perf_callchain_entry *entry = data;
1714
1715 perf_callchain_store(entry, addr);
1716 }
1717
1718 static const struct stacktrace_ops backtrace_ops = {
1719 .stack = backtrace_stack,
1720 .address = backtrace_address,
1721 .walk_stack = print_context_stack_bp,
1722 };
1723
1724 void
1725 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
1726 {
1727 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1728 /* TODO: We don't support guest os callchain now */
1729 return;
1730 }
1731
1732 perf_callchain_store(entry, regs->ip);
1733
1734 dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
1735 }
1736
1737 static inline int
1738 valid_user_frame(const void __user *fp, unsigned long size)
1739 {
1740 return (__range_not_ok(fp, size, TASK_SIZE) == 0);
1741 }
1742
1743 static unsigned long get_segment_base(unsigned int segment)
1744 {
1745 struct desc_struct *desc;
1746 int idx = segment >> 3;
1747
1748 if ((segment & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1749 if (idx > LDT_ENTRIES)
1750 return 0;
1751
1752 if (idx > current->active_mm->context.size)
1753 return 0;
1754
1755 desc = current->active_mm->context.ldt;
1756 } else {
1757 if (idx > GDT_ENTRIES)
1758 return 0;
1759
1760 desc = __this_cpu_ptr(&gdt_page.gdt[0]);
1761 }
1762
1763 return get_desc_base(desc + idx);
1764 }
1765
1766 #ifdef CONFIG_COMPAT
1767
1768 #include <asm/compat.h>
1769
1770 static inline int
1771 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1772 {
1773 /* 32-bit process in 64-bit kernel. */
1774 unsigned long ss_base, cs_base;
1775 struct stack_frame_ia32 frame;
1776 const void __user *fp;
1777
1778 if (!test_thread_flag(TIF_IA32))
1779 return 0;
1780
1781 cs_base = get_segment_base(regs->cs);
1782 ss_base = get_segment_base(regs->ss);
1783
1784 fp = compat_ptr(ss_base + regs->bp);
1785 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1786 unsigned long bytes;
1787 frame.next_frame = 0;
1788 frame.return_address = 0;
1789
1790 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1791 if (bytes != sizeof(frame))
1792 break;
1793
1794 if (!valid_user_frame(fp, sizeof(frame)))
1795 break;
1796
1797 perf_callchain_store(entry, cs_base + frame.return_address);
1798 fp = compat_ptr(ss_base + frame.next_frame);
1799 }
1800 return 1;
1801 }
1802 #else
1803 static inline int
1804 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1805 {
1806 return 0;
1807 }
1808 #endif
1809
1810 void
1811 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
1812 {
1813 struct stack_frame frame;
1814 const void __user *fp;
1815
1816 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1817 /* TODO: We don't support guest os callchain now */
1818 return;
1819 }
1820
1821 /*
1822 * We don't know what to do with VM86 stacks.. ignore them for now.
1823 */
1824 if (regs->flags & (X86_VM_MASK | PERF_EFLAGS_VM))
1825 return;
1826
1827 fp = (void __user *)regs->bp;
1828
1829 perf_callchain_store(entry, regs->ip);
1830
1831 if (!current->mm)
1832 return;
1833
1834 if (perf_callchain_user32(regs, entry))
1835 return;
1836
1837 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1838 unsigned long bytes;
1839 frame.next_frame = NULL;
1840 frame.return_address = 0;
1841
1842 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1843 if (bytes != sizeof(frame))
1844 break;
1845
1846 if (!valid_user_frame(fp, sizeof(frame)))
1847 break;
1848
1849 perf_callchain_store(entry, frame.return_address);
1850 fp = frame.next_frame;
1851 }
1852 }
1853
1854 /*
1855 * Deal with code segment offsets for the various execution modes:
1856 *
1857 * VM86 - the good olde 16 bit days, where the linear address is
1858 * 20 bits and we use regs->ip + 0x10 * regs->cs.
1859 *
1860 * IA32 - Where we need to look at GDT/LDT segment descriptor tables
1861 * to figure out what the 32bit base address is.
1862 *
1863 * X32 - has TIF_X32 set, but is running in x86_64
1864 *
1865 * X86_64 - CS,DS,SS,ES are all zero based.
1866 */
1867 static unsigned long code_segment_base(struct pt_regs *regs)
1868 {
1869 /*
1870 * If we are in VM86 mode, add the segment offset to convert to a
1871 * linear address.
1872 */
1873 if (regs->flags & X86_VM_MASK)
1874 return 0x10 * regs->cs;
1875
1876 /*
1877 * For IA32 we look at the GDT/LDT segment base to convert the
1878 * effective IP to a linear address.
1879 */
1880 #ifdef CONFIG_X86_32
1881 if (user_mode(regs) && regs->cs != __USER_CS)
1882 return get_segment_base(regs->cs);
1883 #else
1884 if (test_thread_flag(TIF_IA32)) {
1885 if (user_mode(regs) && regs->cs != __USER32_CS)
1886 return get_segment_base(regs->cs);
1887 }
1888 #endif
1889 return 0;
1890 }
1891
1892 unsigned long perf_instruction_pointer(struct pt_regs *regs)
1893 {
1894 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
1895 return perf_guest_cbs->get_guest_ip();
1896
1897 return regs->ip + code_segment_base(regs);
1898 }
1899
1900 unsigned long perf_misc_flags(struct pt_regs *regs)
1901 {
1902 int misc = 0;
1903
1904 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1905 if (perf_guest_cbs->is_user_mode())
1906 misc |= PERF_RECORD_MISC_GUEST_USER;
1907 else
1908 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1909 } else {
1910 if (user_mode(regs))
1911 misc |= PERF_RECORD_MISC_USER;
1912 else
1913 misc |= PERF_RECORD_MISC_KERNEL;
1914 }
1915
1916 if (regs->flags & PERF_EFLAGS_EXACT)
1917 misc |= PERF_RECORD_MISC_EXACT_IP;
1918
1919 return misc;
1920 }
1921
1922 void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
1923 {
1924 cap->version = x86_pmu.version;
1925 cap->num_counters_gp = x86_pmu.num_counters;
1926 cap->num_counters_fixed = x86_pmu.num_counters_fixed;
1927 cap->bit_width_gp = x86_pmu.cntval_bits;
1928 cap->bit_width_fixed = x86_pmu.cntval_bits;
1929 cap->events_mask = (unsigned int)x86_pmu.events_maskl;
1930 cap->events_mask_len = x86_pmu.events_mask_len;
1931 }
1932 EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);
This page took 0.125001 seconds and 5 git commands to generate.