Merge remote-tracking branch 'lsk/v3.10/topic/arm64-cpuidle' into linux-linaro-lsk
[firefly-linux-kernel-4.4.55.git] / arch / powerpc / perf / core-book3s.c
1 /*
2  * Performance event support - powerpc architecture code
3  *
4  * Copyright 2008-2009 Paul Mackerras, IBM Corporation.
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version
9  * 2 of the License, or (at your option) any later version.
10  */
11 #include <linux/kernel.h>
12 #include <linux/sched.h>
13 #include <linux/perf_event.h>
14 #include <linux/percpu.h>
15 #include <linux/hardirq.h>
16 #include <linux/uaccess.h>
17 #include <asm/reg.h>
18 #include <asm/pmc.h>
19 #include <asm/machdep.h>
20 #include <asm/firmware.h>
21 #include <asm/ptrace.h>
22 #include <asm/code-patching.h>
23
24 #define BHRB_MAX_ENTRIES        32
25 #define BHRB_TARGET             0x0000000000000002
26 #define BHRB_PREDICTION         0x0000000000000001
27 #define BHRB_EA                 0xFFFFFFFFFFFFFFFC
28
29 struct cpu_hw_events {
30         int n_events;
31         int n_percpu;
32         int disabled;
33         int n_added;
34         int n_limited;
35         u8  pmcs_enabled;
36         struct perf_event *event[MAX_HWEVENTS];
37         u64 events[MAX_HWEVENTS];
38         unsigned int flags[MAX_HWEVENTS];
39         unsigned long mmcr[3];
40         struct perf_event *limited_counter[MAX_LIMITED_HWCOUNTERS];
41         u8  limited_hwidx[MAX_LIMITED_HWCOUNTERS];
42         u64 alternatives[MAX_HWEVENTS][MAX_EVENT_ALTERNATIVES];
43         unsigned long amasks[MAX_HWEVENTS][MAX_EVENT_ALTERNATIVES];
44         unsigned long avalues[MAX_HWEVENTS][MAX_EVENT_ALTERNATIVES];
45
46         unsigned int group_flag;
47         int n_txn_start;
48
49         /* BHRB bits */
50         u64                             bhrb_filter;    /* BHRB HW branch filter */
51         int                             bhrb_users;
52         void                            *bhrb_context;
53         struct  perf_branch_stack       bhrb_stack;
54         struct  perf_branch_entry       bhrb_entries[BHRB_MAX_ENTRIES];
55 };
56
57 DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events);
58
59 struct power_pmu *ppmu;
60
61 /*
62  * Normally, to ignore kernel events we set the FCS (freeze counters
63  * in supervisor mode) bit in MMCR0, but if the kernel runs with the
64  * hypervisor bit set in the MSR, or if we are running on a processor
65  * where the hypervisor bit is forced to 1 (as on Apple G5 processors),
66  * then we need to use the FCHV bit to ignore kernel events.
67  */
68 static unsigned int freeze_events_kernel = MMCR0_FCS;
69
70 /*
71  * 32-bit doesn't have MMCRA but does have an MMCR2,
72  * and a few other names are different.
73  */
74 #ifdef CONFIG_PPC32
75
76 #define MMCR0_FCHV              0
77 #define MMCR0_PMCjCE            MMCR0_PMCnCE
78 #define MMCR0_FC56              0
79 #define MMCR0_PMAO              0
80
81 #define SPRN_MMCRA              SPRN_MMCR2
82 #define MMCRA_SAMPLE_ENABLE     0
83
84 static inline unsigned long perf_ip_adjust(struct pt_regs *regs)
85 {
86         return 0;
87 }
88 static inline void perf_get_data_addr(struct pt_regs *regs, u64 *addrp) { }
89 static inline u32 perf_get_misc_flags(struct pt_regs *regs)
90 {
91         return 0;
92 }
93 static inline void perf_read_regs(struct pt_regs *regs)
94 {
95         regs->result = 0;
96 }
97 static inline int perf_intr_is_nmi(struct pt_regs *regs)
98 {
99         return 0;
100 }
101
102 static inline int siar_valid(struct pt_regs *regs)
103 {
104         return 1;
105 }
106
107 static inline void power_pmu_bhrb_enable(struct perf_event *event) {}
108 static inline void power_pmu_bhrb_disable(struct perf_event *event) {}
109 void power_pmu_flush_branch_stack(void) {}
110 static inline void power_pmu_bhrb_read(struct cpu_hw_events *cpuhw) {}
111 #endif /* CONFIG_PPC32 */
112
113 static bool regs_use_siar(struct pt_regs *regs)
114 {
115         return !!regs->result;
116 }
117
118 /*
119  * Things that are specific to 64-bit implementations.
120  */
121 #ifdef CONFIG_PPC64
122
123 static inline unsigned long perf_ip_adjust(struct pt_regs *regs)
124 {
125         unsigned long mmcra = regs->dsisr;
126
127         if ((ppmu->flags & PPMU_HAS_SSLOT) && (mmcra & MMCRA_SAMPLE_ENABLE)) {
128                 unsigned long slot = (mmcra & MMCRA_SLOT) >> MMCRA_SLOT_SHIFT;
129                 if (slot > 1)
130                         return 4 * (slot - 1);
131         }
132
133         return 0;
134 }
135
136 /*
137  * The user wants a data address recorded.
138  * If we're not doing instruction sampling, give them the SDAR
139  * (sampled data address).  If we are doing instruction sampling, then
140  * only give them the SDAR if it corresponds to the instruction
141  * pointed to by SIAR; this is indicated by the [POWER6_]MMCRA_SDSYNC, the
142  * [POWER7P_]MMCRA_SDAR_VALID bit in MMCRA, or the SDAR_VALID bit in SIER.
143  */
144 static inline void perf_get_data_addr(struct pt_regs *regs, u64 *addrp)
145 {
146         unsigned long mmcra = regs->dsisr;
147         bool sdar_valid;
148
149         if (ppmu->flags & PPMU_HAS_SIER)
150                 sdar_valid = regs->dar & SIER_SDAR_VALID;
151         else {
152                 unsigned long sdsync;
153
154                 if (ppmu->flags & PPMU_SIAR_VALID)
155                         sdsync = POWER7P_MMCRA_SDAR_VALID;
156                 else if (ppmu->flags & PPMU_ALT_SIPR)
157                         sdsync = POWER6_MMCRA_SDSYNC;
158                 else
159                         sdsync = MMCRA_SDSYNC;
160
161                 sdar_valid = mmcra & sdsync;
162         }
163
164         if (!(mmcra & MMCRA_SAMPLE_ENABLE) || sdar_valid)
165                 *addrp = mfspr(SPRN_SDAR);
166 }
167
168 static bool regs_sihv(struct pt_regs *regs)
169 {
170         unsigned long sihv = MMCRA_SIHV;
171
172         if (ppmu->flags & PPMU_HAS_SIER)
173                 return !!(regs->dar & SIER_SIHV);
174
175         if (ppmu->flags & PPMU_ALT_SIPR)
176                 sihv = POWER6_MMCRA_SIHV;
177
178         return !!(regs->dsisr & sihv);
179 }
180
181 static bool regs_sipr(struct pt_regs *regs)
182 {
183         unsigned long sipr = MMCRA_SIPR;
184
185         if (ppmu->flags & PPMU_HAS_SIER)
186                 return !!(regs->dar & SIER_SIPR);
187
188         if (ppmu->flags & PPMU_ALT_SIPR)
189                 sipr = POWER6_MMCRA_SIPR;
190
191         return !!(regs->dsisr & sipr);
192 }
193
194 static inline u32 perf_flags_from_msr(struct pt_regs *regs)
195 {
196         if (regs->msr & MSR_PR)
197                 return PERF_RECORD_MISC_USER;
198         if ((regs->msr & MSR_HV) && freeze_events_kernel != MMCR0_FCHV)
199                 return PERF_RECORD_MISC_HYPERVISOR;
200         return PERF_RECORD_MISC_KERNEL;
201 }
202
203 static inline u32 perf_get_misc_flags(struct pt_regs *regs)
204 {
205         bool use_siar = regs_use_siar(regs);
206
207         if (!use_siar)
208                 return perf_flags_from_msr(regs);
209
210         /*
211          * If we don't have flags in MMCRA, rather than using
212          * the MSR, we intuit the flags from the address in
213          * SIAR which should give slightly more reliable
214          * results
215          */
216         if (ppmu->flags & PPMU_NO_SIPR) {
217                 unsigned long siar = mfspr(SPRN_SIAR);
218                 if (siar >= PAGE_OFFSET)
219                         return PERF_RECORD_MISC_KERNEL;
220                 return PERF_RECORD_MISC_USER;
221         }
222
223         /* PR has priority over HV, so order below is important */
224         if (regs_sipr(regs))
225                 return PERF_RECORD_MISC_USER;
226
227         if (regs_sihv(regs) && (freeze_events_kernel != MMCR0_FCHV))
228                 return PERF_RECORD_MISC_HYPERVISOR;
229
230         return PERF_RECORD_MISC_KERNEL;
231 }
232
233 /*
234  * Overload regs->dsisr to store MMCRA so we only need to read it once
235  * on each interrupt.
236  * Overload regs->dar to store SIER if we have it.
237  * Overload regs->result to specify whether we should use the MSR (result
238  * is zero) or the SIAR (result is non zero).
239  */
240 static inline void perf_read_regs(struct pt_regs *regs)
241 {
242         unsigned long mmcra = mfspr(SPRN_MMCRA);
243         int marked = mmcra & MMCRA_SAMPLE_ENABLE;
244         int use_siar;
245
246         regs->dsisr = mmcra;
247
248         if (ppmu->flags & PPMU_HAS_SIER)
249                 regs->dar = mfspr(SPRN_SIER);
250
251         /*
252          * If this isn't a PMU exception (eg a software event) the SIAR is
253          * not valid. Use pt_regs.
254          *
255          * If it is a marked event use the SIAR.
256          *
257          * If the PMU doesn't update the SIAR for non marked events use
258          * pt_regs.
259          *
260          * If the PMU has HV/PR flags then check to see if they
261          * place the exception in userspace. If so, use pt_regs. In
262          * continuous sampling mode the SIAR and the PMU exception are
263          * not synchronised, so they may be many instructions apart.
264          * This can result in confusing backtraces. We still want
265          * hypervisor samples as well as samples in the kernel with
266          * interrupts off hence the userspace check.
267          */
268         if (TRAP(regs) != 0xf00)
269                 use_siar = 0;
270         else if (marked)
271                 use_siar = 1;
272         else if ((ppmu->flags & PPMU_NO_CONT_SAMPLING))
273                 use_siar = 0;
274         else if (!(ppmu->flags & PPMU_NO_SIPR) && regs_sipr(regs))
275                 use_siar = 0;
276         else
277                 use_siar = 1;
278
279         regs->result = use_siar;
280 }
281
282 /*
283  * If interrupts were soft-disabled when a PMU interrupt occurs, treat
284  * it as an NMI.
285  */
286 static inline int perf_intr_is_nmi(struct pt_regs *regs)
287 {
288         return !regs->softe;
289 }
290
291 /*
292  * On processors like P7+ that have the SIAR-Valid bit, marked instructions
293  * must be sampled only if the SIAR-valid bit is set.
294  *
295  * For unmarked instructions and for processors that don't have the SIAR-Valid
296  * bit, assume that SIAR is valid.
297  */
298 static inline int siar_valid(struct pt_regs *regs)
299 {
300         unsigned long mmcra = regs->dsisr;
301         int marked = mmcra & MMCRA_SAMPLE_ENABLE;
302
303         if (marked) {
304                 if (ppmu->flags & PPMU_HAS_SIER)
305                         return regs->dar & SIER_SIAR_VALID;
306
307                 if (ppmu->flags & PPMU_SIAR_VALID)
308                         return mmcra & POWER7P_MMCRA_SIAR_VALID;
309         }
310
311         return 1;
312 }
313
314
315 /* Reset all possible BHRB entries */
316 static void power_pmu_bhrb_reset(void)
317 {
318         asm volatile(PPC_CLRBHRB);
319 }
320
321 static void power_pmu_bhrb_enable(struct perf_event *event)
322 {
323         struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
324
325         if (!ppmu->bhrb_nr)
326                 return;
327
328         /* Clear BHRB if we changed task context to avoid data leaks */
329         if (event->ctx->task && cpuhw->bhrb_context != event->ctx) {
330                 power_pmu_bhrb_reset();
331                 cpuhw->bhrb_context = event->ctx;
332         }
333         cpuhw->bhrb_users++;
334 }
335
336 static void power_pmu_bhrb_disable(struct perf_event *event)
337 {
338         struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
339
340         if (!ppmu->bhrb_nr)
341                 return;
342
343         cpuhw->bhrb_users--;
344         WARN_ON_ONCE(cpuhw->bhrb_users < 0);
345
346         if (!cpuhw->disabled && !cpuhw->bhrb_users) {
347                 /* BHRB cannot be turned off when other
348                  * events are active on the PMU.
349                  */
350
351                 /* avoid stale pointer */
352                 cpuhw->bhrb_context = NULL;
353         }
354 }
355
356 /* Called from ctxsw to prevent one process's branch entries to
357  * mingle with the other process's entries during context switch.
358  */
359 void power_pmu_flush_branch_stack(void)
360 {
361         if (ppmu->bhrb_nr)
362                 power_pmu_bhrb_reset();
363 }
364 /* Calculate the to address for a branch */
365 static __u64 power_pmu_bhrb_to(u64 addr)
366 {
367         unsigned int instr;
368         int ret;
369         __u64 target;
370
371         if (is_kernel_addr(addr))
372                 return branch_target((unsigned int *)addr);
373
374         /* Userspace: need copy instruction here then translate it */
375         pagefault_disable();
376         ret = __get_user_inatomic(instr, (unsigned int __user *)addr);
377         if (ret) {
378                 pagefault_enable();
379                 return 0;
380         }
381         pagefault_enable();
382
383         target = branch_target(&instr);
384         if ((!target) || (instr & BRANCH_ABSOLUTE))
385                 return target;
386
387         /* Translate relative branch target from kernel to user address */
388         return target - (unsigned long)&instr + addr;
389 }
390
391 /* Processing BHRB entries */
392 void power_pmu_bhrb_read(struct cpu_hw_events *cpuhw)
393 {
394         u64 val;
395         u64 addr;
396         int r_index, u_index, pred;
397
398         r_index = 0;
399         u_index = 0;
400         while (r_index < ppmu->bhrb_nr) {
401                 /* Assembly read function */
402                 val = read_bhrb(r_index++);
403                 if (!val)
404                         /* Terminal marker: End of valid BHRB entries */
405                         break;
406                 else {
407                         addr = val & BHRB_EA;
408                         pred = val & BHRB_PREDICTION;
409
410                         if (!addr)
411                                 /* invalid entry */
412                                 continue;
413
414                         /* Branches are read most recent first (ie. mfbhrb 0 is
415                          * the most recent branch).
416                          * There are two types of valid entries:
417                          * 1) a target entry which is the to address of a
418                          *    computed goto like a blr,bctr,btar.  The next
419                          *    entry read from the bhrb will be branch
420                          *    corresponding to this target (ie. the actual
421                          *    blr/bctr/btar instruction).
422                          * 2) a from address which is an actual branch.  If a
423                          *    target entry proceeds this, then this is the
424                          *    matching branch for that target.  If this is not
425                          *    following a target entry, then this is a branch
426                          *    where the target is given as an immediate field
427                          *    in the instruction (ie. an i or b form branch).
428                          *    In this case we need to read the instruction from
429                          *    memory to determine the target/to address.
430                          */
431
432                         if (val & BHRB_TARGET) {
433                                 /* Target branches use two entries
434                                  * (ie. computed gotos/XL form)
435                                  */
436                                 cpuhw->bhrb_entries[u_index].to = addr;
437                                 cpuhw->bhrb_entries[u_index].mispred = pred;
438                                 cpuhw->bhrb_entries[u_index].predicted = ~pred;
439
440                                 /* Get from address in next entry */
441                                 val = read_bhrb(r_index++);
442                                 addr = val & BHRB_EA;
443                                 if (val & BHRB_TARGET) {
444                                         /* Shouldn't have two targets in a
445                                            row.. Reset index and try again */
446                                         r_index--;
447                                         addr = 0;
448                                 }
449                                 cpuhw->bhrb_entries[u_index].from = addr;
450                         } else {
451                                 /* Branches to immediate field 
452                                    (ie I or B form) */
453                                 cpuhw->bhrb_entries[u_index].from = addr;
454                                 cpuhw->bhrb_entries[u_index].to =
455                                         power_pmu_bhrb_to(addr);
456                                 cpuhw->bhrb_entries[u_index].mispred = pred;
457                                 cpuhw->bhrb_entries[u_index].predicted = ~pred;
458                         }
459                         u_index++;
460
461                 }
462         }
463         cpuhw->bhrb_stack.nr = u_index;
464         return;
465 }
466
467 #endif /* CONFIG_PPC64 */
468
469 static void perf_event_interrupt(struct pt_regs *regs);
470
471 void perf_event_print_debug(void)
472 {
473 }
474
475 /*
476  * Read one performance monitor counter (PMC).
477  */
478 static unsigned long read_pmc(int idx)
479 {
480         unsigned long val;
481
482         switch (idx) {
483         case 1:
484                 val = mfspr(SPRN_PMC1);
485                 break;
486         case 2:
487                 val = mfspr(SPRN_PMC2);
488                 break;
489         case 3:
490                 val = mfspr(SPRN_PMC3);
491                 break;
492         case 4:
493                 val = mfspr(SPRN_PMC4);
494                 break;
495         case 5:
496                 val = mfspr(SPRN_PMC5);
497                 break;
498         case 6:
499                 val = mfspr(SPRN_PMC6);
500                 break;
501 #ifdef CONFIG_PPC64
502         case 7:
503                 val = mfspr(SPRN_PMC7);
504                 break;
505         case 8:
506                 val = mfspr(SPRN_PMC8);
507                 break;
508 #endif /* CONFIG_PPC64 */
509         default:
510                 printk(KERN_ERR "oops trying to read PMC%d\n", idx);
511                 val = 0;
512         }
513         return val;
514 }
515
516 /*
517  * Write one PMC.
518  */
519 static void write_pmc(int idx, unsigned long val)
520 {
521         switch (idx) {
522         case 1:
523                 mtspr(SPRN_PMC1, val);
524                 break;
525         case 2:
526                 mtspr(SPRN_PMC2, val);
527                 break;
528         case 3:
529                 mtspr(SPRN_PMC3, val);
530                 break;
531         case 4:
532                 mtspr(SPRN_PMC4, val);
533                 break;
534         case 5:
535                 mtspr(SPRN_PMC5, val);
536                 break;
537         case 6:
538                 mtspr(SPRN_PMC6, val);
539                 break;
540 #ifdef CONFIG_PPC64
541         case 7:
542                 mtspr(SPRN_PMC7, val);
543                 break;
544         case 8:
545                 mtspr(SPRN_PMC8, val);
546                 break;
547 #endif /* CONFIG_PPC64 */
548         default:
549                 printk(KERN_ERR "oops trying to write PMC%d\n", idx);
550         }
551 }
552
553 /*
554  * Check if a set of events can all go on the PMU at once.
555  * If they can't, this will look at alternative codes for the events
556  * and see if any combination of alternative codes is feasible.
557  * The feasible set is returned in event_id[].
558  */
559 static int power_check_constraints(struct cpu_hw_events *cpuhw,
560                                    u64 event_id[], unsigned int cflags[],
561                                    int n_ev)
562 {
563         unsigned long mask, value, nv;
564         unsigned long smasks[MAX_HWEVENTS], svalues[MAX_HWEVENTS];
565         int n_alt[MAX_HWEVENTS], choice[MAX_HWEVENTS];
566         int i, j;
567         unsigned long addf = ppmu->add_fields;
568         unsigned long tadd = ppmu->test_adder;
569
570         if (n_ev > ppmu->n_counter)
571                 return -1;
572
573         /* First see if the events will go on as-is */
574         for (i = 0; i < n_ev; ++i) {
575                 if ((cflags[i] & PPMU_LIMITED_PMC_REQD)
576                     && !ppmu->limited_pmc_event(event_id[i])) {
577                         ppmu->get_alternatives(event_id[i], cflags[i],
578                                                cpuhw->alternatives[i]);
579                         event_id[i] = cpuhw->alternatives[i][0];
580                 }
581                 if (ppmu->get_constraint(event_id[i], &cpuhw->amasks[i][0],
582                                          &cpuhw->avalues[i][0]))
583                         return -1;
584         }
585         value = mask = 0;
586         for (i = 0; i < n_ev; ++i) {
587                 nv = (value | cpuhw->avalues[i][0]) +
588                         (value & cpuhw->avalues[i][0] & addf);
589                 if ((((nv + tadd) ^ value) & mask) != 0 ||
590                     (((nv + tadd) ^ cpuhw->avalues[i][0]) &
591                      cpuhw->amasks[i][0]) != 0)
592                         break;
593                 value = nv;
594                 mask |= cpuhw->amasks[i][0];
595         }
596         if (i == n_ev)
597                 return 0;       /* all OK */
598
599         /* doesn't work, gather alternatives... */
600         if (!ppmu->get_alternatives)
601                 return -1;
602         for (i = 0; i < n_ev; ++i) {
603                 choice[i] = 0;
604                 n_alt[i] = ppmu->get_alternatives(event_id[i], cflags[i],
605                                                   cpuhw->alternatives[i]);
606                 for (j = 1; j < n_alt[i]; ++j)
607                         ppmu->get_constraint(cpuhw->alternatives[i][j],
608                                              &cpuhw->amasks[i][j],
609                                              &cpuhw->avalues[i][j]);
610         }
611
612         /* enumerate all possibilities and see if any will work */
613         i = 0;
614         j = -1;
615         value = mask = nv = 0;
616         while (i < n_ev) {
617                 if (j >= 0) {
618                         /* we're backtracking, restore context */
619                         value = svalues[i];
620                         mask = smasks[i];
621                         j = choice[i];
622                 }
623                 /*
624                  * See if any alternative k for event_id i,
625                  * where k > j, will satisfy the constraints.
626                  */
627                 while (++j < n_alt[i]) {
628                         nv = (value | cpuhw->avalues[i][j]) +
629                                 (value & cpuhw->avalues[i][j] & addf);
630                         if ((((nv + tadd) ^ value) & mask) == 0 &&
631                             (((nv + tadd) ^ cpuhw->avalues[i][j])
632                              & cpuhw->amasks[i][j]) == 0)
633                                 break;
634                 }
635                 if (j >= n_alt[i]) {
636                         /*
637                          * No feasible alternative, backtrack
638                          * to event_id i-1 and continue enumerating its
639                          * alternatives from where we got up to.
640                          */
641                         if (--i < 0)
642                                 return -1;
643                 } else {
644                         /*
645                          * Found a feasible alternative for event_id i,
646                          * remember where we got up to with this event_id,
647                          * go on to the next event_id, and start with
648                          * the first alternative for it.
649                          */
650                         choice[i] = j;
651                         svalues[i] = value;
652                         smasks[i] = mask;
653                         value = nv;
654                         mask |= cpuhw->amasks[i][j];
655                         ++i;
656                         j = -1;
657                 }
658         }
659
660         /* OK, we have a feasible combination, tell the caller the solution */
661         for (i = 0; i < n_ev; ++i)
662                 event_id[i] = cpuhw->alternatives[i][choice[i]];
663         return 0;
664 }
665
666 /*
667  * Check if newly-added events have consistent settings for
668  * exclude_{user,kernel,hv} with each other and any previously
669  * added events.
670  */
671 static int check_excludes(struct perf_event **ctrs, unsigned int cflags[],
672                           int n_prev, int n_new)
673 {
674         int eu = 0, ek = 0, eh = 0;
675         int i, n, first;
676         struct perf_event *event;
677
678         n = n_prev + n_new;
679         if (n <= 1)
680                 return 0;
681
682         first = 1;
683         for (i = 0; i < n; ++i) {
684                 if (cflags[i] & PPMU_LIMITED_PMC_OK) {
685                         cflags[i] &= ~PPMU_LIMITED_PMC_REQD;
686                         continue;
687                 }
688                 event = ctrs[i];
689                 if (first) {
690                         eu = event->attr.exclude_user;
691                         ek = event->attr.exclude_kernel;
692                         eh = event->attr.exclude_hv;
693                         first = 0;
694                 } else if (event->attr.exclude_user != eu ||
695                            event->attr.exclude_kernel != ek ||
696                            event->attr.exclude_hv != eh) {
697                         return -EAGAIN;
698                 }
699         }
700
701         if (eu || ek || eh)
702                 for (i = 0; i < n; ++i)
703                         if (cflags[i] & PPMU_LIMITED_PMC_OK)
704                                 cflags[i] |= PPMU_LIMITED_PMC_REQD;
705
706         return 0;
707 }
708
709 static u64 check_and_compute_delta(u64 prev, u64 val)
710 {
711         u64 delta = (val - prev) & 0xfffffffful;
712
713         /*
714          * POWER7 can roll back counter values, if the new value is smaller
715          * than the previous value it will cause the delta and the counter to
716          * have bogus values unless we rolled a counter over.  If a coutner is
717          * rolled back, it will be smaller, but within 256, which is the maximum
718          * number of events to rollback at once.  If we dectect a rollback
719          * return 0.  This can lead to a small lack of precision in the
720          * counters.
721          */
722         if (prev > val && (prev - val) < 256)
723                 delta = 0;
724
725         return delta;
726 }
727
728 static void power_pmu_read(struct perf_event *event)
729 {
730         s64 val, delta, prev;
731
732         if (event->hw.state & PERF_HES_STOPPED)
733                 return;
734
735         if (!event->hw.idx)
736                 return;
737         /*
738          * Performance monitor interrupts come even when interrupts
739          * are soft-disabled, as long as interrupts are hard-enabled.
740          * Therefore we treat them like NMIs.
741          */
742         do {
743                 prev = local64_read(&event->hw.prev_count);
744                 barrier();
745                 val = read_pmc(event->hw.idx);
746                 delta = check_and_compute_delta(prev, val);
747                 if (!delta)
748                         return;
749         } while (local64_cmpxchg(&event->hw.prev_count, prev, val) != prev);
750
751         local64_add(delta, &event->count);
752
753         /*
754          * A number of places program the PMC with (0x80000000 - period_left).
755          * We never want period_left to be less than 1 because we will program
756          * the PMC with a value >= 0x800000000 and an edge detected PMC will
757          * roll around to 0 before taking an exception. We have seen this
758          * on POWER8.
759          *
760          * To fix this, clamp the minimum value of period_left to 1.
761          */
762         do {
763                 prev = local64_read(&event->hw.period_left);
764                 val = prev - delta;
765                 if (val < 1)
766                         val = 1;
767         } while (local64_cmpxchg(&event->hw.period_left, prev, val) != prev);
768 }
769
770 /*
771  * On some machines, PMC5 and PMC6 can't be written, don't respect
772  * the freeze conditions, and don't generate interrupts.  This tells
773  * us if `event' is using such a PMC.
774  */
775 static int is_limited_pmc(int pmcnum)
776 {
777         return (ppmu->flags & PPMU_LIMITED_PMC5_6)
778                 && (pmcnum == 5 || pmcnum == 6);
779 }
780
781 static void freeze_limited_counters(struct cpu_hw_events *cpuhw,
782                                     unsigned long pmc5, unsigned long pmc6)
783 {
784         struct perf_event *event;
785         u64 val, prev, delta;
786         int i;
787
788         for (i = 0; i < cpuhw->n_limited; ++i) {
789                 event = cpuhw->limited_counter[i];
790                 if (!event->hw.idx)
791                         continue;
792                 val = (event->hw.idx == 5) ? pmc5 : pmc6;
793                 prev = local64_read(&event->hw.prev_count);
794                 event->hw.idx = 0;
795                 delta = check_and_compute_delta(prev, val);
796                 if (delta)
797                         local64_add(delta, &event->count);
798         }
799 }
800
801 static void thaw_limited_counters(struct cpu_hw_events *cpuhw,
802                                   unsigned long pmc5, unsigned long pmc6)
803 {
804         struct perf_event *event;
805         u64 val, prev;
806         int i;
807
808         for (i = 0; i < cpuhw->n_limited; ++i) {
809                 event = cpuhw->limited_counter[i];
810                 event->hw.idx = cpuhw->limited_hwidx[i];
811                 val = (event->hw.idx == 5) ? pmc5 : pmc6;
812                 prev = local64_read(&event->hw.prev_count);
813                 if (check_and_compute_delta(prev, val))
814                         local64_set(&event->hw.prev_count, val);
815                 perf_event_update_userpage(event);
816         }
817 }
818
819 /*
820  * Since limited events don't respect the freeze conditions, we
821  * have to read them immediately after freezing or unfreezing the
822  * other events.  We try to keep the values from the limited
823  * events as consistent as possible by keeping the delay (in
824  * cycles and instructions) between freezing/unfreezing and reading
825  * the limited events as small and consistent as possible.
826  * Therefore, if any limited events are in use, we read them
827  * both, and always in the same order, to minimize variability,
828  * and do it inside the same asm that writes MMCR0.
829  */
830 static void write_mmcr0(struct cpu_hw_events *cpuhw, unsigned long mmcr0)
831 {
832         unsigned long pmc5, pmc6;
833
834         if (!cpuhw->n_limited) {
835                 mtspr(SPRN_MMCR0, mmcr0);
836                 return;
837         }
838
839         /*
840          * Write MMCR0, then read PMC5 and PMC6 immediately.
841          * To ensure we don't get a performance monitor interrupt
842          * between writing MMCR0 and freezing/thawing the limited
843          * events, we first write MMCR0 with the event overflow
844          * interrupt enable bits turned off.
845          */
846         asm volatile("mtspr %3,%2; mfspr %0,%4; mfspr %1,%5"
847                      : "=&r" (pmc5), "=&r" (pmc6)
848                      : "r" (mmcr0 & ~(MMCR0_PMC1CE | MMCR0_PMCjCE)),
849                        "i" (SPRN_MMCR0),
850                        "i" (SPRN_PMC5), "i" (SPRN_PMC6));
851
852         if (mmcr0 & MMCR0_FC)
853                 freeze_limited_counters(cpuhw, pmc5, pmc6);
854         else
855                 thaw_limited_counters(cpuhw, pmc5, pmc6);
856
857         /*
858          * Write the full MMCR0 including the event overflow interrupt
859          * enable bits, if necessary.
860          */
861         if (mmcr0 & (MMCR0_PMC1CE | MMCR0_PMCjCE))
862                 mtspr(SPRN_MMCR0, mmcr0);
863 }
864
865 /*
866  * Disable all events to prevent PMU interrupts and to allow
867  * events to be added or removed.
868  */
869 static void power_pmu_disable(struct pmu *pmu)
870 {
871         struct cpu_hw_events *cpuhw;
872         unsigned long flags, val;
873
874         if (!ppmu)
875                 return;
876         local_irq_save(flags);
877         cpuhw = &__get_cpu_var(cpu_hw_events);
878
879         if (!cpuhw->disabled) {
880                 /*
881                  * Check if we ever enabled the PMU on this cpu.
882                  */
883                 if (!cpuhw->pmcs_enabled) {
884                         ppc_enable_pmcs();
885                         cpuhw->pmcs_enabled = 1;
886                 }
887
888                 /*
889                  * Set the 'freeze counters' bit, clear PMAO/FC56.
890                  */
891                 val  = mfspr(SPRN_MMCR0);
892                 val |= MMCR0_FC;
893                 val &= ~(MMCR0_PMAO | MMCR0_FC56);
894
895                 /*
896                  * The barrier is to make sure the mtspr has been
897                  * executed and the PMU has frozen the events etc.
898                  * before we return.
899                  */
900                 write_mmcr0(cpuhw, val);
901                 mb();
902
903                 /*
904                  * Disable instruction sampling if it was enabled
905                  */
906                 if (cpuhw->mmcr[2] & MMCRA_SAMPLE_ENABLE) {
907                         mtspr(SPRN_MMCRA,
908                               cpuhw->mmcr[2] & ~MMCRA_SAMPLE_ENABLE);
909                         mb();
910                 }
911
912                 cpuhw->disabled = 1;
913                 cpuhw->n_added = 0;
914         }
915         local_irq_restore(flags);
916 }
917
918 /*
919  * Re-enable all events if disable == 0.
920  * If we were previously disabled and events were added, then
921  * put the new config on the PMU.
922  */
923 static void power_pmu_enable(struct pmu *pmu)
924 {
925         struct perf_event *event;
926         struct cpu_hw_events *cpuhw;
927         unsigned long flags;
928         long i;
929         unsigned long val;
930         s64 left;
931         unsigned int hwc_index[MAX_HWEVENTS];
932         int n_lim;
933         int idx;
934
935         if (!ppmu)
936                 return;
937
938         local_irq_save(flags);
939
940         cpuhw = &__get_cpu_var(cpu_hw_events);
941         if (!cpuhw->disabled)
942                 goto out;
943
944         if (cpuhw->n_events == 0) {
945                 ppc_set_pmu_inuse(0);
946                 goto out;
947         }
948
949         cpuhw->disabled = 0;
950
951         /*
952          * If we didn't change anything, or only removed events,
953          * no need to recalculate MMCR* settings and reset the PMCs.
954          * Just reenable the PMU with the current MMCR* settings
955          * (possibly updated for removal of events).
956          */
957         if (!cpuhw->n_added) {
958                 mtspr(SPRN_MMCRA, cpuhw->mmcr[2] & ~MMCRA_SAMPLE_ENABLE);
959                 mtspr(SPRN_MMCR1, cpuhw->mmcr[1]);
960                 goto out_enable;
961         }
962
963         /*
964          * Compute MMCR* values for the new set of events
965          */
966         if (ppmu->compute_mmcr(cpuhw->events, cpuhw->n_events, hwc_index,
967                                cpuhw->mmcr)) {
968                 /* shouldn't ever get here */
969                 printk(KERN_ERR "oops compute_mmcr failed\n");
970                 goto out;
971         }
972
973         /*
974          * Add in MMCR0 freeze bits corresponding to the
975          * attr.exclude_* bits for the first event.
976          * We have already checked that all events have the
977          * same values for these bits as the first event.
978          */
979         event = cpuhw->event[0];
980         if (event->attr.exclude_user)
981                 cpuhw->mmcr[0] |= MMCR0_FCP;
982         if (event->attr.exclude_kernel)
983                 cpuhw->mmcr[0] |= freeze_events_kernel;
984         if (event->attr.exclude_hv)
985                 cpuhw->mmcr[0] |= MMCR0_FCHV;
986
987         /*
988          * Write the new configuration to MMCR* with the freeze
989          * bit set and set the hardware events to their initial values.
990          * Then unfreeze the events.
991          */
992         ppc_set_pmu_inuse(1);
993         mtspr(SPRN_MMCRA, cpuhw->mmcr[2] & ~MMCRA_SAMPLE_ENABLE);
994         mtspr(SPRN_MMCR1, cpuhw->mmcr[1]);
995         mtspr(SPRN_MMCR0, (cpuhw->mmcr[0] & ~(MMCR0_PMC1CE | MMCR0_PMCjCE))
996                                 | MMCR0_FC);
997
998         /*
999          * Read off any pre-existing events that need to move
1000          * to another PMC.
1001          */
1002         for (i = 0; i < cpuhw->n_events; ++i) {
1003                 event = cpuhw->event[i];
1004                 if (event->hw.idx && event->hw.idx != hwc_index[i] + 1) {
1005                         power_pmu_read(event);
1006                         write_pmc(event->hw.idx, 0);
1007                         event->hw.idx = 0;
1008                 }
1009         }
1010
1011         /*
1012          * Initialize the PMCs for all the new and moved events.
1013          */
1014         cpuhw->n_limited = n_lim = 0;
1015         for (i = 0; i < cpuhw->n_events; ++i) {
1016                 event = cpuhw->event[i];
1017                 if (event->hw.idx)
1018                         continue;
1019                 idx = hwc_index[i] + 1;
1020                 if (is_limited_pmc(idx)) {
1021                         cpuhw->limited_counter[n_lim] = event;
1022                         cpuhw->limited_hwidx[n_lim] = idx;
1023                         ++n_lim;
1024                         continue;
1025                 }
1026                 val = 0;
1027                 if (event->hw.sample_period) {
1028                         left = local64_read(&event->hw.period_left);
1029                         if (left < 0x80000000L)
1030                                 val = 0x80000000L - left;
1031                 }
1032                 local64_set(&event->hw.prev_count, val);
1033                 event->hw.idx = idx;
1034                 if (event->hw.state & PERF_HES_STOPPED)
1035                         val = 0;
1036                 write_pmc(idx, val);
1037                 perf_event_update_userpage(event);
1038         }
1039         cpuhw->n_limited = n_lim;
1040         cpuhw->mmcr[0] |= MMCR0_PMXE | MMCR0_FCECE;
1041
1042  out_enable:
1043         mb();
1044         write_mmcr0(cpuhw, cpuhw->mmcr[0]);
1045
1046         /*
1047          * Enable instruction sampling if necessary
1048          */
1049         if (cpuhw->mmcr[2] & MMCRA_SAMPLE_ENABLE) {
1050                 mb();
1051                 mtspr(SPRN_MMCRA, cpuhw->mmcr[2]);
1052         }
1053
1054  out:
1055         if (cpuhw->bhrb_users)
1056                 ppmu->config_bhrb(cpuhw->bhrb_filter);
1057
1058         local_irq_restore(flags);
1059 }
1060
1061 static int collect_events(struct perf_event *group, int max_count,
1062                           struct perf_event *ctrs[], u64 *events,
1063                           unsigned int *flags)
1064 {
1065         int n = 0;
1066         struct perf_event *event;
1067
1068         if (!is_software_event(group)) {
1069                 if (n >= max_count)
1070                         return -1;
1071                 ctrs[n] = group;
1072                 flags[n] = group->hw.event_base;
1073                 events[n++] = group->hw.config;
1074         }
1075         list_for_each_entry(event, &group->sibling_list, group_entry) {
1076                 if (!is_software_event(event) &&
1077                     event->state != PERF_EVENT_STATE_OFF) {
1078                         if (n >= max_count)
1079                                 return -1;
1080                         ctrs[n] = event;
1081                         flags[n] = event->hw.event_base;
1082                         events[n++] = event->hw.config;
1083                 }
1084         }
1085         return n;
1086 }
1087
1088 /*
1089  * Add a event to the PMU.
1090  * If all events are not already frozen, then we disable and
1091  * re-enable the PMU in order to get hw_perf_enable to do the
1092  * actual work of reconfiguring the PMU.
1093  */
1094 static int power_pmu_add(struct perf_event *event, int ef_flags)
1095 {
1096         struct cpu_hw_events *cpuhw;
1097         unsigned long flags;
1098         int n0;
1099         int ret = -EAGAIN;
1100
1101         local_irq_save(flags);
1102         perf_pmu_disable(event->pmu);
1103
1104         /*
1105          * Add the event to the list (if there is room)
1106          * and check whether the total set is still feasible.
1107          */
1108         cpuhw = &__get_cpu_var(cpu_hw_events);
1109         n0 = cpuhw->n_events;
1110         if (n0 >= ppmu->n_counter)
1111                 goto out;
1112         cpuhw->event[n0] = event;
1113         cpuhw->events[n0] = event->hw.config;
1114         cpuhw->flags[n0] = event->hw.event_base;
1115
1116         /*
1117          * This event may have been disabled/stopped in record_and_restart()
1118          * because we exceeded the ->event_limit. If re-starting the event,
1119          * clear the ->hw.state (STOPPED and UPTODATE flags), so the user
1120          * notification is re-enabled.
1121          */
1122         if (!(ef_flags & PERF_EF_START))
1123                 event->hw.state = PERF_HES_STOPPED | PERF_HES_UPTODATE;
1124         else
1125                 event->hw.state = 0;
1126
1127         /*
1128          * If group events scheduling transaction was started,
1129          * skip the schedulability test here, it will be performed
1130          * at commit time(->commit_txn) as a whole
1131          */
1132         if (cpuhw->group_flag & PERF_EVENT_TXN)
1133                 goto nocheck;
1134
1135         if (check_excludes(cpuhw->event, cpuhw->flags, n0, 1))
1136                 goto out;
1137         if (power_check_constraints(cpuhw, cpuhw->events, cpuhw->flags, n0 + 1))
1138                 goto out;
1139         event->hw.config = cpuhw->events[n0];
1140
1141 nocheck:
1142         ++cpuhw->n_events;
1143         ++cpuhw->n_added;
1144
1145         ret = 0;
1146  out:
1147         if (has_branch_stack(event))
1148                 power_pmu_bhrb_enable(event);
1149
1150         perf_pmu_enable(event->pmu);
1151         local_irq_restore(flags);
1152         return ret;
1153 }
1154
1155 /*
1156  * Remove a event from the PMU.
1157  */
1158 static void power_pmu_del(struct perf_event *event, int ef_flags)
1159 {
1160         struct cpu_hw_events *cpuhw;
1161         long i;
1162         unsigned long flags;
1163
1164         local_irq_save(flags);
1165         perf_pmu_disable(event->pmu);
1166
1167         power_pmu_read(event);
1168
1169         cpuhw = &__get_cpu_var(cpu_hw_events);
1170         for (i = 0; i < cpuhw->n_events; ++i) {
1171                 if (event == cpuhw->event[i]) {
1172                         while (++i < cpuhw->n_events) {
1173                                 cpuhw->event[i-1] = cpuhw->event[i];
1174                                 cpuhw->events[i-1] = cpuhw->events[i];
1175                                 cpuhw->flags[i-1] = cpuhw->flags[i];
1176                         }
1177                         --cpuhw->n_events;
1178                         ppmu->disable_pmc(event->hw.idx - 1, cpuhw->mmcr);
1179                         if (event->hw.idx) {
1180                                 write_pmc(event->hw.idx, 0);
1181                                 event->hw.idx = 0;
1182                         }
1183                         perf_event_update_userpage(event);
1184                         break;
1185                 }
1186         }
1187         for (i = 0; i < cpuhw->n_limited; ++i)
1188                 if (event == cpuhw->limited_counter[i])
1189                         break;
1190         if (i < cpuhw->n_limited) {
1191                 while (++i < cpuhw->n_limited) {
1192                         cpuhw->limited_counter[i-1] = cpuhw->limited_counter[i];
1193                         cpuhw->limited_hwidx[i-1] = cpuhw->limited_hwidx[i];
1194                 }
1195                 --cpuhw->n_limited;
1196         }
1197         if (cpuhw->n_events == 0) {
1198                 /* disable exceptions if no events are running */
1199                 cpuhw->mmcr[0] &= ~(MMCR0_PMXE | MMCR0_FCECE);
1200         }
1201
1202         if (has_branch_stack(event))
1203                 power_pmu_bhrb_disable(event);
1204
1205         perf_pmu_enable(event->pmu);
1206         local_irq_restore(flags);
1207 }
1208
1209 /*
1210  * POWER-PMU does not support disabling individual counters, hence
1211  * program their cycle counter to their max value and ignore the interrupts.
1212  */
1213
1214 static void power_pmu_start(struct perf_event *event, int ef_flags)
1215 {
1216         unsigned long flags;
1217         s64 left;
1218         unsigned long val;
1219
1220         if (!event->hw.idx || !event->hw.sample_period)
1221                 return;
1222
1223         if (!(event->hw.state & PERF_HES_STOPPED))
1224                 return;
1225
1226         if (ef_flags & PERF_EF_RELOAD)
1227                 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1228
1229         local_irq_save(flags);
1230         perf_pmu_disable(event->pmu);
1231
1232         event->hw.state = 0;
1233         left = local64_read(&event->hw.period_left);
1234
1235         val = 0;
1236         if (left < 0x80000000L)
1237                 val = 0x80000000L - left;
1238
1239         write_pmc(event->hw.idx, val);
1240
1241         perf_event_update_userpage(event);
1242         perf_pmu_enable(event->pmu);
1243         local_irq_restore(flags);
1244 }
1245
1246 static void power_pmu_stop(struct perf_event *event, int ef_flags)
1247 {
1248         unsigned long flags;
1249
1250         if (!event->hw.idx || !event->hw.sample_period)
1251                 return;
1252
1253         if (event->hw.state & PERF_HES_STOPPED)
1254                 return;
1255
1256         local_irq_save(flags);
1257         perf_pmu_disable(event->pmu);
1258
1259         power_pmu_read(event);
1260         event->hw.state |= PERF_HES_STOPPED | PERF_HES_UPTODATE;
1261         write_pmc(event->hw.idx, 0);
1262
1263         perf_event_update_userpage(event);
1264         perf_pmu_enable(event->pmu);
1265         local_irq_restore(flags);
1266 }
1267
1268 /*
1269  * Start group events scheduling transaction
1270  * Set the flag to make pmu::enable() not perform the
1271  * schedulability test, it will be performed at commit time
1272  */
1273 void power_pmu_start_txn(struct pmu *pmu)
1274 {
1275         struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
1276
1277         perf_pmu_disable(pmu);
1278         cpuhw->group_flag |= PERF_EVENT_TXN;
1279         cpuhw->n_txn_start = cpuhw->n_events;
1280 }
1281
1282 /*
1283  * Stop group events scheduling transaction
1284  * Clear the flag and pmu::enable() will perform the
1285  * schedulability test.
1286  */
1287 void power_pmu_cancel_txn(struct pmu *pmu)
1288 {
1289         struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
1290
1291         cpuhw->group_flag &= ~PERF_EVENT_TXN;
1292         perf_pmu_enable(pmu);
1293 }
1294
1295 /*
1296  * Commit group events scheduling transaction
1297  * Perform the group schedulability test as a whole
1298  * Return 0 if success
1299  */
1300 int power_pmu_commit_txn(struct pmu *pmu)
1301 {
1302         struct cpu_hw_events *cpuhw;
1303         long i, n;
1304
1305         if (!ppmu)
1306                 return -EAGAIN;
1307         cpuhw = &__get_cpu_var(cpu_hw_events);
1308         n = cpuhw->n_events;
1309         if (check_excludes(cpuhw->event, cpuhw->flags, 0, n))
1310                 return -EAGAIN;
1311         i = power_check_constraints(cpuhw, cpuhw->events, cpuhw->flags, n);
1312         if (i < 0)
1313                 return -EAGAIN;
1314
1315         for (i = cpuhw->n_txn_start; i < n; ++i)
1316                 cpuhw->event[i]->hw.config = cpuhw->events[i];
1317
1318         cpuhw->group_flag &= ~PERF_EVENT_TXN;
1319         perf_pmu_enable(pmu);
1320         return 0;
1321 }
1322
1323 /*
1324  * Return 1 if we might be able to put event on a limited PMC,
1325  * or 0 if not.
1326  * A event can only go on a limited PMC if it counts something
1327  * that a limited PMC can count, doesn't require interrupts, and
1328  * doesn't exclude any processor mode.
1329  */
1330 static int can_go_on_limited_pmc(struct perf_event *event, u64 ev,
1331                                  unsigned int flags)
1332 {
1333         int n;
1334         u64 alt[MAX_EVENT_ALTERNATIVES];
1335
1336         if (event->attr.exclude_user
1337             || event->attr.exclude_kernel
1338             || event->attr.exclude_hv
1339             || event->attr.sample_period)
1340                 return 0;
1341
1342         if (ppmu->limited_pmc_event(ev))
1343                 return 1;
1344
1345         if (ppmu->flags & PPMU_ARCH_207S)
1346                 mtspr(SPRN_MMCR2, 0);
1347
1348         /*
1349          * The requested event_id isn't on a limited PMC already;
1350          * see if any alternative code goes on a limited PMC.
1351          */
1352         if (!ppmu->get_alternatives)
1353                 return 0;
1354
1355         flags |= PPMU_LIMITED_PMC_OK | PPMU_LIMITED_PMC_REQD;
1356         n = ppmu->get_alternatives(ev, flags, alt);
1357
1358         return n > 0;
1359 }
1360
1361 /*
1362  * Find an alternative event_id that goes on a normal PMC, if possible,
1363  * and return the event_id code, or 0 if there is no such alternative.
1364  * (Note: event_id code 0 is "don't count" on all machines.)
1365  */
1366 static u64 normal_pmc_alternative(u64 ev, unsigned long flags)
1367 {
1368         u64 alt[MAX_EVENT_ALTERNATIVES];
1369         int n;
1370
1371         flags &= ~(PPMU_LIMITED_PMC_OK | PPMU_LIMITED_PMC_REQD);
1372         n = ppmu->get_alternatives(ev, flags, alt);
1373         if (!n)
1374                 return 0;
1375         return alt[0];
1376 }
1377
1378 /* Number of perf_events counting hardware events */
1379 static atomic_t num_events;
1380 /* Used to avoid races in calling reserve/release_pmc_hardware */
1381 static DEFINE_MUTEX(pmc_reserve_mutex);
1382
1383 /*
1384  * Release the PMU if this is the last perf_event.
1385  */
1386 static void hw_perf_event_destroy(struct perf_event *event)
1387 {
1388         if (!atomic_add_unless(&num_events, -1, 1)) {
1389                 mutex_lock(&pmc_reserve_mutex);
1390                 if (atomic_dec_return(&num_events) == 0)
1391                         release_pmc_hardware();
1392                 mutex_unlock(&pmc_reserve_mutex);
1393         }
1394 }
1395
1396 /*
1397  * Translate a generic cache event_id config to a raw event_id code.
1398  */
1399 static int hw_perf_cache_event(u64 config, u64 *eventp)
1400 {
1401         unsigned long type, op, result;
1402         int ev;
1403
1404         if (!ppmu->cache_events)
1405                 return -EINVAL;
1406
1407         /* unpack config */
1408         type = config & 0xff;
1409         op = (config >> 8) & 0xff;
1410         result = (config >> 16) & 0xff;
1411
1412         if (type >= PERF_COUNT_HW_CACHE_MAX ||
1413             op >= PERF_COUNT_HW_CACHE_OP_MAX ||
1414             result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
1415                 return -EINVAL;
1416
1417         ev = (*ppmu->cache_events)[type][op][result];
1418         if (ev == 0)
1419                 return -EOPNOTSUPP;
1420         if (ev == -1)
1421                 return -EINVAL;
1422         *eventp = ev;
1423         return 0;
1424 }
1425
1426 static int power_pmu_event_init(struct perf_event *event)
1427 {
1428         u64 ev;
1429         unsigned long flags;
1430         struct perf_event *ctrs[MAX_HWEVENTS];
1431         u64 events[MAX_HWEVENTS];
1432         unsigned int cflags[MAX_HWEVENTS];
1433         int n;
1434         int err;
1435         struct cpu_hw_events *cpuhw;
1436
1437         if (!ppmu)
1438                 return -ENOENT;
1439
1440         if (has_branch_stack(event)) {
1441                 /* PMU has BHRB enabled */
1442                 if (!(ppmu->flags & PPMU_ARCH_207S))
1443                         return -EOPNOTSUPP;
1444         }
1445
1446         switch (event->attr.type) {
1447         case PERF_TYPE_HARDWARE:
1448                 ev = event->attr.config;
1449                 if (ev >= ppmu->n_generic || ppmu->generic_events[ev] == 0)
1450                         return -EOPNOTSUPP;
1451                 ev = ppmu->generic_events[ev];
1452                 break;
1453         case PERF_TYPE_HW_CACHE:
1454                 err = hw_perf_cache_event(event->attr.config, &ev);
1455                 if (err)
1456                         return err;
1457                 break;
1458         case PERF_TYPE_RAW:
1459                 ev = event->attr.config;
1460                 break;
1461         default:
1462                 return -ENOENT;
1463         }
1464
1465         event->hw.config_base = ev;
1466         event->hw.idx = 0;
1467
1468         /*
1469          * If we are not running on a hypervisor, force the
1470          * exclude_hv bit to 0 so that we don't care what
1471          * the user set it to.
1472          */
1473         if (!firmware_has_feature(FW_FEATURE_LPAR))
1474                 event->attr.exclude_hv = 0;
1475
1476         /*
1477          * If this is a per-task event, then we can use
1478          * PM_RUN_* events interchangeably with their non RUN_*
1479          * equivalents, e.g. PM_RUN_CYC instead of PM_CYC.
1480          * XXX we should check if the task is an idle task.
1481          */
1482         flags = 0;
1483         if (event->attach_state & PERF_ATTACH_TASK)
1484                 flags |= PPMU_ONLY_COUNT_RUN;
1485
1486         /*
1487          * If this machine has limited events, check whether this
1488          * event_id could go on a limited event.
1489          */
1490         if (ppmu->flags & PPMU_LIMITED_PMC5_6) {
1491                 if (can_go_on_limited_pmc(event, ev, flags)) {
1492                         flags |= PPMU_LIMITED_PMC_OK;
1493                 } else if (ppmu->limited_pmc_event(ev)) {
1494                         /*
1495                          * The requested event_id is on a limited PMC,
1496                          * but we can't use a limited PMC; see if any
1497                          * alternative goes on a normal PMC.
1498                          */
1499                         ev = normal_pmc_alternative(ev, flags);
1500                         if (!ev)
1501                                 return -EINVAL;
1502                 }
1503         }
1504
1505         /*
1506          * If this is in a group, check if it can go on with all the
1507          * other hardware events in the group.  We assume the event
1508          * hasn't been linked into its leader's sibling list at this point.
1509          */
1510         n = 0;
1511         if (event->group_leader != event) {
1512                 n = collect_events(event->group_leader, ppmu->n_counter - 1,
1513                                    ctrs, events, cflags);
1514                 if (n < 0)
1515                         return -EINVAL;
1516         }
1517         events[n] = ev;
1518         ctrs[n] = event;
1519         cflags[n] = flags;
1520         if (check_excludes(ctrs, cflags, n, 1))
1521                 return -EINVAL;
1522
1523         cpuhw = &get_cpu_var(cpu_hw_events);
1524         err = power_check_constraints(cpuhw, events, cflags, n + 1);
1525
1526         if (has_branch_stack(event)) {
1527                 cpuhw->bhrb_filter = ppmu->bhrb_filter_map(
1528                                         event->attr.branch_sample_type);
1529
1530                 if(cpuhw->bhrb_filter == -1)
1531                         return -EOPNOTSUPP;
1532         }
1533
1534         put_cpu_var(cpu_hw_events);
1535         if (err)
1536                 return -EINVAL;
1537
1538         event->hw.config = events[n];
1539         event->hw.event_base = cflags[n];
1540         event->hw.last_period = event->hw.sample_period;
1541         local64_set(&event->hw.period_left, event->hw.last_period);
1542
1543         /*
1544          * See if we need to reserve the PMU.
1545          * If no events are currently in use, then we have to take a
1546          * mutex to ensure that we don't race with another task doing
1547          * reserve_pmc_hardware or release_pmc_hardware.
1548          */
1549         err = 0;
1550         if (!atomic_inc_not_zero(&num_events)) {
1551                 mutex_lock(&pmc_reserve_mutex);
1552                 if (atomic_read(&num_events) == 0 &&
1553                     reserve_pmc_hardware(perf_event_interrupt))
1554                         err = -EBUSY;
1555                 else
1556                         atomic_inc(&num_events);
1557                 mutex_unlock(&pmc_reserve_mutex);
1558         }
1559         event->destroy = hw_perf_event_destroy;
1560
1561         return err;
1562 }
1563
1564 static int power_pmu_event_idx(struct perf_event *event)
1565 {
1566         return event->hw.idx;
1567 }
1568
1569 ssize_t power_events_sysfs_show(struct device *dev,
1570                                 struct device_attribute *attr, char *page)
1571 {
1572         struct perf_pmu_events_attr *pmu_attr;
1573
1574         pmu_attr = container_of(attr, struct perf_pmu_events_attr, attr);
1575
1576         return sprintf(page, "event=0x%02llx\n", pmu_attr->id);
1577 }
1578
1579 struct pmu power_pmu = {
1580         .pmu_enable     = power_pmu_enable,
1581         .pmu_disable    = power_pmu_disable,
1582         .event_init     = power_pmu_event_init,
1583         .add            = power_pmu_add,
1584         .del            = power_pmu_del,
1585         .start          = power_pmu_start,
1586         .stop           = power_pmu_stop,
1587         .read           = power_pmu_read,
1588         .start_txn      = power_pmu_start_txn,
1589         .cancel_txn     = power_pmu_cancel_txn,
1590         .commit_txn     = power_pmu_commit_txn,
1591         .event_idx      = power_pmu_event_idx,
1592         .flush_branch_stack = power_pmu_flush_branch_stack,
1593 };
1594
1595 /*
1596  * A counter has overflowed; update its count and record
1597  * things if requested.  Note that interrupts are hard-disabled
1598  * here so there is no possibility of being interrupted.
1599  */
1600 static void record_and_restart(struct perf_event *event, unsigned long val,
1601                                struct pt_regs *regs)
1602 {
1603         u64 period = event->hw.sample_period;
1604         s64 prev, delta, left;
1605         int record = 0;
1606
1607         if (event->hw.state & PERF_HES_STOPPED) {
1608                 write_pmc(event->hw.idx, 0);
1609                 return;
1610         }
1611
1612         /* we don't have to worry about interrupts here */
1613         prev = local64_read(&event->hw.prev_count);
1614         delta = check_and_compute_delta(prev, val);
1615         local64_add(delta, &event->count);
1616
1617         /*
1618          * See if the total period for this event has expired,
1619          * and update for the next period.
1620          */
1621         val = 0;
1622         left = local64_read(&event->hw.period_left) - delta;
1623         if (delta == 0)
1624                 left++;
1625         if (period) {
1626                 if (left <= 0) {
1627                         left += period;
1628                         if (left <= 0)
1629                                 left = period;
1630                         record = siar_valid(regs);
1631                         event->hw.last_period = event->hw.sample_period;
1632                 }
1633                 if (left < 0x80000000LL)
1634                         val = 0x80000000LL - left;
1635         }
1636
1637         write_pmc(event->hw.idx, val);
1638         local64_set(&event->hw.prev_count, val);
1639         local64_set(&event->hw.period_left, left);
1640         perf_event_update_userpage(event);
1641
1642         /*
1643          * Finally record data if requested.
1644          */
1645         if (record) {
1646                 struct perf_sample_data data;
1647
1648                 perf_sample_data_init(&data, ~0ULL, event->hw.last_period);
1649
1650                 if (event->attr.sample_type & PERF_SAMPLE_ADDR)
1651                         perf_get_data_addr(regs, &data.addr);
1652
1653                 if (event->attr.sample_type & PERF_SAMPLE_BRANCH_STACK) {
1654                         struct cpu_hw_events *cpuhw;
1655                         cpuhw = &__get_cpu_var(cpu_hw_events);
1656                         power_pmu_bhrb_read(cpuhw);
1657                         data.br_stack = &cpuhw->bhrb_stack;
1658                 }
1659
1660                 if (perf_event_overflow(event, &data, regs))
1661                         power_pmu_stop(event, 0);
1662         }
1663 }
1664
1665 /*
1666  * Called from generic code to get the misc flags (i.e. processor mode)
1667  * for an event_id.
1668  */
1669 unsigned long perf_misc_flags(struct pt_regs *regs)
1670 {
1671         u32 flags = perf_get_misc_flags(regs);
1672
1673         if (flags)
1674                 return flags;
1675         return user_mode(regs) ? PERF_RECORD_MISC_USER :
1676                 PERF_RECORD_MISC_KERNEL;
1677 }
1678
1679 /*
1680  * Called from generic code to get the instruction pointer
1681  * for an event_id.
1682  */
1683 unsigned long perf_instruction_pointer(struct pt_regs *regs)
1684 {
1685         bool use_siar = regs_use_siar(regs);
1686
1687         if (use_siar && siar_valid(regs))
1688                 return mfspr(SPRN_SIAR) + perf_ip_adjust(regs);
1689         else if (use_siar)
1690                 return 0;               // no valid instruction pointer
1691         else
1692                 return regs->nip;
1693 }
1694
1695 static bool pmc_overflow_power7(unsigned long val)
1696 {
1697         /*
1698          * Events on POWER7 can roll back if a speculative event doesn't
1699          * eventually complete. Unfortunately in some rare cases they will
1700          * raise a performance monitor exception. We need to catch this to
1701          * ensure we reset the PMC. In all cases the PMC will be 256 or less
1702          * cycles from overflow.
1703          *
1704          * We only do this if the first pass fails to find any overflowing
1705          * PMCs because a user might set a period of less than 256 and we
1706          * don't want to mistakenly reset them.
1707          */
1708         if ((0x80000000 - val) <= 256)
1709                 return true;
1710
1711         return false;
1712 }
1713
1714 static bool pmc_overflow(unsigned long val)
1715 {
1716         if ((int)val < 0)
1717                 return true;
1718
1719         return false;
1720 }
1721
1722 /*
1723  * Performance monitor interrupt stuff
1724  */
1725 static void perf_event_interrupt(struct pt_regs *regs)
1726 {
1727         int i, j;
1728         struct cpu_hw_events *cpuhw = &__get_cpu_var(cpu_hw_events);
1729         struct perf_event *event;
1730         unsigned long val[8];
1731         int found, active;
1732         int nmi;
1733
1734         if (cpuhw->n_limited)
1735                 freeze_limited_counters(cpuhw, mfspr(SPRN_PMC5),
1736                                         mfspr(SPRN_PMC6));
1737
1738         perf_read_regs(regs);
1739
1740         nmi = perf_intr_is_nmi(regs);
1741         if (nmi)
1742                 nmi_enter();
1743         else
1744                 irq_enter();
1745
1746         /* Read all the PMCs since we'll need them a bunch of times */
1747         for (i = 0; i < ppmu->n_counter; ++i)
1748                 val[i] = read_pmc(i + 1);
1749
1750         /* Try to find what caused the IRQ */
1751         found = 0;
1752         for (i = 0; i < ppmu->n_counter; ++i) {
1753                 if (!pmc_overflow(val[i]))
1754                         continue;
1755                 if (is_limited_pmc(i + 1))
1756                         continue; /* these won't generate IRQs */
1757                 /*
1758                  * We've found one that's overflowed.  For active
1759                  * counters we need to log this.  For inactive
1760                  * counters, we need to reset it anyway
1761                  */
1762                 found = 1;
1763                 active = 0;
1764                 for (j = 0; j < cpuhw->n_events; ++j) {
1765                         event = cpuhw->event[j];
1766                         if (event->hw.idx == (i + 1)) {
1767                                 active = 1;
1768                                 record_and_restart(event, val[i], regs);
1769                                 break;
1770                         }
1771                 }
1772                 if (!active)
1773                         /* reset non active counters that have overflowed */
1774                         write_pmc(i + 1, 0);
1775         }
1776         if (!found && pvr_version_is(PVR_POWER7)) {
1777                 /* check active counters for special buggy p7 overflow */
1778                 for (i = 0; i < cpuhw->n_events; ++i) {
1779                         event = cpuhw->event[i];
1780                         if (!event->hw.idx || is_limited_pmc(event->hw.idx))
1781                                 continue;
1782                         if (pmc_overflow_power7(val[event->hw.idx - 1])) {
1783                                 /* event has overflowed in a buggy way*/
1784                                 found = 1;
1785                                 record_and_restart(event,
1786                                                    val[event->hw.idx - 1],
1787                                                    regs);
1788                         }
1789                 }
1790         }
1791         if (!found && !nmi && printk_ratelimit())
1792                 printk(KERN_WARNING "Can't find PMC that caused IRQ\n");
1793
1794         /*
1795          * Reset MMCR0 to its normal value.  This will set PMXE and
1796          * clear FC (freeze counters) and PMAO (perf mon alert occurred)
1797          * and thus allow interrupts to occur again.
1798          * XXX might want to use MSR.PM to keep the events frozen until
1799          * we get back out of this interrupt.
1800          */
1801         write_mmcr0(cpuhw, cpuhw->mmcr[0]);
1802
1803         if (nmi)
1804                 nmi_exit();
1805         else
1806                 irq_exit();
1807 }
1808
1809 static void power_pmu_setup(int cpu)
1810 {
1811         struct cpu_hw_events *cpuhw = &per_cpu(cpu_hw_events, cpu);
1812
1813         if (!ppmu)
1814                 return;
1815         memset(cpuhw, 0, sizeof(*cpuhw));
1816         cpuhw->mmcr[0] = MMCR0_FC;
1817 }
1818
1819 static int __cpuinit
1820 power_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1821 {
1822         unsigned int cpu = (long)hcpu;
1823
1824         switch (action & ~CPU_TASKS_FROZEN) {
1825         case CPU_UP_PREPARE:
1826                 power_pmu_setup(cpu);
1827                 break;
1828
1829         default:
1830                 break;
1831         }
1832
1833         return NOTIFY_OK;
1834 }
1835
1836 int __cpuinit register_power_pmu(struct power_pmu *pmu)
1837 {
1838         if (ppmu)
1839                 return -EBUSY;          /* something's already registered */
1840
1841         ppmu = pmu;
1842         pr_info("%s performance monitor hardware support registered\n",
1843                 pmu->name);
1844
1845         power_pmu.attr_groups = ppmu->attr_groups;
1846
1847 #ifdef MSR_HV
1848         /*
1849          * Use FCHV to ignore kernel events if MSR.HV is set.
1850          */
1851         if (mfmsr() & MSR_HV)
1852                 freeze_events_kernel = MMCR0_FCHV;
1853 #endif /* CONFIG_PPC64 */
1854
1855         perf_pmu_register(&power_pmu, "cpu", PERF_TYPE_RAW);
1856         perf_cpu_notifier(power_pmu_notifier);
1857
1858         return 0;
1859 }