]> git.karo-electronics.de Git - mv-sheeva.git/blob - arch/x86/kernel/cpu/perf_counter.c
perf_counter: x86: Fix call-chain support to use NMI-safe methods
[mv-sheeva.git] / arch / x86 / kernel / cpu / perf_counter.c
1 /*
2  * Performance counter 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  *
10  *  For licencing details see kernel-base/COPYING
11  */
12
13 #include <linux/perf_counter.h>
14 #include <linux/capability.h>
15 #include <linux/notifier.h>
16 #include <linux/hardirq.h>
17 #include <linux/kprobes.h>
18 #include <linux/module.h>
19 #include <linux/kdebug.h>
20 #include <linux/sched.h>
21 #include <linux/uaccess.h>
22 #include <linux/highmem.h>
23
24 #include <asm/apic.h>
25 #include <asm/stacktrace.h>
26 #include <asm/nmi.h>
27
28 static u64 perf_counter_mask __read_mostly;
29
30 struct cpu_hw_counters {
31         struct perf_counter     *counters[X86_PMC_IDX_MAX];
32         unsigned long           used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
33         unsigned long           active_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
34         unsigned long           interrupts;
35         int                     enabled;
36 };
37
38 /*
39  * struct x86_pmu - generic x86 pmu
40  */
41 struct x86_pmu {
42         const char      *name;
43         int             version;
44         int             (*handle_irq)(struct pt_regs *);
45         void            (*disable_all)(void);
46         void            (*enable_all)(void);
47         void            (*enable)(struct hw_perf_counter *, int);
48         void            (*disable)(struct hw_perf_counter *, int);
49         unsigned        eventsel;
50         unsigned        perfctr;
51         u64             (*event_map)(int);
52         u64             (*raw_event)(u64);
53         int             max_events;
54         int             num_counters;
55         int             num_counters_fixed;
56         int             counter_bits;
57         u64             counter_mask;
58         u64             max_period;
59         u64             intel_ctrl;
60 };
61
62 static struct x86_pmu x86_pmu __read_mostly;
63
64 static DEFINE_PER_CPU(struct cpu_hw_counters, cpu_hw_counters) = {
65         .enabled = 1,
66 };
67
68 /*
69  * Intel PerfMon v3. Used on Core2 and later.
70  */
71 static const u64 intel_perfmon_event_map[] =
72 {
73   [PERF_COUNT_HW_CPU_CYCLES]            = 0x003c,
74   [PERF_COUNT_HW_INSTRUCTIONS]          = 0x00c0,
75   [PERF_COUNT_HW_CACHE_REFERENCES]      = 0x4f2e,
76   [PERF_COUNT_HW_CACHE_MISSES]          = 0x412e,
77   [PERF_COUNT_HW_BRANCH_INSTRUCTIONS]   = 0x00c4,
78   [PERF_COUNT_HW_BRANCH_MISSES]         = 0x00c5,
79   [PERF_COUNT_HW_BUS_CYCLES]            = 0x013c,
80 };
81
82 static u64 intel_pmu_event_map(int event)
83 {
84         return intel_perfmon_event_map[event];
85 }
86
87 /*
88  * Generalized hw caching related event table, filled
89  * in on a per model basis. A value of 0 means
90  * 'not supported', -1 means 'event makes no sense on
91  * this CPU', any other value means the raw event
92  * ID.
93  */
94
95 #define C(x) PERF_COUNT_HW_CACHE_##x
96
97 static u64 __read_mostly hw_cache_event_ids
98                                 [PERF_COUNT_HW_CACHE_MAX]
99                                 [PERF_COUNT_HW_CACHE_OP_MAX]
100                                 [PERF_COUNT_HW_CACHE_RESULT_MAX];
101
102 static const u64 nehalem_hw_cache_event_ids
103                                 [PERF_COUNT_HW_CACHE_MAX]
104                                 [PERF_COUNT_HW_CACHE_OP_MAX]
105                                 [PERF_COUNT_HW_CACHE_RESULT_MAX] =
106 {
107  [ C(L1D) ] = {
108         [ C(OP_READ) ] = {
109                 [ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI            */
110                 [ C(RESULT_MISS)   ] = 0x0140, /* L1D_CACHE_LD.I_STATE         */
111         },
112         [ C(OP_WRITE) ] = {
113                 [ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI            */
114                 [ C(RESULT_MISS)   ] = 0x0141, /* L1D_CACHE_ST.I_STATE         */
115         },
116         [ C(OP_PREFETCH) ] = {
117                 [ C(RESULT_ACCESS) ] = 0x014e, /* L1D_PREFETCH.REQUESTS        */
118                 [ C(RESULT_MISS)   ] = 0x024e, /* L1D_PREFETCH.MISS            */
119         },
120  },
121  [ C(L1I ) ] = {
122         [ C(OP_READ) ] = {
123                 [ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS                    */
124                 [ C(RESULT_MISS)   ] = 0x0280, /* L1I.MISSES                   */
125         },
126         [ C(OP_WRITE) ] = {
127                 [ C(RESULT_ACCESS) ] = -1,
128                 [ C(RESULT_MISS)   ] = -1,
129         },
130         [ C(OP_PREFETCH) ] = {
131                 [ C(RESULT_ACCESS) ] = 0x0,
132                 [ C(RESULT_MISS)   ] = 0x0,
133         },
134  },
135  [ C(LL  ) ] = {
136         [ C(OP_READ) ] = {
137                 [ C(RESULT_ACCESS) ] = 0x0324, /* L2_RQSTS.LOADS               */
138                 [ C(RESULT_MISS)   ] = 0x0224, /* L2_RQSTS.LD_MISS             */
139         },
140         [ C(OP_WRITE) ] = {
141                 [ C(RESULT_ACCESS) ] = 0x0c24, /* L2_RQSTS.RFOS                */
142                 [ C(RESULT_MISS)   ] = 0x0824, /* L2_RQSTS.RFO_MISS            */
143         },
144         [ C(OP_PREFETCH) ] = {
145                 [ C(RESULT_ACCESS) ] = 0x4f2e, /* LLC Reference                */
146                 [ C(RESULT_MISS)   ] = 0x412e, /* LLC Misses                   */
147         },
148  },
149  [ C(DTLB) ] = {
150         [ C(OP_READ) ] = {
151                 [ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI   (alias)  */
152                 [ C(RESULT_MISS)   ] = 0x0108, /* DTLB_LOAD_MISSES.ANY         */
153         },
154         [ C(OP_WRITE) ] = {
155                 [ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI   (alias)  */
156                 [ C(RESULT_MISS)   ] = 0x010c, /* MEM_STORE_RETIRED.DTLB_MISS  */
157         },
158         [ C(OP_PREFETCH) ] = {
159                 [ C(RESULT_ACCESS) ] = 0x0,
160                 [ C(RESULT_MISS)   ] = 0x0,
161         },
162  },
163  [ C(ITLB) ] = {
164         [ C(OP_READ) ] = {
165                 [ C(RESULT_ACCESS) ] = 0x01c0, /* INST_RETIRED.ANY_P           */
166                 [ C(RESULT_MISS)   ] = 0x20c8, /* ITLB_MISS_RETIRED            */
167         },
168         [ C(OP_WRITE) ] = {
169                 [ C(RESULT_ACCESS) ] = -1,
170                 [ C(RESULT_MISS)   ] = -1,
171         },
172         [ C(OP_PREFETCH) ] = {
173                 [ C(RESULT_ACCESS) ] = -1,
174                 [ C(RESULT_MISS)   ] = -1,
175         },
176  },
177  [ C(BPU ) ] = {
178         [ C(OP_READ) ] = {
179                 [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ALL_BRANCHES */
180                 [ C(RESULT_MISS)   ] = 0x03e8, /* BPU_CLEARS.ANY               */
181         },
182         [ C(OP_WRITE) ] = {
183                 [ C(RESULT_ACCESS) ] = -1,
184                 [ C(RESULT_MISS)   ] = -1,
185         },
186         [ C(OP_PREFETCH) ] = {
187                 [ C(RESULT_ACCESS) ] = -1,
188                 [ C(RESULT_MISS)   ] = -1,
189         },
190  },
191 };
192
193 static const u64 core2_hw_cache_event_ids
194                                 [PERF_COUNT_HW_CACHE_MAX]
195                                 [PERF_COUNT_HW_CACHE_OP_MAX]
196                                 [PERF_COUNT_HW_CACHE_RESULT_MAX] =
197 {
198  [ C(L1D) ] = {
199         [ C(OP_READ) ] = {
200                 [ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI          */
201                 [ C(RESULT_MISS)   ] = 0x0140, /* L1D_CACHE_LD.I_STATE       */
202         },
203         [ C(OP_WRITE) ] = {
204                 [ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI          */
205                 [ C(RESULT_MISS)   ] = 0x0141, /* L1D_CACHE_ST.I_STATE       */
206         },
207         [ C(OP_PREFETCH) ] = {
208                 [ C(RESULT_ACCESS) ] = 0x104e, /* L1D_PREFETCH.REQUESTS      */
209                 [ C(RESULT_MISS)   ] = 0,
210         },
211  },
212  [ C(L1I ) ] = {
213         [ C(OP_READ) ] = {
214                 [ C(RESULT_ACCESS) ] = 0x0080, /* L1I.READS                  */
215                 [ C(RESULT_MISS)   ] = 0x0081, /* L1I.MISSES                 */
216         },
217         [ C(OP_WRITE) ] = {
218                 [ C(RESULT_ACCESS) ] = -1,
219                 [ C(RESULT_MISS)   ] = -1,
220         },
221         [ C(OP_PREFETCH) ] = {
222                 [ C(RESULT_ACCESS) ] = 0,
223                 [ C(RESULT_MISS)   ] = 0,
224         },
225  },
226  [ C(LL  ) ] = {
227         [ C(OP_READ) ] = {
228                 [ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI                 */
229                 [ C(RESULT_MISS)   ] = 0x4129, /* L2_LD.ISTATE               */
230         },
231         [ C(OP_WRITE) ] = {
232                 [ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI                 */
233                 [ C(RESULT_MISS)   ] = 0x412A, /* L2_ST.ISTATE               */
234         },
235         [ C(OP_PREFETCH) ] = {
236                 [ C(RESULT_ACCESS) ] = 0,
237                 [ C(RESULT_MISS)   ] = 0,
238         },
239  },
240  [ C(DTLB) ] = {
241         [ C(OP_READ) ] = {
242                 [ C(RESULT_ACCESS) ] = 0x0f40, /* L1D_CACHE_LD.MESI  (alias) */
243                 [ C(RESULT_MISS)   ] = 0x0208, /* DTLB_MISSES.MISS_LD        */
244         },
245         [ C(OP_WRITE) ] = {
246                 [ C(RESULT_ACCESS) ] = 0x0f41, /* L1D_CACHE_ST.MESI  (alias) */
247                 [ C(RESULT_MISS)   ] = 0x0808, /* DTLB_MISSES.MISS_ST        */
248         },
249         [ C(OP_PREFETCH) ] = {
250                 [ C(RESULT_ACCESS) ] = 0,
251                 [ C(RESULT_MISS)   ] = 0,
252         },
253  },
254  [ C(ITLB) ] = {
255         [ C(OP_READ) ] = {
256                 [ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P         */
257                 [ C(RESULT_MISS)   ] = 0x1282, /* ITLBMISSES                 */
258         },
259         [ C(OP_WRITE) ] = {
260                 [ C(RESULT_ACCESS) ] = -1,
261                 [ C(RESULT_MISS)   ] = -1,
262         },
263         [ C(OP_PREFETCH) ] = {
264                 [ C(RESULT_ACCESS) ] = -1,
265                 [ C(RESULT_MISS)   ] = -1,
266         },
267  },
268  [ C(BPU ) ] = {
269         [ C(OP_READ) ] = {
270                 [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY        */
271                 [ C(RESULT_MISS)   ] = 0x00c5, /* BP_INST_RETIRED.MISPRED    */
272         },
273         [ C(OP_WRITE) ] = {
274                 [ C(RESULT_ACCESS) ] = -1,
275                 [ C(RESULT_MISS)   ] = -1,
276         },
277         [ C(OP_PREFETCH) ] = {
278                 [ C(RESULT_ACCESS) ] = -1,
279                 [ C(RESULT_MISS)   ] = -1,
280         },
281  },
282 };
283
284 static const u64 atom_hw_cache_event_ids
285                                 [PERF_COUNT_HW_CACHE_MAX]
286                                 [PERF_COUNT_HW_CACHE_OP_MAX]
287                                 [PERF_COUNT_HW_CACHE_RESULT_MAX] =
288 {
289  [ C(L1D) ] = {
290         [ C(OP_READ) ] = {
291                 [ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE.LD               */
292                 [ C(RESULT_MISS)   ] = 0,
293         },
294         [ C(OP_WRITE) ] = {
295                 [ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE.ST               */
296                 [ C(RESULT_MISS)   ] = 0,
297         },
298         [ C(OP_PREFETCH) ] = {
299                 [ C(RESULT_ACCESS) ] = 0x0,
300                 [ C(RESULT_MISS)   ] = 0,
301         },
302  },
303  [ C(L1I ) ] = {
304         [ C(OP_READ) ] = {
305                 [ C(RESULT_ACCESS) ] = 0x0380, /* L1I.READS                  */
306                 [ C(RESULT_MISS)   ] = 0x0280, /* L1I.MISSES                 */
307         },
308         [ C(OP_WRITE) ] = {
309                 [ C(RESULT_ACCESS) ] = -1,
310                 [ C(RESULT_MISS)   ] = -1,
311         },
312         [ C(OP_PREFETCH) ] = {
313                 [ C(RESULT_ACCESS) ] = 0,
314                 [ C(RESULT_MISS)   ] = 0,
315         },
316  },
317  [ C(LL  ) ] = {
318         [ C(OP_READ) ] = {
319                 [ C(RESULT_ACCESS) ] = 0x4f29, /* L2_LD.MESI                 */
320                 [ C(RESULT_MISS)   ] = 0x4129, /* L2_LD.ISTATE               */
321         },
322         [ C(OP_WRITE) ] = {
323                 [ C(RESULT_ACCESS) ] = 0x4f2A, /* L2_ST.MESI                 */
324                 [ C(RESULT_MISS)   ] = 0x412A, /* L2_ST.ISTATE               */
325         },
326         [ C(OP_PREFETCH) ] = {
327                 [ C(RESULT_ACCESS) ] = 0,
328                 [ C(RESULT_MISS)   ] = 0,
329         },
330  },
331  [ C(DTLB) ] = {
332         [ C(OP_READ) ] = {
333                 [ C(RESULT_ACCESS) ] = 0x2140, /* L1D_CACHE_LD.MESI  (alias) */
334                 [ C(RESULT_MISS)   ] = 0x0508, /* DTLB_MISSES.MISS_LD        */
335         },
336         [ C(OP_WRITE) ] = {
337                 [ C(RESULT_ACCESS) ] = 0x2240, /* L1D_CACHE_ST.MESI  (alias) */
338                 [ C(RESULT_MISS)   ] = 0x0608, /* DTLB_MISSES.MISS_ST        */
339         },
340         [ C(OP_PREFETCH) ] = {
341                 [ C(RESULT_ACCESS) ] = 0,
342                 [ C(RESULT_MISS)   ] = 0,
343         },
344  },
345  [ C(ITLB) ] = {
346         [ C(OP_READ) ] = {
347                 [ C(RESULT_ACCESS) ] = 0x00c0, /* INST_RETIRED.ANY_P         */
348                 [ C(RESULT_MISS)   ] = 0x0282, /* ITLB.MISSES                */
349         },
350         [ C(OP_WRITE) ] = {
351                 [ C(RESULT_ACCESS) ] = -1,
352                 [ C(RESULT_MISS)   ] = -1,
353         },
354         [ C(OP_PREFETCH) ] = {
355                 [ C(RESULT_ACCESS) ] = -1,
356                 [ C(RESULT_MISS)   ] = -1,
357         },
358  },
359  [ C(BPU ) ] = {
360         [ C(OP_READ) ] = {
361                 [ C(RESULT_ACCESS) ] = 0x00c4, /* BR_INST_RETIRED.ANY        */
362                 [ C(RESULT_MISS)   ] = 0x00c5, /* BP_INST_RETIRED.MISPRED    */
363         },
364         [ C(OP_WRITE) ] = {
365                 [ C(RESULT_ACCESS) ] = -1,
366                 [ C(RESULT_MISS)   ] = -1,
367         },
368         [ C(OP_PREFETCH) ] = {
369                 [ C(RESULT_ACCESS) ] = -1,
370                 [ C(RESULT_MISS)   ] = -1,
371         },
372  },
373 };
374
375 static u64 intel_pmu_raw_event(u64 event)
376 {
377 #define CORE_EVNTSEL_EVENT_MASK         0x000000FFULL
378 #define CORE_EVNTSEL_UNIT_MASK          0x0000FF00ULL
379 #define CORE_EVNTSEL_EDGE_MASK          0x00040000ULL
380 #define CORE_EVNTSEL_INV_MASK           0x00800000ULL
381 #define CORE_EVNTSEL_COUNTER_MASK       0xFF000000ULL
382
383 #define CORE_EVNTSEL_MASK               \
384         (CORE_EVNTSEL_EVENT_MASK |      \
385          CORE_EVNTSEL_UNIT_MASK  |      \
386          CORE_EVNTSEL_EDGE_MASK  |      \
387          CORE_EVNTSEL_INV_MASK  |       \
388          CORE_EVNTSEL_COUNTER_MASK)
389
390         return event & CORE_EVNTSEL_MASK;
391 }
392
393 static const u64 amd_hw_cache_event_ids
394                                 [PERF_COUNT_HW_CACHE_MAX]
395                                 [PERF_COUNT_HW_CACHE_OP_MAX]
396                                 [PERF_COUNT_HW_CACHE_RESULT_MAX] =
397 {
398  [ C(L1D) ] = {
399         [ C(OP_READ) ] = {
400                 [ C(RESULT_ACCESS) ] = 0x0040, /* Data Cache Accesses        */
401                 [ C(RESULT_MISS)   ] = 0x0041, /* Data Cache Misses          */
402         },
403         [ C(OP_WRITE) ] = {
404                 [ C(RESULT_ACCESS) ] = 0x0042, /* Data Cache Refills from L2 */
405                 [ C(RESULT_MISS)   ] = 0,
406         },
407         [ C(OP_PREFETCH) ] = {
408                 [ C(RESULT_ACCESS) ] = 0x0267, /* Data Prefetcher :attempts  */
409                 [ C(RESULT_MISS)   ] = 0x0167, /* Data Prefetcher :cancelled */
410         },
411  },
412  [ C(L1I ) ] = {
413         [ C(OP_READ) ] = {
414                 [ C(RESULT_ACCESS) ] = 0x0080, /* Instruction cache fetches  */
415                 [ C(RESULT_MISS)   ] = 0x0081, /* Instruction cache misses   */
416         },
417         [ C(OP_WRITE) ] = {
418                 [ C(RESULT_ACCESS) ] = -1,
419                 [ C(RESULT_MISS)   ] = -1,
420         },
421         [ C(OP_PREFETCH) ] = {
422                 [ C(RESULT_ACCESS) ] = 0x014B, /* Prefetch Instructions :Load */
423                 [ C(RESULT_MISS)   ] = 0,
424         },
425  },
426  [ C(LL  ) ] = {
427         [ C(OP_READ) ] = {
428                 [ C(RESULT_ACCESS) ] = 0x037D, /* Requests to L2 Cache :IC+DC */
429                 [ C(RESULT_MISS)   ] = 0x037E, /* L2 Cache Misses : IC+DC     */
430         },
431         [ C(OP_WRITE) ] = {
432                 [ C(RESULT_ACCESS) ] = 0x017F, /* L2 Fill/Writeback           */
433                 [ C(RESULT_MISS)   ] = 0,
434         },
435         [ C(OP_PREFETCH) ] = {
436                 [ C(RESULT_ACCESS) ] = 0,
437                 [ C(RESULT_MISS)   ] = 0,
438         },
439  },
440  [ C(DTLB) ] = {
441         [ C(OP_READ) ] = {
442                 [ C(RESULT_ACCESS) ] = 0x0040, /* Data Cache Accesses        */
443                 [ C(RESULT_MISS)   ] = 0x0046, /* L1 DTLB and L2 DLTB Miss   */
444         },
445         [ C(OP_WRITE) ] = {
446                 [ C(RESULT_ACCESS) ] = 0,
447                 [ C(RESULT_MISS)   ] = 0,
448         },
449         [ C(OP_PREFETCH) ] = {
450                 [ C(RESULT_ACCESS) ] = 0,
451                 [ C(RESULT_MISS)   ] = 0,
452         },
453  },
454  [ C(ITLB) ] = {
455         [ C(OP_READ) ] = {
456                 [ C(RESULT_ACCESS) ] = 0x0080, /* Instruction fecthes        */
457                 [ C(RESULT_MISS)   ] = 0x0085, /* Instr. fetch ITLB misses   */
458         },
459         [ C(OP_WRITE) ] = {
460                 [ C(RESULT_ACCESS) ] = -1,
461                 [ C(RESULT_MISS)   ] = -1,
462         },
463         [ C(OP_PREFETCH) ] = {
464                 [ C(RESULT_ACCESS) ] = -1,
465                 [ C(RESULT_MISS)   ] = -1,
466         },
467  },
468  [ C(BPU ) ] = {
469         [ C(OP_READ) ] = {
470                 [ C(RESULT_ACCESS) ] = 0x00c2, /* Retired Branch Instr.      */
471                 [ C(RESULT_MISS)   ] = 0x00c3, /* Retired Mispredicted BI    */
472         },
473         [ C(OP_WRITE) ] = {
474                 [ C(RESULT_ACCESS) ] = -1,
475                 [ C(RESULT_MISS)   ] = -1,
476         },
477         [ C(OP_PREFETCH) ] = {
478                 [ C(RESULT_ACCESS) ] = -1,
479                 [ C(RESULT_MISS)   ] = -1,
480         },
481  },
482 };
483
484 /*
485  * AMD Performance Monitor K7 and later.
486  */
487 static const u64 amd_perfmon_event_map[] =
488 {
489   [PERF_COUNT_HW_CPU_CYCLES]            = 0x0076,
490   [PERF_COUNT_HW_INSTRUCTIONS]          = 0x00c0,
491   [PERF_COUNT_HW_CACHE_REFERENCES]      = 0x0080,
492   [PERF_COUNT_HW_CACHE_MISSES]          = 0x0081,
493   [PERF_COUNT_HW_BRANCH_INSTRUCTIONS]   = 0x00c4,
494   [PERF_COUNT_HW_BRANCH_MISSES]         = 0x00c5,
495 };
496
497 static u64 amd_pmu_event_map(int event)
498 {
499         return amd_perfmon_event_map[event];
500 }
501
502 static u64 amd_pmu_raw_event(u64 event)
503 {
504 #define K7_EVNTSEL_EVENT_MASK   0x7000000FFULL
505 #define K7_EVNTSEL_UNIT_MASK    0x00000FF00ULL
506 #define K7_EVNTSEL_EDGE_MASK    0x000040000ULL
507 #define K7_EVNTSEL_INV_MASK     0x000800000ULL
508 #define K7_EVNTSEL_COUNTER_MASK 0x0FF000000ULL
509
510 #define K7_EVNTSEL_MASK                 \
511         (K7_EVNTSEL_EVENT_MASK |        \
512          K7_EVNTSEL_UNIT_MASK  |        \
513          K7_EVNTSEL_EDGE_MASK  |        \
514          K7_EVNTSEL_INV_MASK   |        \
515          K7_EVNTSEL_COUNTER_MASK)
516
517         return event & K7_EVNTSEL_MASK;
518 }
519
520 /*
521  * Propagate counter elapsed time into the generic counter.
522  * Can only be executed on the CPU where the counter is active.
523  * Returns the delta events processed.
524  */
525 static u64
526 x86_perf_counter_update(struct perf_counter *counter,
527                         struct hw_perf_counter *hwc, int idx)
528 {
529         int shift = 64 - x86_pmu.counter_bits;
530         u64 prev_raw_count, new_raw_count;
531         s64 delta;
532
533         /*
534          * Careful: an NMI might modify the previous counter value.
535          *
536          * Our tactic to handle this is to first atomically read and
537          * exchange a new raw count - then add that new-prev delta
538          * count to the generic counter atomically:
539          */
540 again:
541         prev_raw_count = atomic64_read(&hwc->prev_count);
542         rdmsrl(hwc->counter_base + idx, new_raw_count);
543
544         if (atomic64_cmpxchg(&hwc->prev_count, prev_raw_count,
545                                         new_raw_count) != prev_raw_count)
546                 goto again;
547
548         /*
549          * Now we have the new raw value and have updated the prev
550          * timestamp already. We can now calculate the elapsed delta
551          * (counter-)time and add that to the generic counter.
552          *
553          * Careful, not all hw sign-extends above the physical width
554          * of the count.
555          */
556         delta = (new_raw_count << shift) - (prev_raw_count << shift);
557         delta >>= shift;
558
559         atomic64_add(delta, &counter->count);
560         atomic64_sub(delta, &hwc->period_left);
561
562         return new_raw_count;
563 }
564
565 static atomic_t active_counters;
566 static DEFINE_MUTEX(pmc_reserve_mutex);
567
568 static bool reserve_pmc_hardware(void)
569 {
570         int i;
571
572         if (nmi_watchdog == NMI_LOCAL_APIC)
573                 disable_lapic_nmi_watchdog();
574
575         for (i = 0; i < x86_pmu.num_counters; i++) {
576                 if (!reserve_perfctr_nmi(x86_pmu.perfctr + i))
577                         goto perfctr_fail;
578         }
579
580         for (i = 0; i < x86_pmu.num_counters; i++) {
581                 if (!reserve_evntsel_nmi(x86_pmu.eventsel + i))
582                         goto eventsel_fail;
583         }
584
585         return true;
586
587 eventsel_fail:
588         for (i--; i >= 0; i--)
589                 release_evntsel_nmi(x86_pmu.eventsel + i);
590
591         i = x86_pmu.num_counters;
592
593 perfctr_fail:
594         for (i--; i >= 0; i--)
595                 release_perfctr_nmi(x86_pmu.perfctr + i);
596
597         if (nmi_watchdog == NMI_LOCAL_APIC)
598                 enable_lapic_nmi_watchdog();
599
600         return false;
601 }
602
603 static void release_pmc_hardware(void)
604 {
605         int i;
606
607         for (i = 0; i < x86_pmu.num_counters; i++) {
608                 release_perfctr_nmi(x86_pmu.perfctr + i);
609                 release_evntsel_nmi(x86_pmu.eventsel + i);
610         }
611
612         if (nmi_watchdog == NMI_LOCAL_APIC)
613                 enable_lapic_nmi_watchdog();
614 }
615
616 static void hw_perf_counter_destroy(struct perf_counter *counter)
617 {
618         if (atomic_dec_and_mutex_lock(&active_counters, &pmc_reserve_mutex)) {
619                 release_pmc_hardware();
620                 mutex_unlock(&pmc_reserve_mutex);
621         }
622 }
623
624 static inline int x86_pmu_initialized(void)
625 {
626         return x86_pmu.handle_irq != NULL;
627 }
628
629 static inline int
630 set_ext_hw_attr(struct hw_perf_counter *hwc, struct perf_counter_attr *attr)
631 {
632         unsigned int cache_type, cache_op, cache_result;
633         u64 config, val;
634
635         config = attr->config;
636
637         cache_type = (config >>  0) & 0xff;
638         if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
639                 return -EINVAL;
640
641         cache_op = (config >>  8) & 0xff;
642         if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
643                 return -EINVAL;
644
645         cache_result = (config >> 16) & 0xff;
646         if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
647                 return -EINVAL;
648
649         val = hw_cache_event_ids[cache_type][cache_op][cache_result];
650
651         if (val == 0)
652                 return -ENOENT;
653
654         if (val == -1)
655                 return -EINVAL;
656
657         hwc->config |= val;
658
659         return 0;
660 }
661
662 /*
663  * Setup the hardware configuration for a given attr_type
664  */
665 static int __hw_perf_counter_init(struct perf_counter *counter)
666 {
667         struct perf_counter_attr *attr = &counter->attr;
668         struct hw_perf_counter *hwc = &counter->hw;
669         int err;
670
671         if (!x86_pmu_initialized())
672                 return -ENODEV;
673
674         err = 0;
675         if (!atomic_inc_not_zero(&active_counters)) {
676                 mutex_lock(&pmc_reserve_mutex);
677                 if (atomic_read(&active_counters) == 0 && !reserve_pmc_hardware())
678                         err = -EBUSY;
679                 else
680                         atomic_inc(&active_counters);
681                 mutex_unlock(&pmc_reserve_mutex);
682         }
683         if (err)
684                 return err;
685
686         /*
687          * Generate PMC IRQs:
688          * (keep 'enabled' bit clear for now)
689          */
690         hwc->config = ARCH_PERFMON_EVENTSEL_INT;
691
692         /*
693          * Count user and OS events unless requested not to.
694          */
695         if (!attr->exclude_user)
696                 hwc->config |= ARCH_PERFMON_EVENTSEL_USR;
697         if (!attr->exclude_kernel)
698                 hwc->config |= ARCH_PERFMON_EVENTSEL_OS;
699
700         if (!hwc->sample_period) {
701                 hwc->sample_period = x86_pmu.max_period;
702                 hwc->last_period = hwc->sample_period;
703                 atomic64_set(&hwc->period_left, hwc->sample_period);
704         }
705
706         counter->destroy = hw_perf_counter_destroy;
707
708         /*
709          * Raw event type provide the config in the event structure
710          */
711         if (attr->type == PERF_TYPE_RAW) {
712                 hwc->config |= x86_pmu.raw_event(attr->config);
713                 return 0;
714         }
715
716         if (attr->type == PERF_TYPE_HW_CACHE)
717                 return set_ext_hw_attr(hwc, attr);
718
719         if (attr->config >= x86_pmu.max_events)
720                 return -EINVAL;
721         /*
722          * The generic map:
723          */
724         hwc->config |= x86_pmu.event_map(attr->config);
725
726         return 0;
727 }
728
729 static void intel_pmu_disable_all(void)
730 {
731         wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0);
732 }
733
734 static void amd_pmu_disable_all(void)
735 {
736         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
737         int idx;
738
739         if (!cpuc->enabled)
740                 return;
741
742         cpuc->enabled = 0;
743         /*
744          * ensure we write the disable before we start disabling the
745          * counters proper, so that amd_pmu_enable_counter() does the
746          * right thing.
747          */
748         barrier();
749
750         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
751                 u64 val;
752
753                 if (!test_bit(idx, cpuc->active_mask))
754                         continue;
755                 rdmsrl(MSR_K7_EVNTSEL0 + idx, val);
756                 if (!(val & ARCH_PERFMON_EVENTSEL0_ENABLE))
757                         continue;
758                 val &= ~ARCH_PERFMON_EVENTSEL0_ENABLE;
759                 wrmsrl(MSR_K7_EVNTSEL0 + idx, val);
760         }
761 }
762
763 void hw_perf_disable(void)
764 {
765         if (!x86_pmu_initialized())
766                 return;
767         return x86_pmu.disable_all();
768 }
769
770 static void intel_pmu_enable_all(void)
771 {
772         wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, x86_pmu.intel_ctrl);
773 }
774
775 static void amd_pmu_enable_all(void)
776 {
777         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
778         int idx;
779
780         if (cpuc->enabled)
781                 return;
782
783         cpuc->enabled = 1;
784         barrier();
785
786         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
787                 u64 val;
788
789                 if (!test_bit(idx, cpuc->active_mask))
790                         continue;
791                 rdmsrl(MSR_K7_EVNTSEL0 + idx, val);
792                 if (val & ARCH_PERFMON_EVENTSEL0_ENABLE)
793                         continue;
794                 val |= ARCH_PERFMON_EVENTSEL0_ENABLE;
795                 wrmsrl(MSR_K7_EVNTSEL0 + idx, val);
796         }
797 }
798
799 void hw_perf_enable(void)
800 {
801         if (!x86_pmu_initialized())
802                 return;
803         x86_pmu.enable_all();
804 }
805
806 static inline u64 intel_pmu_get_status(void)
807 {
808         u64 status;
809
810         rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
811
812         return status;
813 }
814
815 static inline void intel_pmu_ack_status(u64 ack)
816 {
817         wrmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, ack);
818 }
819
820 static inline void x86_pmu_enable_counter(struct hw_perf_counter *hwc, int idx)
821 {
822         int err;
823         err = checking_wrmsrl(hwc->config_base + idx,
824                               hwc->config | ARCH_PERFMON_EVENTSEL0_ENABLE);
825 }
826
827 static inline void x86_pmu_disable_counter(struct hw_perf_counter *hwc, int idx)
828 {
829         int err;
830         err = checking_wrmsrl(hwc->config_base + idx,
831                               hwc->config);
832 }
833
834 static inline void
835 intel_pmu_disable_fixed(struct hw_perf_counter *hwc, int __idx)
836 {
837         int idx = __idx - X86_PMC_IDX_FIXED;
838         u64 ctrl_val, mask;
839         int err;
840
841         mask = 0xfULL << (idx * 4);
842
843         rdmsrl(hwc->config_base, ctrl_val);
844         ctrl_val &= ~mask;
845         err = checking_wrmsrl(hwc->config_base, ctrl_val);
846 }
847
848 static inline void
849 intel_pmu_disable_counter(struct hw_perf_counter *hwc, int idx)
850 {
851         if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
852                 intel_pmu_disable_fixed(hwc, idx);
853                 return;
854         }
855
856         x86_pmu_disable_counter(hwc, idx);
857 }
858
859 static inline void
860 amd_pmu_disable_counter(struct hw_perf_counter *hwc, int idx)
861 {
862         x86_pmu_disable_counter(hwc, idx);
863 }
864
865 static DEFINE_PER_CPU(u64, prev_left[X86_PMC_IDX_MAX]);
866
867 /*
868  * Set the next IRQ period, based on the hwc->period_left value.
869  * To be called with the counter disabled in hw:
870  */
871 static int
872 x86_perf_counter_set_period(struct perf_counter *counter,
873                              struct hw_perf_counter *hwc, int idx)
874 {
875         s64 left = atomic64_read(&hwc->period_left);
876         s64 period = hwc->sample_period;
877         int err, ret = 0;
878
879         /*
880          * If we are way outside a reasoable range then just skip forward:
881          */
882         if (unlikely(left <= -period)) {
883                 left = period;
884                 atomic64_set(&hwc->period_left, left);
885                 hwc->last_period = period;
886                 ret = 1;
887         }
888
889         if (unlikely(left <= 0)) {
890                 left += period;
891                 atomic64_set(&hwc->period_left, left);
892                 hwc->last_period = period;
893                 ret = 1;
894         }
895         /*
896          * Quirk: certain CPUs dont like it if just 1 event is left:
897          */
898         if (unlikely(left < 2))
899                 left = 2;
900
901         if (left > x86_pmu.max_period)
902                 left = x86_pmu.max_period;
903
904         per_cpu(prev_left[idx], smp_processor_id()) = left;
905
906         /*
907          * The hw counter starts counting from this counter offset,
908          * mark it to be able to extra future deltas:
909          */
910         atomic64_set(&hwc->prev_count, (u64)-left);
911
912         err = checking_wrmsrl(hwc->counter_base + idx,
913                              (u64)(-left) & x86_pmu.counter_mask);
914
915         return ret;
916 }
917
918 static inline void
919 intel_pmu_enable_fixed(struct hw_perf_counter *hwc, int __idx)
920 {
921         int idx = __idx - X86_PMC_IDX_FIXED;
922         u64 ctrl_val, bits, mask;
923         int err;
924
925         /*
926          * Enable IRQ generation (0x8),
927          * and enable ring-3 counting (0x2) and ring-0 counting (0x1)
928          * if requested:
929          */
930         bits = 0x8ULL;
931         if (hwc->config & ARCH_PERFMON_EVENTSEL_USR)
932                 bits |= 0x2;
933         if (hwc->config & ARCH_PERFMON_EVENTSEL_OS)
934                 bits |= 0x1;
935         bits <<= (idx * 4);
936         mask = 0xfULL << (idx * 4);
937
938         rdmsrl(hwc->config_base, ctrl_val);
939         ctrl_val &= ~mask;
940         ctrl_val |= bits;
941         err = checking_wrmsrl(hwc->config_base, ctrl_val);
942 }
943
944 static void intel_pmu_enable_counter(struct hw_perf_counter *hwc, int idx)
945 {
946         if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
947                 intel_pmu_enable_fixed(hwc, idx);
948                 return;
949         }
950
951         x86_pmu_enable_counter(hwc, idx);
952 }
953
954 static void amd_pmu_enable_counter(struct hw_perf_counter *hwc, int idx)
955 {
956         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
957
958         if (cpuc->enabled)
959                 x86_pmu_enable_counter(hwc, idx);
960         else
961                 x86_pmu_disable_counter(hwc, idx);
962 }
963
964 static int
965 fixed_mode_idx(struct perf_counter *counter, struct hw_perf_counter *hwc)
966 {
967         unsigned int event;
968
969         if (!x86_pmu.num_counters_fixed)
970                 return -1;
971
972         /*
973          * Quirk, IA32_FIXED_CTRs do not work on current Atom processors:
974          */
975         if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL &&
976                                         boot_cpu_data.x86_model == 28)
977                 return -1;
978
979         event = hwc->config & ARCH_PERFMON_EVENT_MASK;
980
981         if (unlikely(event == x86_pmu.event_map(PERF_COUNT_HW_INSTRUCTIONS)))
982                 return X86_PMC_IDX_FIXED_INSTRUCTIONS;
983         if (unlikely(event == x86_pmu.event_map(PERF_COUNT_HW_CPU_CYCLES)))
984                 return X86_PMC_IDX_FIXED_CPU_CYCLES;
985         if (unlikely(event == x86_pmu.event_map(PERF_COUNT_HW_BUS_CYCLES)))
986                 return X86_PMC_IDX_FIXED_BUS_CYCLES;
987
988         return -1;
989 }
990
991 /*
992  * Find a PMC slot for the freshly enabled / scheduled in counter:
993  */
994 static int x86_pmu_enable(struct perf_counter *counter)
995 {
996         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
997         struct hw_perf_counter *hwc = &counter->hw;
998         int idx;
999
1000         idx = fixed_mode_idx(counter, hwc);
1001         if (idx >= 0) {
1002                 /*
1003                  * Try to get the fixed counter, if that is already taken
1004                  * then try to get a generic counter:
1005                  */
1006                 if (test_and_set_bit(idx, cpuc->used_mask))
1007                         goto try_generic;
1008
1009                 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
1010                 /*
1011                  * We set it so that counter_base + idx in wrmsr/rdmsr maps to
1012                  * MSR_ARCH_PERFMON_FIXED_CTR0 ... CTR2:
1013                  */
1014                 hwc->counter_base =
1015                         MSR_ARCH_PERFMON_FIXED_CTR0 - X86_PMC_IDX_FIXED;
1016                 hwc->idx = idx;
1017         } else {
1018                 idx = hwc->idx;
1019                 /* Try to get the previous generic counter again */
1020                 if (test_and_set_bit(idx, cpuc->used_mask)) {
1021 try_generic:
1022                         idx = find_first_zero_bit(cpuc->used_mask,
1023                                                   x86_pmu.num_counters);
1024                         if (idx == x86_pmu.num_counters)
1025                                 return -EAGAIN;
1026
1027                         set_bit(idx, cpuc->used_mask);
1028                         hwc->idx = idx;
1029                 }
1030                 hwc->config_base  = x86_pmu.eventsel;
1031                 hwc->counter_base = x86_pmu.perfctr;
1032         }
1033
1034         perf_counters_lapic_init();
1035
1036         x86_pmu.disable(hwc, idx);
1037
1038         cpuc->counters[idx] = counter;
1039         set_bit(idx, cpuc->active_mask);
1040
1041         x86_perf_counter_set_period(counter, hwc, idx);
1042         x86_pmu.enable(hwc, idx);
1043
1044         return 0;
1045 }
1046
1047 static void x86_pmu_unthrottle(struct perf_counter *counter)
1048 {
1049         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
1050         struct hw_perf_counter *hwc = &counter->hw;
1051
1052         if (WARN_ON_ONCE(hwc->idx >= X86_PMC_IDX_MAX ||
1053                                 cpuc->counters[hwc->idx] != counter))
1054                 return;
1055
1056         x86_pmu.enable(hwc, hwc->idx);
1057 }
1058
1059 void perf_counter_print_debug(void)
1060 {
1061         u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1062         struct cpu_hw_counters *cpuc;
1063         unsigned long flags;
1064         int cpu, idx;
1065
1066         if (!x86_pmu.num_counters)
1067                 return;
1068
1069         local_irq_save(flags);
1070
1071         cpu = smp_processor_id();
1072         cpuc = &per_cpu(cpu_hw_counters, cpu);
1073
1074         if (x86_pmu.version >= 2) {
1075                 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1076                 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1077                 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1078                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1079
1080                 pr_info("\n");
1081                 pr_info("CPU#%d: ctrl:       %016llx\n", cpu, ctrl);
1082                 pr_info("CPU#%d: status:     %016llx\n", cpu, status);
1083                 pr_info("CPU#%d: overflow:   %016llx\n", cpu, overflow);
1084                 pr_info("CPU#%d: fixed:      %016llx\n", cpu, fixed);
1085         }
1086         pr_info("CPU#%d: used:       %016llx\n", cpu, *(u64 *)cpuc->used_mask);
1087
1088         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1089                 rdmsrl(x86_pmu.eventsel + idx, pmc_ctrl);
1090                 rdmsrl(x86_pmu.perfctr  + idx, pmc_count);
1091
1092                 prev_left = per_cpu(prev_left[idx], cpu);
1093
1094                 pr_info("CPU#%d:   gen-PMC%d ctrl:  %016llx\n",
1095                         cpu, idx, pmc_ctrl);
1096                 pr_info("CPU#%d:   gen-PMC%d count: %016llx\n",
1097                         cpu, idx, pmc_count);
1098                 pr_info("CPU#%d:   gen-PMC%d left:  %016llx\n",
1099                         cpu, idx, prev_left);
1100         }
1101         for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1102                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1103
1104                 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1105                         cpu, idx, pmc_count);
1106         }
1107         local_irq_restore(flags);
1108 }
1109
1110 static void x86_pmu_disable(struct perf_counter *counter)
1111 {
1112         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
1113         struct hw_perf_counter *hwc = &counter->hw;
1114         int idx = hwc->idx;
1115
1116         /*
1117          * Must be done before we disable, otherwise the nmi handler
1118          * could reenable again:
1119          */
1120         clear_bit(idx, cpuc->active_mask);
1121         x86_pmu.disable(hwc, idx);
1122
1123         /*
1124          * Make sure the cleared pointer becomes visible before we
1125          * (potentially) free the counter:
1126          */
1127         barrier();
1128
1129         /*
1130          * Drain the remaining delta count out of a counter
1131          * that we are disabling:
1132          */
1133         x86_perf_counter_update(counter, hwc, idx);
1134         cpuc->counters[idx] = NULL;
1135         clear_bit(idx, cpuc->used_mask);
1136 }
1137
1138 /*
1139  * Save and restart an expired counter. Called by NMI contexts,
1140  * so it has to be careful about preempting normal counter ops:
1141  */
1142 static int intel_pmu_save_and_restart(struct perf_counter *counter)
1143 {
1144         struct hw_perf_counter *hwc = &counter->hw;
1145         int idx = hwc->idx;
1146         int ret;
1147
1148         x86_perf_counter_update(counter, hwc, idx);
1149         ret = x86_perf_counter_set_period(counter, hwc, idx);
1150
1151         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
1152                 intel_pmu_enable_counter(hwc, idx);
1153
1154         return ret;
1155 }
1156
1157 static void intel_pmu_reset(void)
1158 {
1159         unsigned long flags;
1160         int idx;
1161
1162         if (!x86_pmu.num_counters)
1163                 return;
1164
1165         local_irq_save(flags);
1166
1167         printk("clearing PMU state on CPU#%d\n", smp_processor_id());
1168
1169         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1170                 checking_wrmsrl(x86_pmu.eventsel + idx, 0ull);
1171                 checking_wrmsrl(x86_pmu.perfctr  + idx, 0ull);
1172         }
1173         for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1174                 checking_wrmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, 0ull);
1175         }
1176
1177         local_irq_restore(flags);
1178 }
1179
1180
1181 /*
1182  * This handler is triggered by the local APIC, so the APIC IRQ handling
1183  * rules apply:
1184  */
1185 static int intel_pmu_handle_irq(struct pt_regs *regs)
1186 {
1187         struct perf_sample_data data;
1188         struct cpu_hw_counters *cpuc;
1189         int bit, cpu, loops;
1190         u64 ack, status;
1191
1192         data.regs = regs;
1193         data.addr = 0;
1194
1195         cpu = smp_processor_id();
1196         cpuc = &per_cpu(cpu_hw_counters, cpu);
1197
1198         perf_disable();
1199         status = intel_pmu_get_status();
1200         if (!status) {
1201                 perf_enable();
1202                 return 0;
1203         }
1204
1205         loops = 0;
1206 again:
1207         if (++loops > 100) {
1208                 WARN_ONCE(1, "perfcounters: irq loop stuck!\n");
1209                 perf_counter_print_debug();
1210                 intel_pmu_reset();
1211                 perf_enable();
1212                 return 1;
1213         }
1214
1215         inc_irq_stat(apic_perf_irqs);
1216         ack = status;
1217         for_each_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
1218                 struct perf_counter *counter = cpuc->counters[bit];
1219
1220                 clear_bit(bit, (unsigned long *) &status);
1221                 if (!test_bit(bit, cpuc->active_mask))
1222                         continue;
1223
1224                 if (!intel_pmu_save_and_restart(counter))
1225                         continue;
1226
1227                 if (perf_counter_overflow(counter, 1, &data))
1228                         intel_pmu_disable_counter(&counter->hw, bit);
1229         }
1230
1231         intel_pmu_ack_status(ack);
1232
1233         /*
1234          * Repeat if there is more work to be done:
1235          */
1236         status = intel_pmu_get_status();
1237         if (status)
1238                 goto again;
1239
1240         perf_enable();
1241
1242         return 1;
1243 }
1244
1245 static int amd_pmu_handle_irq(struct pt_regs *regs)
1246 {
1247         struct perf_sample_data data;
1248         struct cpu_hw_counters *cpuc;
1249         struct perf_counter *counter;
1250         struct hw_perf_counter *hwc;
1251         int cpu, idx, handled = 0;
1252         u64 val;
1253
1254         data.regs = regs;
1255         data.addr = 0;
1256
1257         cpu = smp_processor_id();
1258         cpuc = &per_cpu(cpu_hw_counters, cpu);
1259
1260         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1261                 if (!test_bit(idx, cpuc->active_mask))
1262                         continue;
1263
1264                 counter = cpuc->counters[idx];
1265                 hwc = &counter->hw;
1266
1267                 val = x86_perf_counter_update(counter, hwc, idx);
1268                 if (val & (1ULL << (x86_pmu.counter_bits - 1)))
1269                         continue;
1270
1271                 /*
1272                  * counter overflow
1273                  */
1274                 handled         = 1;
1275                 data.period     = counter->hw.last_period;
1276
1277                 if (!x86_perf_counter_set_period(counter, hwc, idx))
1278                         continue;
1279
1280                 if (perf_counter_overflow(counter, 1, &data))
1281                         amd_pmu_disable_counter(hwc, idx);
1282         }
1283
1284         if (handled)
1285                 inc_irq_stat(apic_perf_irqs);
1286
1287         return handled;
1288 }
1289
1290 void smp_perf_pending_interrupt(struct pt_regs *regs)
1291 {
1292         irq_enter();
1293         ack_APIC_irq();
1294         inc_irq_stat(apic_pending_irqs);
1295         perf_counter_do_pending();
1296         irq_exit();
1297 }
1298
1299 void set_perf_counter_pending(void)
1300 {
1301         apic->send_IPI_self(LOCAL_PENDING_VECTOR);
1302 }
1303
1304 void perf_counters_lapic_init(void)
1305 {
1306         if (!x86_pmu_initialized())
1307                 return;
1308
1309         /*
1310          * Always use NMI for PMU
1311          */
1312         apic_write(APIC_LVTPC, APIC_DM_NMI);
1313 }
1314
1315 static int __kprobes
1316 perf_counter_nmi_handler(struct notifier_block *self,
1317                          unsigned long cmd, void *__args)
1318 {
1319         struct die_args *args = __args;
1320         struct pt_regs *regs;
1321
1322         if (!atomic_read(&active_counters))
1323                 return NOTIFY_DONE;
1324
1325         switch (cmd) {
1326         case DIE_NMI:
1327         case DIE_NMI_IPI:
1328                 break;
1329
1330         default:
1331                 return NOTIFY_DONE;
1332         }
1333
1334         regs = args->regs;
1335
1336         apic_write(APIC_LVTPC, APIC_DM_NMI);
1337         /*
1338          * Can't rely on the handled return value to say it was our NMI, two
1339          * counters could trigger 'simultaneously' raising two back-to-back NMIs.
1340          *
1341          * If the first NMI handles both, the latter will be empty and daze
1342          * the CPU.
1343          */
1344         x86_pmu.handle_irq(regs);
1345
1346         return NOTIFY_STOP;
1347 }
1348
1349 static __read_mostly struct notifier_block perf_counter_nmi_notifier = {
1350         .notifier_call          = perf_counter_nmi_handler,
1351         .next                   = NULL,
1352         .priority               = 1
1353 };
1354
1355 static struct x86_pmu intel_pmu = {
1356         .name                   = "Intel",
1357         .handle_irq             = intel_pmu_handle_irq,
1358         .disable_all            = intel_pmu_disable_all,
1359         .enable_all             = intel_pmu_enable_all,
1360         .enable                 = intel_pmu_enable_counter,
1361         .disable                = intel_pmu_disable_counter,
1362         .eventsel               = MSR_ARCH_PERFMON_EVENTSEL0,
1363         .perfctr                = MSR_ARCH_PERFMON_PERFCTR0,
1364         .event_map              = intel_pmu_event_map,
1365         .raw_event              = intel_pmu_raw_event,
1366         .max_events             = ARRAY_SIZE(intel_perfmon_event_map),
1367         /*
1368          * Intel PMCs cannot be accessed sanely above 32 bit width,
1369          * so we install an artificial 1<<31 period regardless of
1370          * the generic counter period:
1371          */
1372         .max_period             = (1ULL << 31) - 1,
1373 };
1374
1375 static struct x86_pmu amd_pmu = {
1376         .name                   = "AMD",
1377         .handle_irq             = amd_pmu_handle_irq,
1378         .disable_all            = amd_pmu_disable_all,
1379         .enable_all             = amd_pmu_enable_all,
1380         .enable                 = amd_pmu_enable_counter,
1381         .disable                = amd_pmu_disable_counter,
1382         .eventsel               = MSR_K7_EVNTSEL0,
1383         .perfctr                = MSR_K7_PERFCTR0,
1384         .event_map              = amd_pmu_event_map,
1385         .raw_event              = amd_pmu_raw_event,
1386         .max_events             = ARRAY_SIZE(amd_perfmon_event_map),
1387         .num_counters           = 4,
1388         .counter_bits           = 48,
1389         .counter_mask           = (1ULL << 48) - 1,
1390         /* use highest bit to detect overflow */
1391         .max_period             = (1ULL << 47) - 1,
1392 };
1393
1394 static int intel_pmu_init(void)
1395 {
1396         union cpuid10_edx edx;
1397         union cpuid10_eax eax;
1398         unsigned int unused;
1399         unsigned int ebx;
1400         int version;
1401
1402         if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON))
1403                 return -ENODEV;
1404
1405         /*
1406          * Check whether the Architectural PerfMon supports
1407          * Branch Misses Retired Event or not.
1408          */
1409         cpuid(10, &eax.full, &ebx, &unused, &edx.full);
1410         if (eax.split.mask_length <= ARCH_PERFMON_BRANCH_MISSES_RETIRED)
1411                 return -ENODEV;
1412
1413         version = eax.split.version_id;
1414         if (version < 2)
1415                 return -ENODEV;
1416
1417         x86_pmu                         = intel_pmu;
1418         x86_pmu.version                 = version;
1419         x86_pmu.num_counters            = eax.split.num_counters;
1420         x86_pmu.counter_bits            = eax.split.bit_width;
1421         x86_pmu.counter_mask            = (1ULL << eax.split.bit_width) - 1;
1422
1423         /*
1424          * Quirk: v2 perfmon does not report fixed-purpose counters, so
1425          * assume at least 3 counters:
1426          */
1427         x86_pmu.num_counters_fixed      = max((int)edx.split.num_counters_fixed, 3);
1428
1429         rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, x86_pmu.intel_ctrl);
1430
1431         /*
1432          * Install the hw-cache-events table:
1433          */
1434         switch (boot_cpu_data.x86_model) {
1435         case 15: /* original 65 nm celeron/pentium/core2/xeon, "Merom"/"Conroe" */
1436         case 22: /* single-core 65 nm celeron/core2solo "Merom-L"/"Conroe-L" */
1437         case 23: /* current 45 nm celeron/core2/xeon "Penryn"/"Wolfdale" */
1438         case 29: /* six-core 45 nm xeon "Dunnington" */
1439                 memcpy(hw_cache_event_ids, core2_hw_cache_event_ids,
1440                        sizeof(hw_cache_event_ids));
1441
1442                 pr_cont("Core2 events, ");
1443                 break;
1444         default:
1445         case 26:
1446                 memcpy(hw_cache_event_ids, nehalem_hw_cache_event_ids,
1447                        sizeof(hw_cache_event_ids));
1448
1449                 pr_cont("Nehalem/Corei7 events, ");
1450                 break;
1451         case 28:
1452                 memcpy(hw_cache_event_ids, atom_hw_cache_event_ids,
1453                        sizeof(hw_cache_event_ids));
1454
1455                 pr_cont("Atom events, ");
1456                 break;
1457         }
1458         return 0;
1459 }
1460
1461 static int amd_pmu_init(void)
1462 {
1463         /* Performance-monitoring supported from K7 and later: */
1464         if (boot_cpu_data.x86 < 6)
1465                 return -ENODEV;
1466
1467         x86_pmu = amd_pmu;
1468
1469         /* Events are common for all AMDs */
1470         memcpy(hw_cache_event_ids, amd_hw_cache_event_ids,
1471                sizeof(hw_cache_event_ids));
1472
1473         return 0;
1474 }
1475
1476 void __init init_hw_perf_counters(void)
1477 {
1478         int err;
1479
1480         pr_info("Performance Counters: ");
1481
1482         switch (boot_cpu_data.x86_vendor) {
1483         case X86_VENDOR_INTEL:
1484                 err = intel_pmu_init();
1485                 break;
1486         case X86_VENDOR_AMD:
1487                 err = amd_pmu_init();
1488                 break;
1489         default:
1490                 return;
1491         }
1492         if (err != 0) {
1493                 pr_cont("no PMU driver, software counters only.\n");
1494                 return;
1495         }
1496
1497         pr_cont("%s PMU driver.\n", x86_pmu.name);
1498
1499         if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
1500                 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
1501                 WARN(1, KERN_ERR "hw perf counters %d > max(%d), clipping!",
1502                      x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1503         }
1504         perf_counter_mask = (1 << x86_pmu.num_counters) - 1;
1505         perf_max_counters = x86_pmu.num_counters;
1506
1507         if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1508                 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1509                 WARN(1, KERN_ERR "hw perf counters fixed %d > max(%d), clipping!",
1510                      x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1511         }
1512
1513         perf_counter_mask |=
1514                 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1515
1516         perf_counters_lapic_init();
1517         register_die_notifier(&perf_counter_nmi_notifier);
1518
1519         pr_info("... version:                 %d\n",     x86_pmu.version);
1520         pr_info("... bit width:               %d\n",     x86_pmu.counter_bits);
1521         pr_info("... generic counters:        %d\n",     x86_pmu.num_counters);
1522         pr_info("... value mask:              %016Lx\n", x86_pmu.counter_mask);
1523         pr_info("... max period:              %016Lx\n", x86_pmu.max_period);
1524         pr_info("... fixed-purpose counters:  %d\n",     x86_pmu.num_counters_fixed);
1525         pr_info("... counter mask:            %016Lx\n", perf_counter_mask);
1526 }
1527
1528 static inline void x86_pmu_read(struct perf_counter *counter)
1529 {
1530         x86_perf_counter_update(counter, &counter->hw, counter->hw.idx);
1531 }
1532
1533 static const struct pmu pmu = {
1534         .enable         = x86_pmu_enable,
1535         .disable        = x86_pmu_disable,
1536         .read           = x86_pmu_read,
1537         .unthrottle     = x86_pmu_unthrottle,
1538 };
1539
1540 const struct pmu *hw_perf_counter_init(struct perf_counter *counter)
1541 {
1542         int err;
1543
1544         err = __hw_perf_counter_init(counter);
1545         if (err)
1546                 return ERR_PTR(err);
1547
1548         return &pmu;
1549 }
1550
1551 /*
1552  * callchain support
1553  */
1554
1555 static inline
1556 void callchain_store(struct perf_callchain_entry *entry, unsigned long ip)
1557 {
1558         if (entry->nr < MAX_STACK_DEPTH)
1559                 entry->ip[entry->nr++] = ip;
1560 }
1561
1562 static DEFINE_PER_CPU(struct perf_callchain_entry, irq_entry);
1563 static DEFINE_PER_CPU(struct perf_callchain_entry, nmi_entry);
1564
1565
1566 static void
1567 backtrace_warning_symbol(void *data, char *msg, unsigned long symbol)
1568 {
1569         /* Ignore warnings */
1570 }
1571
1572 static void backtrace_warning(void *data, char *msg)
1573 {
1574         /* Ignore warnings */
1575 }
1576
1577 static int backtrace_stack(void *data, char *name)
1578 {
1579         /* Process all stacks: */
1580         return 0;
1581 }
1582
1583 static void backtrace_address(void *data, unsigned long addr, int reliable)
1584 {
1585         struct perf_callchain_entry *entry = data;
1586
1587         if (reliable)
1588                 callchain_store(entry, addr);
1589 }
1590
1591 static const struct stacktrace_ops backtrace_ops = {
1592         .warning                = backtrace_warning,
1593         .warning_symbol         = backtrace_warning_symbol,
1594         .stack                  = backtrace_stack,
1595         .address                = backtrace_address,
1596 };
1597
1598 #include "../dumpstack.h"
1599
1600 static void
1601 perf_callchain_kernel(struct pt_regs *regs, struct perf_callchain_entry *entry)
1602 {
1603         unsigned long bp;
1604         char *stack;
1605         int nr = entry->nr;
1606
1607         callchain_store(entry, regs->ip);
1608
1609         stack = ((char *)regs + sizeof(struct pt_regs));
1610 #ifdef CONFIG_FRAME_POINTER
1611         get_bp(bp);
1612 #else
1613         bp = 0;
1614 #endif
1615
1616         dump_trace(NULL, regs, (void *)&stack, bp, &backtrace_ops, entry);
1617
1618         entry->kernel = entry->nr - nr;
1619 }
1620
1621 /*
1622  * best effort, GUP based copy_from_user() that assumes IRQ or NMI context
1623  */
1624 static unsigned long
1625 copy_from_user_nmi(void *to, const void __user *from, unsigned long n)
1626 {
1627         unsigned long offset, addr = (unsigned long)from;
1628         int type = in_nmi() ? KM_NMI : KM_IRQ0;
1629         unsigned long size, len = 0;
1630         struct page *page;
1631         void *map;
1632         int ret;
1633
1634         do {
1635                 ret = __get_user_pages_fast(addr, 1, 0, &page);
1636                 if (!ret)
1637                         break;
1638
1639                 offset = addr & (PAGE_SIZE - 1);
1640                 size = min(PAGE_SIZE - offset, n - len);
1641
1642                 map = kmap_atomic(page, type);
1643                 memcpy(to, map+offset, size);
1644                 kunmap_atomic(map, type);
1645                 put_page(page);
1646
1647                 len  += size;
1648                 to   += size;
1649                 addr += size;
1650
1651         } while (len < n);
1652
1653         return len;
1654 }
1655
1656 static int copy_stack_frame(const void __user *fp, struct stack_frame *frame)
1657 {
1658         unsigned long bytes;
1659
1660         bytes = copy_from_user_nmi(frame, fp, sizeof(*frame));
1661
1662         return bytes == sizeof(*frame);
1663 }
1664
1665 static void
1666 perf_callchain_user(struct pt_regs *regs, struct perf_callchain_entry *entry)
1667 {
1668         struct stack_frame frame;
1669         const void __user *fp;
1670         int nr = entry->nr;
1671
1672         if (!user_mode(regs))
1673                 regs = task_pt_regs(current);
1674
1675         fp = (void __user *)regs->bp;
1676
1677         callchain_store(entry, regs->ip);
1678
1679         while (entry->nr < MAX_STACK_DEPTH) {
1680                 frame.next_frame             = NULL;
1681                 frame.return_address = 0;
1682
1683                 if (!copy_stack_frame(fp, &frame))
1684                         break;
1685
1686                 if ((unsigned long)fp < regs->sp)
1687                         break;
1688
1689                 callchain_store(entry, frame.return_address);
1690                 fp = frame.next_frame;
1691         }
1692
1693         entry->user = entry->nr - nr;
1694 }
1695
1696 static void
1697 perf_do_callchain(struct pt_regs *regs, struct perf_callchain_entry *entry)
1698 {
1699         int is_user;
1700
1701         if (!regs)
1702                 return;
1703
1704         is_user = user_mode(regs);
1705
1706         if (!current || current->pid == 0)
1707                 return;
1708
1709         if (is_user && current->state != TASK_RUNNING)
1710                 return;
1711
1712         if (!is_user)
1713                 perf_callchain_kernel(regs, entry);
1714
1715         if (current->mm)
1716                 perf_callchain_user(regs, entry);
1717 }
1718
1719 struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
1720 {
1721         struct perf_callchain_entry *entry;
1722
1723         if (in_nmi())
1724                 entry = &__get_cpu_var(nmi_entry);
1725         else
1726                 entry = &__get_cpu_var(irq_entry);
1727
1728         entry->nr = 0;
1729         entry->hv = 0;
1730         entry->kernel = 0;
1731         entry->user = 0;
1732
1733         perf_do_callchain(regs, entry);
1734
1735         return entry;
1736 }