GNU Linux-libre 4.4.284-gnu1
[releases.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
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 #include <linux/nospec.h>
29
30 #include <asm/apic.h>
31 #include <asm/stacktrace.h>
32 #include <asm/nmi.h>
33 #include <asm/smp.h>
34 #include <asm/alternative.h>
35 #include <asm/mmu_context.h>
36 #include <asm/tlbflush.h>
37 #include <asm/timer.h>
38 #include <asm/desc.h>
39 #include <asm/ldt.h>
40
41 #include "perf_event.h"
42
43 struct x86_pmu x86_pmu __read_mostly;
44
45 DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
46         .enabled = 1,
47 };
48
49 struct static_key rdpmc_always_available = STATIC_KEY_INIT_FALSE;
50
51 u64 __read_mostly hw_cache_event_ids
52                                 [PERF_COUNT_HW_CACHE_MAX]
53                                 [PERF_COUNT_HW_CACHE_OP_MAX]
54                                 [PERF_COUNT_HW_CACHE_RESULT_MAX];
55 u64 __read_mostly hw_cache_extra_regs
56                                 [PERF_COUNT_HW_CACHE_MAX]
57                                 [PERF_COUNT_HW_CACHE_OP_MAX]
58                                 [PERF_COUNT_HW_CACHE_RESULT_MAX];
59
60 /*
61  * Propagate event elapsed time into the generic event.
62  * Can only be executed on the CPU where the event is active.
63  * Returns the delta events processed.
64  */
65 u64 x86_perf_event_update(struct perf_event *event)
66 {
67         struct hw_perf_event *hwc = &event->hw;
68         int shift = 64 - x86_pmu.cntval_bits;
69         u64 prev_raw_count, new_raw_count;
70         int idx = hwc->idx;
71         u64 delta;
72
73         if (idx == INTEL_PMC_IDX_FIXED_BTS)
74                 return 0;
75
76         /*
77          * Careful: an NMI might modify the previous event value.
78          *
79          * Our tactic to handle this is to first atomically read and
80          * exchange a new raw count - then add that new-prev delta
81          * count to the generic event atomically:
82          */
83 again:
84         prev_raw_count = local64_read(&hwc->prev_count);
85         rdpmcl(hwc->event_base_rdpmc, new_raw_count);
86
87         if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
88                                         new_raw_count) != prev_raw_count)
89                 goto again;
90
91         /*
92          * Now we have the new raw value and have updated the prev
93          * timestamp already. We can now calculate the elapsed delta
94          * (event-)time and add that to the generic event.
95          *
96          * Careful, not all hw sign-extends above the physical width
97          * of the count.
98          */
99         delta = (new_raw_count << shift) - (prev_raw_count << shift);
100         delta >>= shift;
101
102         local64_add(delta, &event->count);
103         local64_sub(delta, &hwc->period_left);
104
105         return new_raw_count;
106 }
107
108 /*
109  * Find and validate any extra registers to set up.
110  */
111 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
112 {
113         struct hw_perf_event_extra *reg;
114         struct extra_reg *er;
115
116         reg = &event->hw.extra_reg;
117
118         if (!x86_pmu.extra_regs)
119                 return 0;
120
121         for (er = x86_pmu.extra_regs; er->msr; er++) {
122                 if (er->event != (config & er->config_mask))
123                         continue;
124                 if (event->attr.config1 & ~er->valid_mask)
125                         return -EINVAL;
126                 /* Check if the extra msrs can be safely accessed*/
127                 if (!er->extra_msr_access)
128                         return -ENXIO;
129
130                 reg->idx = er->idx;
131                 reg->config = event->attr.config1;
132                 reg->reg = er->msr;
133                 break;
134         }
135         return 0;
136 }
137
138 static atomic_t active_events;
139 static atomic_t pmc_refcount;
140 static DEFINE_MUTEX(pmc_reserve_mutex);
141
142 #ifdef CONFIG_X86_LOCAL_APIC
143
144 static bool reserve_pmc_hardware(void)
145 {
146         int i;
147
148         for (i = 0; i < x86_pmu.num_counters; i++) {
149                 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
150                         goto perfctr_fail;
151         }
152
153         for (i = 0; i < x86_pmu.num_counters; i++) {
154                 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
155                         goto eventsel_fail;
156         }
157
158         return true;
159
160 eventsel_fail:
161         for (i--; i >= 0; i--)
162                 release_evntsel_nmi(x86_pmu_config_addr(i));
163
164         i = x86_pmu.num_counters;
165
166 perfctr_fail:
167         for (i--; i >= 0; i--)
168                 release_perfctr_nmi(x86_pmu_event_addr(i));
169
170         return false;
171 }
172
173 static void release_pmc_hardware(void)
174 {
175         int i;
176
177         for (i = 0; i < x86_pmu.num_counters; i++) {
178                 release_perfctr_nmi(x86_pmu_event_addr(i));
179                 release_evntsel_nmi(x86_pmu_config_addr(i));
180         }
181 }
182
183 #else
184
185 static bool reserve_pmc_hardware(void) { return true; }
186 static void release_pmc_hardware(void) {}
187
188 #endif
189
190 static bool check_hw_exists(void)
191 {
192         u64 val, val_fail = -1, val_new= ~0;
193         int i, reg, reg_fail = -1, ret = 0;
194         int bios_fail = 0;
195         int reg_safe = -1;
196
197         /*
198          * Check to see if the BIOS enabled any of the counters, if so
199          * complain and bail.
200          */
201         for (i = 0; i < x86_pmu.num_counters; i++) {
202                 reg = x86_pmu_config_addr(i);
203                 ret = rdmsrl_safe(reg, &val);
204                 if (ret)
205                         goto msr_fail;
206                 if (val & ARCH_PERFMON_EVENTSEL_ENABLE) {
207                         bios_fail = 1;
208                         val_fail = val;
209                         reg_fail = reg;
210                 } else {
211                         reg_safe = i;
212                 }
213         }
214
215         if (x86_pmu.num_counters_fixed) {
216                 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
217                 ret = rdmsrl_safe(reg, &val);
218                 if (ret)
219                         goto msr_fail;
220                 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
221                         if (val & (0x03 << i*4)) {
222                                 bios_fail = 1;
223                                 val_fail = val;
224                                 reg_fail = reg;
225                         }
226                 }
227         }
228
229         /*
230          * If all the counters are enabled, the below test will always
231          * fail.  The tools will also become useless in this scenario.
232          * Just fail and disable the hardware counters.
233          */
234
235         if (reg_safe == -1) {
236                 reg = reg_safe;
237                 goto msr_fail;
238         }
239
240         /*
241          * Read the current value, change it and read it back to see if it
242          * matches, this is needed to detect certain hardware emulators
243          * (qemu/kvm) that don't trap on the MSR access and always return 0s.
244          */
245         reg = x86_pmu_event_addr(reg_safe);
246         if (rdmsrl_safe(reg, &val))
247                 goto msr_fail;
248         val ^= 0xffffUL;
249         ret = wrmsrl_safe(reg, val);
250         ret |= rdmsrl_safe(reg, &val_new);
251         if (ret || val != val_new)
252                 goto msr_fail;
253
254         /*
255          * We still allow the PMU driver to operate:
256          */
257         if (bios_fail) {
258                 printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
259                 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg_fail, val_fail);
260         }
261
262         return true;
263
264 msr_fail:
265         printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
266         printk("%sFailed to access perfctr msr (MSR %x is %Lx)\n",
267                 boot_cpu_has(X86_FEATURE_HYPERVISOR) ? KERN_INFO : KERN_ERR,
268                 reg, val_new);
269
270         return false;
271 }
272
273 static void hw_perf_event_destroy(struct perf_event *event)
274 {
275         x86_release_hardware();
276         atomic_dec(&active_events);
277 }
278
279 void hw_perf_lbr_event_destroy(struct perf_event *event)
280 {
281         hw_perf_event_destroy(event);
282
283         /* undo the lbr/bts event accounting */
284         x86_del_exclusive(x86_lbr_exclusive_lbr);
285 }
286
287 static inline int x86_pmu_initialized(void)
288 {
289         return x86_pmu.handle_irq != NULL;
290 }
291
292 static inline int
293 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
294 {
295         struct perf_event_attr *attr = &event->attr;
296         unsigned int cache_type, cache_op, cache_result;
297         u64 config, val;
298
299         config = attr->config;
300
301         cache_type = (config >> 0) & 0xff;
302         if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
303                 return -EINVAL;
304         cache_type = array_index_nospec(cache_type, PERF_COUNT_HW_CACHE_MAX);
305
306         cache_op = (config >>  8) & 0xff;
307         if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
308                 return -EINVAL;
309         cache_op = array_index_nospec(cache_op, PERF_COUNT_HW_CACHE_OP_MAX);
310
311         cache_result = (config >> 16) & 0xff;
312         if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
313                 return -EINVAL;
314         cache_result = array_index_nospec(cache_result, PERF_COUNT_HW_CACHE_RESULT_MAX);
315
316         val = hw_cache_event_ids[cache_type][cache_op][cache_result];
317
318         if (val == 0)
319                 return -ENOENT;
320
321         if (val == -1)
322                 return -EINVAL;
323
324         hwc->config |= val;
325         attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
326         return x86_pmu_extra_regs(val, event);
327 }
328
329 int x86_reserve_hardware(void)
330 {
331         int err = 0;
332
333         if (!atomic_inc_not_zero(&pmc_refcount)) {
334                 mutex_lock(&pmc_reserve_mutex);
335                 if (atomic_read(&pmc_refcount) == 0) {
336                         if (!reserve_pmc_hardware())
337                                 err = -EBUSY;
338                         else
339                                 reserve_ds_buffers();
340                 }
341                 if (!err)
342                         atomic_inc(&pmc_refcount);
343                 mutex_unlock(&pmc_reserve_mutex);
344         }
345
346         return err;
347 }
348
349 void x86_release_hardware(void)
350 {
351         if (atomic_dec_and_mutex_lock(&pmc_refcount, &pmc_reserve_mutex)) {
352                 release_pmc_hardware();
353                 release_ds_buffers();
354                 mutex_unlock(&pmc_reserve_mutex);
355         }
356 }
357
358 /*
359  * Check if we can create event of a certain type (that no conflicting events
360  * are present).
361  */
362 int x86_add_exclusive(unsigned int what)
363 {
364         int i;
365
366         if (!atomic_inc_not_zero(&x86_pmu.lbr_exclusive[what])) {
367                 mutex_lock(&pmc_reserve_mutex);
368                 for (i = 0; i < ARRAY_SIZE(x86_pmu.lbr_exclusive); i++) {
369                         if (i != what && atomic_read(&x86_pmu.lbr_exclusive[i]))
370                                 goto fail_unlock;
371                 }
372                 atomic_inc(&x86_pmu.lbr_exclusive[what]);
373                 mutex_unlock(&pmc_reserve_mutex);
374         }
375
376         atomic_inc(&active_events);
377         return 0;
378
379 fail_unlock:
380         mutex_unlock(&pmc_reserve_mutex);
381         return -EBUSY;
382 }
383
384 void x86_del_exclusive(unsigned int what)
385 {
386         atomic_dec(&x86_pmu.lbr_exclusive[what]);
387         atomic_dec(&active_events);
388 }
389
390 int x86_setup_perfctr(struct perf_event *event)
391 {
392         struct perf_event_attr *attr = &event->attr;
393         struct hw_perf_event *hwc = &event->hw;
394         u64 config;
395
396         if (!is_sampling_event(event)) {
397                 hwc->sample_period = x86_pmu.max_period;
398                 hwc->last_period = hwc->sample_period;
399                 local64_set(&hwc->period_left, hwc->sample_period);
400         }
401
402         if (attr->type == PERF_TYPE_RAW)
403                 return x86_pmu_extra_regs(event->attr.config, event);
404
405         if (attr->type == PERF_TYPE_HW_CACHE)
406                 return set_ext_hw_attr(hwc, event);
407
408         if (attr->config >= x86_pmu.max_events)
409                 return -EINVAL;
410
411         attr->config = array_index_nospec((unsigned long)attr->config, x86_pmu.max_events);
412
413         /*
414          * The generic map:
415          */
416         config = x86_pmu.event_map(attr->config);
417
418         if (config == 0)
419                 return -ENOENT;
420
421         if (config == -1LL)
422                 return -EINVAL;
423
424         /*
425          * Branch tracing:
426          */
427         if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
428             !attr->freq && hwc->sample_period == 1) {
429                 /* BTS is not supported by this architecture. */
430                 if (!x86_pmu.bts_active)
431                         return -EOPNOTSUPP;
432
433                 /* BTS is currently only allowed for user-mode. */
434                 if (!attr->exclude_kernel)
435                         return -EOPNOTSUPP;
436
437                 /* disallow bts if conflicting events are present */
438                 if (x86_add_exclusive(x86_lbr_exclusive_lbr))
439                         return -EBUSY;
440
441                 event->destroy = hw_perf_lbr_event_destroy;
442         }
443
444         hwc->config |= config;
445
446         return 0;
447 }
448
449 /*
450  * check that branch_sample_type is compatible with
451  * settings needed for precise_ip > 1 which implies
452  * using the LBR to capture ALL taken branches at the
453  * priv levels of the measurement
454  */
455 static inline int precise_br_compat(struct perf_event *event)
456 {
457         u64 m = event->attr.branch_sample_type;
458         u64 b = 0;
459
460         /* must capture all branches */
461         if (!(m & PERF_SAMPLE_BRANCH_ANY))
462                 return 0;
463
464         m &= PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_USER;
465
466         if (!event->attr.exclude_user)
467                 b |= PERF_SAMPLE_BRANCH_USER;
468
469         if (!event->attr.exclude_kernel)
470                 b |= PERF_SAMPLE_BRANCH_KERNEL;
471
472         /*
473          * ignore PERF_SAMPLE_BRANCH_HV, not supported on x86
474          */
475
476         return m == b;
477 }
478
479 int x86_pmu_hw_config(struct perf_event *event)
480 {
481         if (event->attr.precise_ip) {
482                 int precise = 0;
483
484                 /* Support for constant skid */
485                 if (x86_pmu.pebs_active && !x86_pmu.pebs_broken) {
486                         precise++;
487
488                         /* Support for IP fixup */
489                         if (x86_pmu.lbr_nr || x86_pmu.intel_cap.pebs_format >= 2)
490                                 precise++;
491                 }
492
493                 if (event->attr.precise_ip > precise)
494                         return -EOPNOTSUPP;
495         }
496         /*
497          * check that PEBS LBR correction does not conflict with
498          * whatever the user is asking with attr->branch_sample_type
499          */
500         if (event->attr.precise_ip > 1 && x86_pmu.intel_cap.pebs_format < 2) {
501                 u64 *br_type = &event->attr.branch_sample_type;
502
503                 if (has_branch_stack(event)) {
504                         if (!precise_br_compat(event))
505                                 return -EOPNOTSUPP;
506
507                         /* branch_sample_type is compatible */
508
509                 } else {
510                         /*
511                          * user did not specify  branch_sample_type
512                          *
513                          * For PEBS fixups, we capture all
514                          * the branches at the priv level of the
515                          * event.
516                          */
517                         *br_type = PERF_SAMPLE_BRANCH_ANY;
518
519                         if (!event->attr.exclude_user)
520                                 *br_type |= PERF_SAMPLE_BRANCH_USER;
521
522                         if (!event->attr.exclude_kernel)
523                                 *br_type |= PERF_SAMPLE_BRANCH_KERNEL;
524                 }
525         }
526
527         if (event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_CALL_STACK)
528                 event->attach_state |= PERF_ATTACH_TASK_DATA;
529
530         /*
531          * Generate PMC IRQs:
532          * (keep 'enabled' bit clear for now)
533          */
534         event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
535
536         /*
537          * Count user and OS events unless requested not to
538          */
539         if (!event->attr.exclude_user)
540                 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
541         if (!event->attr.exclude_kernel)
542                 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
543
544         if (event->attr.type == PERF_TYPE_RAW)
545                 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
546
547         if (event->attr.sample_period && x86_pmu.limit_period) {
548                 if (x86_pmu.limit_period(event, event->attr.sample_period) >
549                                 event->attr.sample_period)
550                         return -EINVAL;
551         }
552
553         return x86_setup_perfctr(event);
554 }
555
556 /*
557  * Setup the hardware configuration for a given attr_type
558  */
559 static int __x86_pmu_event_init(struct perf_event *event)
560 {
561         int err;
562
563         if (!x86_pmu_initialized())
564                 return -ENODEV;
565
566         err = x86_reserve_hardware();
567         if (err)
568                 return err;
569
570         atomic_inc(&active_events);
571         event->destroy = hw_perf_event_destroy;
572
573         event->hw.idx = -1;
574         event->hw.last_cpu = -1;
575         event->hw.last_tag = ~0ULL;
576
577         /* mark unused */
578         event->hw.extra_reg.idx = EXTRA_REG_NONE;
579         event->hw.branch_reg.idx = EXTRA_REG_NONE;
580
581         return x86_pmu.hw_config(event);
582 }
583
584 void x86_pmu_disable_all(void)
585 {
586         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
587         int idx;
588
589         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
590                 u64 val;
591
592                 if (!test_bit(idx, cpuc->active_mask))
593                         continue;
594                 rdmsrl(x86_pmu_config_addr(idx), val);
595                 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
596                         continue;
597                 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
598                 wrmsrl(x86_pmu_config_addr(idx), val);
599         }
600 }
601
602 /*
603  * There may be PMI landing after enabled=0. The PMI hitting could be before or
604  * after disable_all.
605  *
606  * If PMI hits before disable_all, the PMU will be disabled in the NMI handler.
607  * It will not be re-enabled in the NMI handler again, because enabled=0. After
608  * handling the NMI, disable_all will be called, which will not change the
609  * state either. If PMI hits after disable_all, the PMU is already disabled
610  * before entering NMI handler. The NMI handler will not change the state
611  * either.
612  *
613  * So either situation is harmless.
614  */
615 static void x86_pmu_disable(struct pmu *pmu)
616 {
617         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
618
619         if (!x86_pmu_initialized())
620                 return;
621
622         if (!cpuc->enabled)
623                 return;
624
625         cpuc->n_added = 0;
626         cpuc->enabled = 0;
627         barrier();
628
629         x86_pmu.disable_all();
630 }
631
632 void x86_pmu_enable_all(int added)
633 {
634         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
635         int idx;
636
637         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
638                 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
639
640                 if (!test_bit(idx, cpuc->active_mask))
641                         continue;
642
643                 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
644         }
645 }
646
647 static struct pmu pmu;
648
649 static inline int is_x86_event(struct perf_event *event)
650 {
651         return event->pmu == &pmu;
652 }
653
654 /*
655  * Event scheduler state:
656  *
657  * Assign events iterating over all events and counters, beginning
658  * with events with least weights first. Keep the current iterator
659  * state in struct sched_state.
660  */
661 struct sched_state {
662         int     weight;
663         int     event;          /* event index */
664         int     counter;        /* counter index */
665         int     unassigned;     /* number of events to be assigned left */
666         int     nr_gp;          /* number of GP counters used */
667         unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
668 };
669
670 /* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
671 #define SCHED_STATES_MAX        2
672
673 struct perf_sched {
674         int                     max_weight;
675         int                     max_events;
676         int                     max_gp;
677         int                     saved_states;
678         struct event_constraint **constraints;
679         struct sched_state      state;
680         struct sched_state      saved[SCHED_STATES_MAX];
681 };
682
683 /*
684  * Initialize interator that runs through all events and counters.
685  */
686 static void perf_sched_init(struct perf_sched *sched, struct event_constraint **constraints,
687                             int num, int wmin, int wmax, int gpmax)
688 {
689         int idx;
690
691         memset(sched, 0, sizeof(*sched));
692         sched->max_events       = num;
693         sched->max_weight       = wmax;
694         sched->max_gp           = gpmax;
695         sched->constraints      = constraints;
696
697         for (idx = 0; idx < num; idx++) {
698                 if (constraints[idx]->weight == wmin)
699                         break;
700         }
701
702         sched->state.event      = idx;          /* start with min weight */
703         sched->state.weight     = wmin;
704         sched->state.unassigned = num;
705 }
706
707 static void perf_sched_save_state(struct perf_sched *sched)
708 {
709         if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
710                 return;
711
712         sched->saved[sched->saved_states] = sched->state;
713         sched->saved_states++;
714 }
715
716 static bool perf_sched_restore_state(struct perf_sched *sched)
717 {
718         if (!sched->saved_states)
719                 return false;
720
721         sched->saved_states--;
722         sched->state = sched->saved[sched->saved_states];
723
724         /* continue with next counter: */
725         clear_bit(sched->state.counter++, sched->state.used);
726
727         return true;
728 }
729
730 /*
731  * Select a counter for the current event to schedule. Return true on
732  * success.
733  */
734 static bool __perf_sched_find_counter(struct perf_sched *sched)
735 {
736         struct event_constraint *c;
737         int idx;
738
739         if (!sched->state.unassigned)
740                 return false;
741
742         if (sched->state.event >= sched->max_events)
743                 return false;
744
745         c = sched->constraints[sched->state.event];
746         /* Prefer fixed purpose counters */
747         if (c->idxmsk64 & (~0ULL << INTEL_PMC_IDX_FIXED)) {
748                 idx = INTEL_PMC_IDX_FIXED;
749                 for_each_set_bit_from(idx, c->idxmsk, X86_PMC_IDX_MAX) {
750                         if (!__test_and_set_bit(idx, sched->state.used))
751                                 goto done;
752                 }
753         }
754
755         /* Grab the first unused counter starting with idx */
756         idx = sched->state.counter;
757         for_each_set_bit_from(idx, c->idxmsk, INTEL_PMC_IDX_FIXED) {
758                 if (!__test_and_set_bit(idx, sched->state.used)) {
759                         if (sched->state.nr_gp++ >= sched->max_gp)
760                                 return false;
761
762                         goto done;
763                 }
764         }
765
766         return false;
767
768 done:
769         sched->state.counter = idx;
770
771         if (c->overlap)
772                 perf_sched_save_state(sched);
773
774         return true;
775 }
776
777 static bool perf_sched_find_counter(struct perf_sched *sched)
778 {
779         while (!__perf_sched_find_counter(sched)) {
780                 if (!perf_sched_restore_state(sched))
781                         return false;
782         }
783
784         return true;
785 }
786
787 /*
788  * Go through all unassigned events and find the next one to schedule.
789  * Take events with the least weight first. Return true on success.
790  */
791 static bool perf_sched_next_event(struct perf_sched *sched)
792 {
793         struct event_constraint *c;
794
795         if (!sched->state.unassigned || !--sched->state.unassigned)
796                 return false;
797
798         do {
799                 /* next event */
800                 sched->state.event++;
801                 if (sched->state.event >= sched->max_events) {
802                         /* next weight */
803                         sched->state.event = 0;
804                         sched->state.weight++;
805                         if (sched->state.weight > sched->max_weight)
806                                 return false;
807                 }
808                 c = sched->constraints[sched->state.event];
809         } while (c->weight != sched->state.weight);
810
811         sched->state.counter = 0;       /* start with first counter */
812
813         return true;
814 }
815
816 /*
817  * Assign a counter for each event.
818  */
819 int perf_assign_events(struct event_constraint **constraints, int n,
820                         int wmin, int wmax, int gpmax, int *assign)
821 {
822         struct perf_sched sched;
823
824         perf_sched_init(&sched, constraints, n, wmin, wmax, gpmax);
825
826         do {
827                 if (!perf_sched_find_counter(&sched))
828                         break;  /* failed */
829                 if (assign)
830                         assign[sched.state.event] = sched.state.counter;
831         } while (perf_sched_next_event(&sched));
832
833         return sched.state.unassigned;
834 }
835 EXPORT_SYMBOL_GPL(perf_assign_events);
836
837 int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
838 {
839         struct event_constraint *c;
840         unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
841         struct perf_event *e;
842         int i, wmin, wmax, unsched = 0;
843         struct hw_perf_event *hwc;
844
845         bitmap_zero(used_mask, X86_PMC_IDX_MAX);
846
847         if (x86_pmu.start_scheduling)
848                 x86_pmu.start_scheduling(cpuc);
849
850         for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
851                 cpuc->event_constraint[i] = NULL;
852                 c = x86_pmu.get_event_constraints(cpuc, i, cpuc->event_list[i]);
853                 cpuc->event_constraint[i] = c;
854
855                 wmin = min(wmin, c->weight);
856                 wmax = max(wmax, c->weight);
857         }
858
859         /*
860          * fastpath, try to reuse previous register
861          */
862         for (i = 0; i < n; i++) {
863                 hwc = &cpuc->event_list[i]->hw;
864                 c = cpuc->event_constraint[i];
865
866                 /* never assigned */
867                 if (hwc->idx == -1)
868                         break;
869
870                 /* constraint still honored */
871                 if (!test_bit(hwc->idx, c->idxmsk))
872                         break;
873
874                 /* not already used */
875                 if (test_bit(hwc->idx, used_mask))
876                         break;
877
878                 __set_bit(hwc->idx, used_mask);
879                 if (assign)
880                         assign[i] = hwc->idx;
881         }
882
883         /* slow path */
884         if (i != n) {
885                 int gpmax = x86_pmu.num_counters;
886
887                 /*
888                  * Do not allow scheduling of more than half the available
889                  * generic counters.
890                  *
891                  * This helps avoid counter starvation of sibling thread by
892                  * ensuring at most half the counters cannot be in exclusive
893                  * mode. There is no designated counters for the limits. Any
894                  * N/2 counters can be used. This helps with events with
895                  * specific counter constraints.
896                  */
897                 if (is_ht_workaround_enabled() && !cpuc->is_fake &&
898                     READ_ONCE(cpuc->excl_cntrs->exclusive_present))
899                         gpmax /= 2;
900
901                 unsched = perf_assign_events(cpuc->event_constraint, n, wmin,
902                                              wmax, gpmax, assign);
903         }
904
905         /*
906          * In case of success (unsched = 0), mark events as committed,
907          * so we do not put_constraint() in case new events are added
908          * and fail to be scheduled
909          *
910          * We invoke the lower level commit callback to lock the resource
911          *
912          * We do not need to do all of this in case we are called to
913          * validate an event group (assign == NULL)
914          */
915         if (!unsched && assign) {
916                 for (i = 0; i < n; i++) {
917                         e = cpuc->event_list[i];
918                         e->hw.flags |= PERF_X86_EVENT_COMMITTED;
919                         if (x86_pmu.commit_scheduling)
920                                 x86_pmu.commit_scheduling(cpuc, i, assign[i]);
921                 }
922         } else {
923                 for (i = 0; i < n; i++) {
924                         e = cpuc->event_list[i];
925                         /*
926                          * do not put_constraint() on comitted events,
927                          * because they are good to go
928                          */
929                         if ((e->hw.flags & PERF_X86_EVENT_COMMITTED))
930                                 continue;
931
932                         /*
933                          * release events that failed scheduling
934                          */
935                         if (x86_pmu.put_event_constraints)
936                                 x86_pmu.put_event_constraints(cpuc, e);
937                 }
938         }
939
940         if (x86_pmu.stop_scheduling)
941                 x86_pmu.stop_scheduling(cpuc);
942
943         return unsched ? -EINVAL : 0;
944 }
945
946 /*
947  * dogrp: true if must collect siblings events (group)
948  * returns total number of events and error code
949  */
950 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
951 {
952         struct perf_event *event;
953         int n, max_count;
954
955         max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
956
957         /* current number of events already accepted */
958         n = cpuc->n_events;
959
960         if (is_x86_event(leader)) {
961                 if (n >= max_count)
962                         return -EINVAL;
963                 cpuc->event_list[n] = leader;
964                 n++;
965         }
966         if (!dogrp)
967                 return n;
968
969         list_for_each_entry(event, &leader->sibling_list, group_entry) {
970                 if (!is_x86_event(event) ||
971                     event->state <= PERF_EVENT_STATE_OFF)
972                         continue;
973
974                 if (n >= max_count)
975                         return -EINVAL;
976
977                 cpuc->event_list[n] = event;
978                 n++;
979         }
980         return n;
981 }
982
983 static inline void x86_assign_hw_event(struct perf_event *event,
984                                 struct cpu_hw_events *cpuc, int i)
985 {
986         struct hw_perf_event *hwc = &event->hw;
987
988         hwc->idx = cpuc->assign[i];
989         hwc->last_cpu = smp_processor_id();
990         hwc->last_tag = ++cpuc->tags[i];
991
992         if (hwc->idx == INTEL_PMC_IDX_FIXED_BTS) {
993                 hwc->config_base = 0;
994                 hwc->event_base = 0;
995         } else if (hwc->idx >= INTEL_PMC_IDX_FIXED) {
996                 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
997                 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - INTEL_PMC_IDX_FIXED);
998                 hwc->event_base_rdpmc = (hwc->idx - INTEL_PMC_IDX_FIXED) | 1<<30;
999         } else {
1000                 hwc->config_base = x86_pmu_config_addr(hwc->idx);
1001                 hwc->event_base  = x86_pmu_event_addr(hwc->idx);
1002                 hwc->event_base_rdpmc = x86_pmu_rdpmc_index(hwc->idx);
1003         }
1004 }
1005
1006 static inline int match_prev_assignment(struct hw_perf_event *hwc,
1007                                         struct cpu_hw_events *cpuc,
1008                                         int i)
1009 {
1010         return hwc->idx == cpuc->assign[i] &&
1011                 hwc->last_cpu == smp_processor_id() &&
1012                 hwc->last_tag == cpuc->tags[i];
1013 }
1014
1015 static void x86_pmu_start(struct perf_event *event, int flags);
1016
1017 static void x86_pmu_enable(struct pmu *pmu)
1018 {
1019         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1020         struct perf_event *event;
1021         struct hw_perf_event *hwc;
1022         int i, added = cpuc->n_added;
1023
1024         if (!x86_pmu_initialized())
1025                 return;
1026
1027         if (cpuc->enabled)
1028                 return;
1029
1030         if (cpuc->n_added) {
1031                 int n_running = cpuc->n_events - cpuc->n_added;
1032                 /*
1033                  * apply assignment obtained either from
1034                  * hw_perf_group_sched_in() or x86_pmu_enable()
1035                  *
1036                  * step1: save events moving to new counters
1037                  */
1038                 for (i = 0; i < n_running; i++) {
1039                         event = cpuc->event_list[i];
1040                         hwc = &event->hw;
1041
1042                         /*
1043                          * we can avoid reprogramming counter if:
1044                          * - assigned same counter as last time
1045                          * - running on same CPU as last time
1046                          * - no other event has used the counter since
1047                          */
1048                         if (hwc->idx == -1 ||
1049                             match_prev_assignment(hwc, cpuc, i))
1050                                 continue;
1051
1052                         /*
1053                          * Ensure we don't accidentally enable a stopped
1054                          * counter simply because we rescheduled.
1055                          */
1056                         if (hwc->state & PERF_HES_STOPPED)
1057                                 hwc->state |= PERF_HES_ARCH;
1058
1059                         x86_pmu_stop(event, PERF_EF_UPDATE);
1060                 }
1061
1062                 /*
1063                  * step2: reprogram moved events into new counters
1064                  */
1065                 for (i = 0; i < cpuc->n_events; i++) {
1066                         event = cpuc->event_list[i];
1067                         hwc = &event->hw;
1068
1069                         if (!match_prev_assignment(hwc, cpuc, i))
1070                                 x86_assign_hw_event(event, cpuc, i);
1071                         else if (i < n_running)
1072                                 continue;
1073
1074                         if (hwc->state & PERF_HES_ARCH)
1075                                 continue;
1076
1077                         x86_pmu_start(event, PERF_EF_RELOAD);
1078                 }
1079                 cpuc->n_added = 0;
1080                 perf_events_lapic_init();
1081         }
1082
1083         cpuc->enabled = 1;
1084         barrier();
1085
1086         x86_pmu.enable_all(added);
1087 }
1088
1089 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
1090
1091 /*
1092  * Set the next IRQ period, based on the hwc->period_left value.
1093  * To be called with the event disabled in hw:
1094  */
1095 int x86_perf_event_set_period(struct perf_event *event)
1096 {
1097         struct hw_perf_event *hwc = &event->hw;
1098         s64 left = local64_read(&hwc->period_left);
1099         s64 period = hwc->sample_period;
1100         int ret = 0, idx = hwc->idx;
1101
1102         if (idx == INTEL_PMC_IDX_FIXED_BTS)
1103                 return 0;
1104
1105         /*
1106          * If we are way outside a reasonable range then just skip forward:
1107          */
1108         if (unlikely(left <= -period)) {
1109                 left = period;
1110                 local64_set(&hwc->period_left, left);
1111                 hwc->last_period = period;
1112                 ret = 1;
1113         }
1114
1115         if (unlikely(left <= 0)) {
1116                 left += period;
1117                 local64_set(&hwc->period_left, left);
1118                 hwc->last_period = period;
1119                 ret = 1;
1120         }
1121         /*
1122          * Quirk: certain CPUs dont like it if just 1 hw_event is left:
1123          */
1124         if (unlikely(left < 2))
1125                 left = 2;
1126
1127         if (left > x86_pmu.max_period)
1128                 left = x86_pmu.max_period;
1129
1130         if (x86_pmu.limit_period)
1131                 left = x86_pmu.limit_period(event, left);
1132
1133         per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
1134
1135         if (!(hwc->flags & PERF_X86_EVENT_AUTO_RELOAD) ||
1136             local64_read(&hwc->prev_count) != (u64)-left) {
1137                 /*
1138                  * The hw event starts counting from this event offset,
1139                  * mark it to be able to extra future deltas:
1140                  */
1141                 local64_set(&hwc->prev_count, (u64)-left);
1142
1143                 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
1144         }
1145
1146         /*
1147          * Due to erratum on certan cpu we need
1148          * a second write to be sure the register
1149          * is updated properly
1150          */
1151         if (x86_pmu.perfctr_second_write) {
1152                 wrmsrl(hwc->event_base,
1153                         (u64)(-left) & x86_pmu.cntval_mask);
1154         }
1155
1156         perf_event_update_userpage(event);
1157
1158         return ret;
1159 }
1160
1161 void x86_pmu_enable_event(struct perf_event *event)
1162 {
1163         if (__this_cpu_read(cpu_hw_events.enabled))
1164                 __x86_pmu_enable_event(&event->hw,
1165                                        ARCH_PERFMON_EVENTSEL_ENABLE);
1166 }
1167
1168 /*
1169  * Add a single event to the PMU.
1170  *
1171  * The event is added to the group of enabled events
1172  * but only if it can be scehduled with existing events.
1173  */
1174 static int x86_pmu_add(struct perf_event *event, int flags)
1175 {
1176         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1177         struct hw_perf_event *hwc;
1178         int assign[X86_PMC_IDX_MAX];
1179         int n, n0, ret;
1180
1181         hwc = &event->hw;
1182
1183         n0 = cpuc->n_events;
1184         ret = n = collect_events(cpuc, event, false);
1185         if (ret < 0)
1186                 goto out;
1187
1188         hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1189         if (!(flags & PERF_EF_START))
1190                 hwc->state |= PERF_HES_ARCH;
1191
1192         /*
1193          * If group events scheduling transaction was started,
1194          * skip the schedulability test here, it will be performed
1195          * at commit time (->commit_txn) as a whole.
1196          */
1197         if (cpuc->txn_flags & PERF_PMU_TXN_ADD)
1198                 goto done_collect;
1199
1200         ret = x86_pmu.schedule_events(cpuc, n, assign);
1201         if (ret)
1202                 goto out;
1203         /*
1204          * copy new assignment, now we know it is possible
1205          * will be used by hw_perf_enable()
1206          */
1207         memcpy(cpuc->assign, assign, n*sizeof(int));
1208
1209 done_collect:
1210         /*
1211          * Commit the collect_events() state. See x86_pmu_del() and
1212          * x86_pmu_*_txn().
1213          */
1214         cpuc->n_events = n;
1215         cpuc->n_added += n - n0;
1216         cpuc->n_txn += n - n0;
1217
1218         ret = 0;
1219 out:
1220         return ret;
1221 }
1222
1223 static void x86_pmu_start(struct perf_event *event, int flags)
1224 {
1225         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1226         int idx = event->hw.idx;
1227
1228         if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1229                 return;
1230
1231         if (WARN_ON_ONCE(idx == -1))
1232                 return;
1233
1234         if (flags & PERF_EF_RELOAD) {
1235                 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1236                 x86_perf_event_set_period(event);
1237         }
1238
1239         event->hw.state = 0;
1240
1241         cpuc->events[idx] = event;
1242         __set_bit(idx, cpuc->active_mask);
1243         __set_bit(idx, cpuc->running);
1244         x86_pmu.enable(event);
1245         perf_event_update_userpage(event);
1246 }
1247
1248 void perf_event_print_debug(void)
1249 {
1250         u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1251         u64 pebs, debugctl;
1252         struct cpu_hw_events *cpuc;
1253         unsigned long flags;
1254         int cpu, idx;
1255
1256         if (!x86_pmu.num_counters)
1257                 return;
1258
1259         local_irq_save(flags);
1260
1261         cpu = smp_processor_id();
1262         cpuc = &per_cpu(cpu_hw_events, cpu);
1263
1264         if (x86_pmu.version >= 2) {
1265                 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1266                 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1267                 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1268                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1269
1270                 pr_info("\n");
1271                 pr_info("CPU#%d: ctrl:       %016llx\n", cpu, ctrl);
1272                 pr_info("CPU#%d: status:     %016llx\n", cpu, status);
1273                 pr_info("CPU#%d: overflow:   %016llx\n", cpu, overflow);
1274                 pr_info("CPU#%d: fixed:      %016llx\n", cpu, fixed);
1275                 if (x86_pmu.pebs_constraints) {
1276                         rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1277                         pr_info("CPU#%d: pebs:       %016llx\n", cpu, pebs);
1278                 }
1279                 if (x86_pmu.lbr_nr) {
1280                         rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
1281                         pr_info("CPU#%d: debugctl:   %016llx\n", cpu, debugctl);
1282                 }
1283         }
1284         pr_info("CPU#%d: active:     %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1285
1286         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1287                 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1288                 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1289
1290                 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1291
1292                 pr_info("CPU#%d:   gen-PMC%d ctrl:  %016llx\n",
1293                         cpu, idx, pmc_ctrl);
1294                 pr_info("CPU#%d:   gen-PMC%d count: %016llx\n",
1295                         cpu, idx, pmc_count);
1296                 pr_info("CPU#%d:   gen-PMC%d left:  %016llx\n",
1297                         cpu, idx, prev_left);
1298         }
1299         for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1300                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1301
1302                 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1303                         cpu, idx, pmc_count);
1304         }
1305         local_irq_restore(flags);
1306 }
1307
1308 void x86_pmu_stop(struct perf_event *event, int flags)
1309 {
1310         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1311         struct hw_perf_event *hwc = &event->hw;
1312
1313         if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1314                 x86_pmu.disable(event);
1315                 cpuc->events[hwc->idx] = NULL;
1316                 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1317                 hwc->state |= PERF_HES_STOPPED;
1318         }
1319
1320         if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1321                 /*
1322                  * Drain the remaining delta count out of a event
1323                  * that we are disabling:
1324                  */
1325                 x86_perf_event_update(event);
1326                 hwc->state |= PERF_HES_UPTODATE;
1327         }
1328 }
1329
1330 static void x86_pmu_del(struct perf_event *event, int flags)
1331 {
1332         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1333         int i;
1334
1335         /*
1336          * event is descheduled
1337          */
1338         event->hw.flags &= ~PERF_X86_EVENT_COMMITTED;
1339
1340         /*
1341          * If we're called during a txn, we don't need to do anything.
1342          * The events never got scheduled and ->cancel_txn will truncate
1343          * the event_list.
1344          *
1345          * XXX assumes any ->del() called during a TXN will only be on
1346          * an event added during that same TXN.
1347          */
1348         if (cpuc->txn_flags & PERF_PMU_TXN_ADD)
1349                 return;
1350
1351         /*
1352          * Not a TXN, therefore cleanup properly.
1353          */
1354         x86_pmu_stop(event, PERF_EF_UPDATE);
1355
1356         for (i = 0; i < cpuc->n_events; i++) {
1357                 if (event == cpuc->event_list[i])
1358                         break;
1359         }
1360
1361         if (WARN_ON_ONCE(i == cpuc->n_events)) /* called ->del() without ->add() ? */
1362                 return;
1363
1364         /* If we have a newly added event; make sure to decrease n_added. */
1365         if (i >= cpuc->n_events - cpuc->n_added)
1366                 --cpuc->n_added;
1367
1368         if (x86_pmu.put_event_constraints)
1369                 x86_pmu.put_event_constraints(cpuc, event);
1370
1371         /* Delete the array entry. */
1372         while (++i < cpuc->n_events) {
1373                 cpuc->event_list[i-1] = cpuc->event_list[i];
1374                 cpuc->event_constraint[i-1] = cpuc->event_constraint[i];
1375         }
1376         --cpuc->n_events;
1377
1378         perf_event_update_userpage(event);
1379 }
1380
1381 int x86_pmu_handle_irq(struct pt_regs *regs)
1382 {
1383         struct perf_sample_data data;
1384         struct cpu_hw_events *cpuc;
1385         struct perf_event *event;
1386         int idx, handled = 0;
1387         u64 val;
1388
1389         cpuc = this_cpu_ptr(&cpu_hw_events);
1390
1391         /*
1392          * Some chipsets need to unmask the LVTPC in a particular spot
1393          * inside the nmi handler.  As a result, the unmasking was pushed
1394          * into all the nmi handlers.
1395          *
1396          * This generic handler doesn't seem to have any issues where the
1397          * unmasking occurs so it was left at the top.
1398          */
1399         apic_write(APIC_LVTPC, APIC_DM_NMI);
1400
1401         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1402                 if (!test_bit(idx, cpuc->active_mask)) {
1403                         /*
1404                          * Though we deactivated the counter some cpus
1405                          * might still deliver spurious interrupts still
1406                          * in flight. Catch them:
1407                          */
1408                         if (__test_and_clear_bit(idx, cpuc->running))
1409                                 handled++;
1410                         continue;
1411                 }
1412
1413                 event = cpuc->events[idx];
1414
1415                 val = x86_perf_event_update(event);
1416                 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1417                         continue;
1418
1419                 /*
1420                  * event overflow
1421                  */
1422                 handled++;
1423                 perf_sample_data_init(&data, 0, event->hw.last_period);
1424
1425                 if (!x86_perf_event_set_period(event))
1426                         continue;
1427
1428                 if (perf_event_overflow(event, &data, regs))
1429                         x86_pmu_stop(event, 0);
1430         }
1431
1432         if (handled)
1433                 inc_irq_stat(apic_perf_irqs);
1434
1435         return handled;
1436 }
1437
1438 void perf_events_lapic_init(void)
1439 {
1440         if (!x86_pmu.apic || !x86_pmu_initialized())
1441                 return;
1442
1443         /*
1444          * Always use NMI for PMU
1445          */
1446         apic_write(APIC_LVTPC, APIC_DM_NMI);
1447 }
1448
1449 static int
1450 perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
1451 {
1452         u64 start_clock;
1453         u64 finish_clock;
1454         int ret;
1455
1456         /*
1457          * All PMUs/events that share this PMI handler should make sure to
1458          * increment active_events for their events.
1459          */
1460         if (!atomic_read(&active_events))
1461                 return NMI_DONE;
1462
1463         start_clock = sched_clock();
1464         ret = x86_pmu.handle_irq(regs);
1465         finish_clock = sched_clock();
1466
1467         perf_sample_event_took(finish_clock - start_clock);
1468
1469         return ret;
1470 }
1471 NOKPROBE_SYMBOL(perf_event_nmi_handler);
1472
1473 struct event_constraint emptyconstraint;
1474 struct event_constraint unconstrained;
1475
1476 static int
1477 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1478 {
1479         unsigned int cpu = (long)hcpu;
1480         struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1481         int i, ret = NOTIFY_OK;
1482
1483         switch (action & ~CPU_TASKS_FROZEN) {
1484         case CPU_UP_PREPARE:
1485                 for (i = 0 ; i < X86_PERF_KFREE_MAX; i++)
1486                         cpuc->kfree_on_online[i] = NULL;
1487                 if (x86_pmu.cpu_prepare)
1488                         ret = x86_pmu.cpu_prepare(cpu);
1489                 break;
1490
1491         case CPU_STARTING:
1492                 if (x86_pmu.cpu_starting)
1493                         x86_pmu.cpu_starting(cpu);
1494                 break;
1495
1496         case CPU_ONLINE:
1497                 for (i = 0 ; i < X86_PERF_KFREE_MAX; i++) {
1498                         kfree(cpuc->kfree_on_online[i]);
1499                         cpuc->kfree_on_online[i] = NULL;
1500                 }
1501                 break;
1502
1503         case CPU_DYING:
1504                 if (x86_pmu.cpu_dying)
1505                         x86_pmu.cpu_dying(cpu);
1506                 break;
1507
1508         case CPU_UP_CANCELED:
1509         case CPU_DEAD:
1510                 if (x86_pmu.cpu_dead)
1511                         x86_pmu.cpu_dead(cpu);
1512                 break;
1513
1514         default:
1515                 break;
1516         }
1517
1518         return ret;
1519 }
1520
1521 static void __init pmu_check_apic(void)
1522 {
1523         if (cpu_has_apic)
1524                 return;
1525
1526         x86_pmu.apic = 0;
1527         pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1528         pr_info("no hardware sampling interrupt available.\n");
1529
1530         /*
1531          * If we have a PMU initialized but no APIC
1532          * interrupts, we cannot sample hardware
1533          * events (user-space has to fall back and
1534          * sample via a hrtimer based software event):
1535          */
1536         pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
1537
1538 }
1539
1540 static struct attribute_group x86_pmu_format_group = {
1541         .name = "format",
1542         .attrs = NULL,
1543 };
1544
1545 /*
1546  * Remove all undefined events (x86_pmu.event_map(id) == 0)
1547  * out of events_attr attributes.
1548  */
1549 static void __init filter_events(struct attribute **attrs)
1550 {
1551         struct device_attribute *d;
1552         struct perf_pmu_events_attr *pmu_attr;
1553         int offset = 0;
1554         int i, j;
1555
1556         for (i = 0; attrs[i]; i++) {
1557                 d = (struct device_attribute *)attrs[i];
1558                 pmu_attr = container_of(d, struct perf_pmu_events_attr, attr);
1559                 /* str trumps id */
1560                 if (pmu_attr->event_str)
1561                         continue;
1562                 if (x86_pmu.event_map(i + offset))
1563                         continue;
1564
1565                 for (j = i; attrs[j]; j++)
1566                         attrs[j] = attrs[j + 1];
1567
1568                 /* Check the shifted attr. */
1569                 i--;
1570
1571                 /*
1572                  * event_map() is index based, the attrs array is organized
1573                  * by increasing event index. If we shift the events, then
1574                  * we need to compensate for the event_map(), otherwise
1575                  * we are looking up the wrong event in the map
1576                  */
1577                 offset++;
1578         }
1579 }
1580
1581 /* Merge two pointer arrays */
1582 __init struct attribute **merge_attr(struct attribute **a, struct attribute **b)
1583 {
1584         struct attribute **new;
1585         int j, i;
1586
1587         for (j = 0; a[j]; j++)
1588                 ;
1589         for (i = 0; b[i]; i++)
1590                 j++;
1591         j++;
1592
1593         new = kmalloc(sizeof(struct attribute *) * j, GFP_KERNEL);
1594         if (!new)
1595                 return NULL;
1596
1597         j = 0;
1598         for (i = 0; a[i]; i++)
1599                 new[j++] = a[i];
1600         for (i = 0; b[i]; i++)
1601                 new[j++] = b[i];
1602         new[j] = NULL;
1603
1604         return new;
1605 }
1606
1607 ssize_t events_sysfs_show(struct device *dev, struct device_attribute *attr,
1608                           char *page)
1609 {
1610         struct perf_pmu_events_attr *pmu_attr = \
1611                 container_of(attr, struct perf_pmu_events_attr, attr);
1612         u64 config = x86_pmu.event_map(pmu_attr->id);
1613
1614         /* string trumps id */
1615         if (pmu_attr->event_str)
1616                 return sprintf(page, "%s", pmu_attr->event_str);
1617
1618         return x86_pmu.events_sysfs_show(page, config);
1619 }
1620
1621 EVENT_ATTR(cpu-cycles,                  CPU_CYCLES              );
1622 EVENT_ATTR(instructions,                INSTRUCTIONS            );
1623 EVENT_ATTR(cache-references,            CACHE_REFERENCES        );
1624 EVENT_ATTR(cache-misses,                CACHE_MISSES            );
1625 EVENT_ATTR(branch-instructions,         BRANCH_INSTRUCTIONS     );
1626 EVENT_ATTR(branch-misses,               BRANCH_MISSES           );
1627 EVENT_ATTR(bus-cycles,                  BUS_CYCLES              );
1628 EVENT_ATTR(stalled-cycles-frontend,     STALLED_CYCLES_FRONTEND );
1629 EVENT_ATTR(stalled-cycles-backend,      STALLED_CYCLES_BACKEND  );
1630 EVENT_ATTR(ref-cycles,                  REF_CPU_CYCLES          );
1631
1632 static struct attribute *empty_attrs;
1633
1634 static struct attribute *events_attr[] = {
1635         EVENT_PTR(CPU_CYCLES),
1636         EVENT_PTR(INSTRUCTIONS),
1637         EVENT_PTR(CACHE_REFERENCES),
1638         EVENT_PTR(CACHE_MISSES),
1639         EVENT_PTR(BRANCH_INSTRUCTIONS),
1640         EVENT_PTR(BRANCH_MISSES),
1641         EVENT_PTR(BUS_CYCLES),
1642         EVENT_PTR(STALLED_CYCLES_FRONTEND),
1643         EVENT_PTR(STALLED_CYCLES_BACKEND),
1644         EVENT_PTR(REF_CPU_CYCLES),
1645         NULL,
1646 };
1647
1648 static struct attribute_group x86_pmu_events_group = {
1649         .name = "events",
1650         .attrs = events_attr,
1651 };
1652
1653 ssize_t x86_event_sysfs_show(char *page, u64 config, u64 event)
1654 {
1655         u64 umask  = (config & ARCH_PERFMON_EVENTSEL_UMASK) >> 8;
1656         u64 cmask  = (config & ARCH_PERFMON_EVENTSEL_CMASK) >> 24;
1657         bool edge  = (config & ARCH_PERFMON_EVENTSEL_EDGE);
1658         bool pc    = (config & ARCH_PERFMON_EVENTSEL_PIN_CONTROL);
1659         bool any   = (config & ARCH_PERFMON_EVENTSEL_ANY);
1660         bool inv   = (config & ARCH_PERFMON_EVENTSEL_INV);
1661         ssize_t ret;
1662
1663         /*
1664         * We have whole page size to spend and just little data
1665         * to write, so we can safely use sprintf.
1666         */
1667         ret = sprintf(page, "event=0x%02llx", event);
1668
1669         if (umask)
1670                 ret += sprintf(page + ret, ",umask=0x%02llx", umask);
1671
1672         if (edge)
1673                 ret += sprintf(page + ret, ",edge");
1674
1675         if (pc)
1676                 ret += sprintf(page + ret, ",pc");
1677
1678         if (any)
1679                 ret += sprintf(page + ret, ",any");
1680
1681         if (inv)
1682                 ret += sprintf(page + ret, ",inv");
1683
1684         if (cmask)
1685                 ret += sprintf(page + ret, ",cmask=0x%02llx", cmask);
1686
1687         ret += sprintf(page + ret, "\n");
1688
1689         return ret;
1690 }
1691
1692 static int __init init_hw_perf_events(void)
1693 {
1694         struct x86_pmu_quirk *quirk;
1695         int err;
1696
1697         pr_info("Performance Events: ");
1698
1699         switch (boot_cpu_data.x86_vendor) {
1700         case X86_VENDOR_INTEL:
1701                 err = intel_pmu_init();
1702                 break;
1703         case X86_VENDOR_AMD:
1704                 err = amd_pmu_init();
1705                 break;
1706         default:
1707                 err = -ENOTSUPP;
1708         }
1709         if (err != 0) {
1710                 pr_cont("no PMU driver, software events only.\n");
1711                 return 0;
1712         }
1713
1714         pmu_check_apic();
1715
1716         /* sanity check that the hardware exists or is emulated */
1717         if (!check_hw_exists())
1718                 return 0;
1719
1720         pr_cont("%s PMU driver.\n", x86_pmu.name);
1721
1722         x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
1723
1724         for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
1725                 quirk->func();
1726
1727         if (!x86_pmu.intel_ctrl)
1728                 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1729
1730         perf_events_lapic_init();
1731         register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
1732
1733         unconstrained = (struct event_constraint)
1734                 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1735                                    0, x86_pmu.num_counters, 0, 0);
1736
1737         x86_pmu_format_group.attrs = x86_pmu.format_attrs;
1738
1739         if (x86_pmu.event_attrs)
1740                 x86_pmu_events_group.attrs = x86_pmu.event_attrs;
1741
1742         if (!x86_pmu.events_sysfs_show)
1743                 x86_pmu_events_group.attrs = &empty_attrs;
1744         else
1745                 filter_events(x86_pmu_events_group.attrs);
1746
1747         if (x86_pmu.cpu_events) {
1748                 struct attribute **tmp;
1749
1750                 tmp = merge_attr(x86_pmu_events_group.attrs, x86_pmu.cpu_events);
1751                 if (!WARN_ON(!tmp))
1752                         x86_pmu_events_group.attrs = tmp;
1753         }
1754
1755         pr_info("... version:                %d\n",     x86_pmu.version);
1756         pr_info("... bit width:              %d\n",     x86_pmu.cntval_bits);
1757         pr_info("... generic registers:      %d\n",     x86_pmu.num_counters);
1758         pr_info("... value mask:             %016Lx\n", x86_pmu.cntval_mask);
1759         pr_info("... max period:             %016Lx\n", x86_pmu.max_period);
1760         pr_info("... fixed-purpose events:   %d\n",     x86_pmu.num_counters_fixed);
1761         pr_info("... event mask:             %016Lx\n", x86_pmu.intel_ctrl);
1762
1763         perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1764         perf_cpu_notifier(x86_pmu_notifier);
1765
1766         return 0;
1767 }
1768 early_initcall(init_hw_perf_events);
1769
1770 static inline void x86_pmu_read(struct perf_event *event)
1771 {
1772         x86_perf_event_update(event);
1773 }
1774
1775 /*
1776  * Start group events scheduling transaction
1777  * Set the flag to make pmu::enable() not perform the
1778  * schedulability test, it will be performed at commit time
1779  *
1780  * We only support PERF_PMU_TXN_ADD transactions. Save the
1781  * transaction flags but otherwise ignore non-PERF_PMU_TXN_ADD
1782  * transactions.
1783  */
1784 static void x86_pmu_start_txn(struct pmu *pmu, unsigned int txn_flags)
1785 {
1786         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1787
1788         WARN_ON_ONCE(cpuc->txn_flags);          /* txn already in flight */
1789
1790         cpuc->txn_flags = txn_flags;
1791         if (txn_flags & ~PERF_PMU_TXN_ADD)
1792                 return;
1793
1794         perf_pmu_disable(pmu);
1795         __this_cpu_write(cpu_hw_events.n_txn, 0);
1796 }
1797
1798 /*
1799  * Stop group events scheduling transaction
1800  * Clear the flag and pmu::enable() will perform the
1801  * schedulability test.
1802  */
1803 static void x86_pmu_cancel_txn(struct pmu *pmu)
1804 {
1805         unsigned int txn_flags;
1806         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1807
1808         WARN_ON_ONCE(!cpuc->txn_flags); /* no txn in flight */
1809
1810         txn_flags = cpuc->txn_flags;
1811         cpuc->txn_flags = 0;
1812         if (txn_flags & ~PERF_PMU_TXN_ADD)
1813                 return;
1814
1815         /*
1816          * Truncate collected array by the number of events added in this
1817          * transaction. See x86_pmu_add() and x86_pmu_*_txn().
1818          */
1819         __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1820         __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1821         perf_pmu_enable(pmu);
1822 }
1823
1824 /*
1825  * Commit group events scheduling transaction
1826  * Perform the group schedulability test as a whole
1827  * Return 0 if success
1828  *
1829  * Does not cancel the transaction on failure; expects the caller to do this.
1830  */
1831 static int x86_pmu_commit_txn(struct pmu *pmu)
1832 {
1833         struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1834         int assign[X86_PMC_IDX_MAX];
1835         int n, ret;
1836
1837         WARN_ON_ONCE(!cpuc->txn_flags); /* no txn in flight */
1838
1839         if (cpuc->txn_flags & ~PERF_PMU_TXN_ADD) {
1840                 cpuc->txn_flags = 0;
1841                 return 0;
1842         }
1843
1844         n = cpuc->n_events;
1845
1846         if (!x86_pmu_initialized())
1847                 return -EAGAIN;
1848
1849         ret = x86_pmu.schedule_events(cpuc, n, assign);
1850         if (ret)
1851                 return ret;
1852
1853         /*
1854          * copy new assignment, now we know it is possible
1855          * will be used by hw_perf_enable()
1856          */
1857         memcpy(cpuc->assign, assign, n*sizeof(int));
1858
1859         cpuc->txn_flags = 0;
1860         perf_pmu_enable(pmu);
1861         return 0;
1862 }
1863 /*
1864  * a fake_cpuc is used to validate event groups. Due to
1865  * the extra reg logic, we need to also allocate a fake
1866  * per_core and per_cpu structure. Otherwise, group events
1867  * using extra reg may conflict without the kernel being
1868  * able to catch this when the last event gets added to
1869  * the group.
1870  */
1871 static void free_fake_cpuc(struct cpu_hw_events *cpuc)
1872 {
1873         kfree(cpuc->shared_regs);
1874         kfree(cpuc);
1875 }
1876
1877 static struct cpu_hw_events *allocate_fake_cpuc(void)
1878 {
1879         struct cpu_hw_events *cpuc;
1880         int cpu = raw_smp_processor_id();
1881
1882         cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
1883         if (!cpuc)
1884                 return ERR_PTR(-ENOMEM);
1885
1886         /* only needed, if we have extra_regs */
1887         if (x86_pmu.extra_regs) {
1888                 cpuc->shared_regs = allocate_shared_regs(cpu);
1889                 if (!cpuc->shared_regs)
1890                         goto error;
1891         }
1892         cpuc->is_fake = 1;
1893         return cpuc;
1894 error:
1895         free_fake_cpuc(cpuc);
1896         return ERR_PTR(-ENOMEM);
1897 }
1898
1899 /*
1900  * validate that we can schedule this event
1901  */
1902 static int validate_event(struct perf_event *event)
1903 {
1904         struct cpu_hw_events *fake_cpuc;
1905         struct event_constraint *c;
1906         int ret = 0;
1907
1908         fake_cpuc = allocate_fake_cpuc();
1909         if (IS_ERR(fake_cpuc))
1910                 return PTR_ERR(fake_cpuc);
1911
1912         c = x86_pmu.get_event_constraints(fake_cpuc, -1, event);
1913
1914         if (!c || !c->weight)
1915                 ret = -EINVAL;
1916
1917         if (x86_pmu.put_event_constraints)
1918                 x86_pmu.put_event_constraints(fake_cpuc, event);
1919
1920         free_fake_cpuc(fake_cpuc);
1921
1922         return ret;
1923 }
1924
1925 /*
1926  * validate a single event group
1927  *
1928  * validation include:
1929  *      - check events are compatible which each other
1930  *      - events do not compete for the same counter
1931  *      - number of events <= number of counters
1932  *
1933  * validation ensures the group can be loaded onto the
1934  * PMU if it was the only group available.
1935  */
1936 static int validate_group(struct perf_event *event)
1937 {
1938         struct perf_event *leader = event->group_leader;
1939         struct cpu_hw_events *fake_cpuc;
1940         int ret = -EINVAL, n;
1941
1942         fake_cpuc = allocate_fake_cpuc();
1943         if (IS_ERR(fake_cpuc))
1944                 return PTR_ERR(fake_cpuc);
1945         /*
1946          * the event is not yet connected with its
1947          * siblings therefore we must first collect
1948          * existing siblings, then add the new event
1949          * before we can simulate the scheduling
1950          */
1951         n = collect_events(fake_cpuc, leader, true);
1952         if (n < 0)
1953                 goto out;
1954
1955         fake_cpuc->n_events = n;
1956         n = collect_events(fake_cpuc, event, false);
1957         if (n < 0)
1958                 goto out;
1959
1960         fake_cpuc->n_events = n;
1961
1962         ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1963
1964 out:
1965         free_fake_cpuc(fake_cpuc);
1966         return ret;
1967 }
1968
1969 static int x86_pmu_event_init(struct perf_event *event)
1970 {
1971         struct pmu *tmp;
1972         int err;
1973
1974         switch (event->attr.type) {
1975         case PERF_TYPE_RAW:
1976         case PERF_TYPE_HARDWARE:
1977         case PERF_TYPE_HW_CACHE:
1978                 break;
1979
1980         default:
1981                 return -ENOENT;
1982         }
1983
1984         err = __x86_pmu_event_init(event);
1985         if (!err) {
1986                 /*
1987                  * we temporarily connect event to its pmu
1988                  * such that validate_group() can classify
1989                  * it as an x86 event using is_x86_event()
1990                  */
1991                 tmp = event->pmu;
1992                 event->pmu = &pmu;
1993
1994                 if (event->group_leader != event)
1995                         err = validate_group(event);
1996                 else
1997                         err = validate_event(event);
1998
1999                 event->pmu = tmp;
2000         }
2001         if (err) {
2002                 if (event->destroy)
2003                         event->destroy(event);
2004         }
2005
2006         if (ACCESS_ONCE(x86_pmu.attr_rdpmc))
2007                 event->hw.flags |= PERF_X86_EVENT_RDPMC_ALLOWED;
2008
2009         return err;
2010 }
2011
2012 static void refresh_pce(void *ignored)
2013 {
2014         if (current->active_mm)
2015                 load_mm_cr4(current->active_mm);
2016 }
2017
2018 static void x86_pmu_event_mapped(struct perf_event *event)
2019 {
2020         if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
2021                 return;
2022
2023         if (atomic_inc_return(&current->mm->context.perf_rdpmc_allowed) == 1)
2024                 on_each_cpu_mask(mm_cpumask(current->mm), refresh_pce, NULL, 1);
2025 }
2026
2027 static void x86_pmu_event_unmapped(struct perf_event *event)
2028 {
2029         if (!current->mm)
2030                 return;
2031
2032         if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
2033                 return;
2034
2035         if (atomic_dec_and_test(&current->mm->context.perf_rdpmc_allowed))
2036                 on_each_cpu_mask(mm_cpumask(current->mm), refresh_pce, NULL, 1);
2037 }
2038
2039 static int x86_pmu_event_idx(struct perf_event *event)
2040 {
2041         int idx = event->hw.idx;
2042
2043         if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
2044                 return 0;
2045
2046         if (x86_pmu.num_counters_fixed && idx >= INTEL_PMC_IDX_FIXED) {
2047                 idx -= INTEL_PMC_IDX_FIXED;
2048                 idx |= 1 << 30;
2049         }
2050
2051         return idx + 1;
2052 }
2053
2054 static ssize_t get_attr_rdpmc(struct device *cdev,
2055                               struct device_attribute *attr,
2056                               char *buf)
2057 {
2058         return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
2059 }
2060
2061 static ssize_t set_attr_rdpmc(struct device *cdev,
2062                               struct device_attribute *attr,
2063                               const char *buf, size_t count)
2064 {
2065         unsigned long val;
2066         ssize_t ret;
2067
2068         ret = kstrtoul(buf, 0, &val);
2069         if (ret)
2070                 return ret;
2071
2072         if (val > 2)
2073                 return -EINVAL;
2074
2075         if (x86_pmu.attr_rdpmc_broken)
2076                 return -ENOTSUPP;
2077
2078         if ((val == 2) != (x86_pmu.attr_rdpmc == 2)) {
2079                 /*
2080                  * Changing into or out of always available, aka
2081                  * perf-event-bypassing mode.  This path is extremely slow,
2082                  * but only root can trigger it, so it's okay.
2083                  */
2084                 if (val == 2)
2085                         static_key_slow_inc(&rdpmc_always_available);
2086                 else
2087                         static_key_slow_dec(&rdpmc_always_available);
2088                 on_each_cpu(refresh_pce, NULL, 1);
2089         }
2090
2091         x86_pmu.attr_rdpmc = val;
2092
2093         return count;
2094 }
2095
2096 static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
2097
2098 static struct attribute *x86_pmu_attrs[] = {
2099         &dev_attr_rdpmc.attr,
2100         NULL,
2101 };
2102
2103 static struct attribute_group x86_pmu_attr_group = {
2104         .attrs = x86_pmu_attrs,
2105 };
2106
2107 static const struct attribute_group *x86_pmu_attr_groups[] = {
2108         &x86_pmu_attr_group,
2109         &x86_pmu_format_group,
2110         &x86_pmu_events_group,
2111         NULL,
2112 };
2113
2114 static void x86_pmu_sched_task(struct perf_event_context *ctx, bool sched_in)
2115 {
2116         if (x86_pmu.sched_task)
2117                 x86_pmu.sched_task(ctx, sched_in);
2118 }
2119
2120 void perf_check_microcode(void)
2121 {
2122         if (x86_pmu.check_microcode)
2123                 x86_pmu.check_microcode();
2124 }
2125 EXPORT_SYMBOL_GPL(perf_check_microcode);
2126
2127 static struct pmu pmu = {
2128         .pmu_enable             = x86_pmu_enable,
2129         .pmu_disable            = x86_pmu_disable,
2130
2131         .attr_groups            = x86_pmu_attr_groups,
2132
2133         .event_init             = x86_pmu_event_init,
2134
2135         .event_mapped           = x86_pmu_event_mapped,
2136         .event_unmapped         = x86_pmu_event_unmapped,
2137
2138         .add                    = x86_pmu_add,
2139         .del                    = x86_pmu_del,
2140         .start                  = x86_pmu_start,
2141         .stop                   = x86_pmu_stop,
2142         .read                   = x86_pmu_read,
2143
2144         .start_txn              = x86_pmu_start_txn,
2145         .cancel_txn             = x86_pmu_cancel_txn,
2146         .commit_txn             = x86_pmu_commit_txn,
2147
2148         .event_idx              = x86_pmu_event_idx,
2149         .sched_task             = x86_pmu_sched_task,
2150         .task_ctx_size          = sizeof(struct x86_perf_task_context),
2151 };
2152
2153 void arch_perf_update_userpage(struct perf_event *event,
2154                                struct perf_event_mmap_page *userpg, u64 now)
2155 {
2156         struct cyc2ns_data *data;
2157
2158         userpg->cap_user_time = 0;
2159         userpg->cap_user_time_zero = 0;
2160         userpg->cap_user_rdpmc =
2161                 !!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED);
2162         userpg->pmc_width = x86_pmu.cntval_bits;
2163
2164         if (!sched_clock_stable())
2165                 return;
2166
2167         data = cyc2ns_read_begin();
2168
2169         /*
2170          * Internal timekeeping for enabled/running/stopped times
2171          * is always in the local_clock domain.
2172          */
2173         userpg->cap_user_time = 1;
2174         userpg->time_mult = data->cyc2ns_mul;
2175         userpg->time_shift = data->cyc2ns_shift;
2176         userpg->time_offset = data->cyc2ns_offset - now;
2177
2178         /*
2179          * cap_user_time_zero doesn't make sense when we're using a different
2180          * time base for the records.
2181          */
2182         if (event->clock == &local_clock) {
2183                 userpg->cap_user_time_zero = 1;
2184                 userpg->time_zero = data->cyc2ns_offset;
2185         }
2186
2187         cyc2ns_read_end(data);
2188 }
2189
2190 /*
2191  * callchain support
2192  */
2193
2194 static int backtrace_stack(void *data, char *name)
2195 {
2196         return 0;
2197 }
2198
2199 static void backtrace_address(void *data, unsigned long addr, int reliable)
2200 {
2201         struct perf_callchain_entry *entry = data;
2202
2203         perf_callchain_store(entry, addr);
2204 }
2205
2206 static const struct stacktrace_ops backtrace_ops = {
2207         .stack                  = backtrace_stack,
2208         .address                = backtrace_address,
2209         .walk_stack             = print_context_stack_bp,
2210 };
2211
2212 void
2213 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
2214 {
2215         if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2216                 /* TODO: We don't support guest os callchain now */
2217                 return;
2218         }
2219
2220         perf_callchain_store(entry, regs->ip);
2221
2222         dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
2223 }
2224
2225 static inline int
2226 valid_user_frame(const void __user *fp, unsigned long size)
2227 {
2228         return (__range_not_ok(fp, size, TASK_SIZE) == 0);
2229 }
2230
2231 static unsigned long get_segment_base(unsigned int segment)
2232 {
2233         struct desc_struct *desc;
2234         int idx = segment >> 3;
2235
2236         if ((segment & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2237 #ifdef CONFIG_MODIFY_LDT_SYSCALL
2238                 struct ldt_struct *ldt;
2239
2240                 if (idx > LDT_ENTRIES)
2241                         return 0;
2242
2243                 /* IRQs are off, so this synchronizes with smp_store_release */
2244                 ldt = lockless_dereference(current->active_mm->context.ldt);
2245                 if (!ldt || idx > ldt->size)
2246                         return 0;
2247
2248                 desc = &ldt->entries[idx];
2249 #else
2250                 return 0;
2251 #endif
2252         } else {
2253                 if (idx > GDT_ENTRIES)
2254                         return 0;
2255
2256                 desc = raw_cpu_ptr(gdt_page.gdt) + idx;
2257         }
2258
2259         return get_desc_base(desc);
2260 }
2261
2262 #ifdef CONFIG_IA32_EMULATION
2263
2264 #include <asm/compat.h>
2265
2266 static inline int
2267 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
2268 {
2269         /* 32-bit process in 64-bit kernel. */
2270         unsigned long ss_base, cs_base;
2271         struct stack_frame_ia32 frame;
2272         const void __user *fp;
2273
2274         if (!test_thread_flag(TIF_IA32))
2275                 return 0;
2276
2277         cs_base = get_segment_base(regs->cs);
2278         ss_base = get_segment_base(regs->ss);
2279
2280         fp = compat_ptr(ss_base + regs->bp);
2281         while (entry->nr < PERF_MAX_STACK_DEPTH) {
2282                 unsigned long bytes;
2283                 frame.next_frame     = 0;
2284                 frame.return_address = 0;
2285
2286                 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
2287                 if (bytes != 0)
2288                         break;
2289
2290                 if (!valid_user_frame(fp, sizeof(frame)))
2291                         break;
2292
2293                 perf_callchain_store(entry, cs_base + frame.return_address);
2294                 fp = compat_ptr(ss_base + frame.next_frame);
2295         }
2296         return 1;
2297 }
2298 #else
2299 static inline int
2300 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
2301 {
2302     return 0;
2303 }
2304 #endif
2305
2306 void
2307 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
2308 {
2309         struct stack_frame frame;
2310         const void __user *fp;
2311
2312         if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2313                 /* TODO: We don't support guest os callchain now */
2314                 return;
2315         }
2316
2317         /*
2318          * We don't know what to do with VM86 stacks.. ignore them for now.
2319          */
2320         if (regs->flags & (X86_VM_MASK | PERF_EFLAGS_VM))
2321                 return;
2322
2323         fp = (void __user *)regs->bp;
2324
2325         perf_callchain_store(entry, regs->ip);
2326
2327         if (!current->mm)
2328                 return;
2329
2330         if (perf_callchain_user32(regs, entry))
2331                 return;
2332
2333         while (entry->nr < PERF_MAX_STACK_DEPTH) {
2334                 unsigned long bytes;
2335                 frame.next_frame             = NULL;
2336                 frame.return_address = 0;
2337
2338                 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
2339                 if (bytes != 0)
2340                         break;
2341
2342                 if (!valid_user_frame(fp, sizeof(frame)))
2343                         break;
2344
2345                 perf_callchain_store(entry, frame.return_address);
2346                 fp = frame.next_frame;
2347         }
2348 }
2349
2350 /*
2351  * Deal with code segment offsets for the various execution modes:
2352  *
2353  *   VM86 - the good olde 16 bit days, where the linear address is
2354  *          20 bits and we use regs->ip + 0x10 * regs->cs.
2355  *
2356  *   IA32 - Where we need to look at GDT/LDT segment descriptor tables
2357  *          to figure out what the 32bit base address is.
2358  *
2359  *    X32 - has TIF_X32 set, but is running in x86_64
2360  *
2361  * X86_64 - CS,DS,SS,ES are all zero based.
2362  */
2363 static unsigned long code_segment_base(struct pt_regs *regs)
2364 {
2365         /*
2366          * For IA32 we look at the GDT/LDT segment base to convert the
2367          * effective IP to a linear address.
2368          */
2369
2370 #ifdef CONFIG_X86_32
2371         /*
2372          * If we are in VM86 mode, add the segment offset to convert to a
2373          * linear address.
2374          */
2375         if (regs->flags & X86_VM_MASK)
2376                 return 0x10 * regs->cs;
2377
2378         if (user_mode(regs) && regs->cs != __USER_CS)
2379                 return get_segment_base(regs->cs);
2380 #else
2381         if (user_mode(regs) && !user_64bit_mode(regs) &&
2382             regs->cs != __USER32_CS)
2383                 return get_segment_base(regs->cs);
2384 #endif
2385         return 0;
2386 }
2387
2388 unsigned long perf_instruction_pointer(struct pt_regs *regs)
2389 {
2390         if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
2391                 return perf_guest_cbs->get_guest_ip();
2392
2393         return regs->ip + code_segment_base(regs);
2394 }
2395
2396 unsigned long perf_misc_flags(struct pt_regs *regs)
2397 {
2398         int misc = 0;
2399
2400         if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2401                 if (perf_guest_cbs->is_user_mode())
2402                         misc |= PERF_RECORD_MISC_GUEST_USER;
2403                 else
2404                         misc |= PERF_RECORD_MISC_GUEST_KERNEL;
2405         } else {
2406                 if (user_mode(regs))
2407                         misc |= PERF_RECORD_MISC_USER;
2408                 else
2409                         misc |= PERF_RECORD_MISC_KERNEL;
2410         }
2411
2412         if (regs->flags & PERF_EFLAGS_EXACT)
2413                 misc |= PERF_RECORD_MISC_EXACT_IP;
2414
2415         return misc;
2416 }
2417
2418 void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
2419 {
2420         cap->version            = x86_pmu.version;
2421         cap->num_counters_gp    = x86_pmu.num_counters;
2422         cap->num_counters_fixed = x86_pmu.num_counters_fixed;
2423         cap->bit_width_gp       = x86_pmu.cntval_bits;
2424         cap->bit_width_fixed    = x86_pmu.cntval_bits;
2425         cap->events_mask        = (unsigned int)x86_pmu.events_maskl;
2426         cap->events_mask_len    = x86_pmu.events_mask_len;
2427 }
2428 EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);