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