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