GNU Linux-libre 5.15.72-gnu
[releases.git] / arch / powerpc / perf / core-book3s.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Performance event support - powerpc architecture code
4  *
5  * Copyright 2008-2009 Paul Mackerras, IBM Corporation.
6  */
7 #include <linux/kernel.h>
8 #include <linux/sched.h>
9 #include <linux/sched/clock.h>
10 #include <linux/perf_event.h>
11 #include <linux/percpu.h>
12 #include <linux/hardirq.h>
13 #include <linux/uaccess.h>
14 #include <asm/reg.h>
15 #include <asm/pmc.h>
16 #include <asm/machdep.h>
17 #include <asm/firmware.h>
18 #include <asm/ptrace.h>
19 #include <asm/code-patching.h>
20 #include <asm/interrupt.h>
21
22 #ifdef CONFIG_PPC64
23 #include "internal.h"
24 #endif
25
26 #define BHRB_MAX_ENTRIES        32
27 #define BHRB_TARGET             0x0000000000000002
28 #define BHRB_PREDICTION         0x0000000000000001
29 #define BHRB_EA                 0xFFFFFFFFFFFFFFFCUL
30
31 struct cpu_hw_events {
32         int n_events;
33         int n_percpu;
34         int disabled;
35         int n_added;
36         int n_limited;
37         u8  pmcs_enabled;
38         struct perf_event *event[MAX_HWEVENTS];
39         u64 events[MAX_HWEVENTS];
40         unsigned int flags[MAX_HWEVENTS];
41         struct mmcr_regs mmcr;
42         struct perf_event *limited_counter[MAX_LIMITED_HWCOUNTERS];
43         u8  limited_hwidx[MAX_LIMITED_HWCOUNTERS];
44         u64 alternatives[MAX_HWEVENTS][MAX_EVENT_ALTERNATIVES];
45         unsigned long amasks[MAX_HWEVENTS][MAX_EVENT_ALTERNATIVES];
46         unsigned long avalues[MAX_HWEVENTS][MAX_EVENT_ALTERNATIVES];
47
48         unsigned int txn_flags;
49         int n_txn_start;
50
51         /* BHRB bits */
52         u64                             bhrb_filter;    /* BHRB HW branch filter */
53         unsigned int                    bhrb_users;
54         void                            *bhrb_context;
55         struct  perf_branch_stack       bhrb_stack;
56         struct  perf_branch_entry       bhrb_entries[BHRB_MAX_ENTRIES];
57         u64                             ic_init;
58
59         /* Store the PMC values */
60         unsigned long pmcs[MAX_HWEVENTS];
61 };
62
63 static DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events);
64
65 static struct power_pmu *ppmu;
66
67 /*
68  * Normally, to ignore kernel events we set the FCS (freeze counters
69  * in supervisor mode) bit in MMCR0, but if the kernel runs with the
70  * hypervisor bit set in the MSR, or if we are running on a processor
71  * where the hypervisor bit is forced to 1 (as on Apple G5 processors),
72  * then we need to use the FCHV bit to ignore kernel events.
73  */
74 static unsigned int freeze_events_kernel = MMCR0_FCS;
75
76 /*
77  * 32-bit doesn't have MMCRA but does have an MMCR2,
78  * and a few other names are different.
79  * Also 32-bit doesn't have MMCR3, SIER2 and SIER3.
80  * Define them as zero knowing that any code path accessing
81  * these registers (via mtspr/mfspr) are done under ppmu flag
82  * check for PPMU_ARCH_31 and we will not enter that code path
83  * for 32-bit.
84  */
85 #ifdef CONFIG_PPC32
86
87 #define MMCR0_FCHV              0
88 #define MMCR0_PMCjCE            MMCR0_PMCnCE
89 #define MMCR0_FC56              0
90 #define MMCR0_PMAO              0
91 #define MMCR0_EBE               0
92 #define MMCR0_BHRBA             0
93 #define MMCR0_PMCC              0
94 #define MMCR0_PMCC_U6           0
95
96 #define SPRN_MMCRA              SPRN_MMCR2
97 #define SPRN_MMCR3              0
98 #define SPRN_SIER2              0
99 #define SPRN_SIER3              0
100 #define MMCRA_SAMPLE_ENABLE     0
101 #define MMCRA_BHRB_DISABLE     0
102 #define MMCR0_PMCCEXT           0
103
104 static inline unsigned long perf_ip_adjust(struct pt_regs *regs)
105 {
106         return 0;
107 }
108 static inline void perf_get_data_addr(struct perf_event *event, struct pt_regs *regs, u64 *addrp) { }
109 static inline u32 perf_get_misc_flags(struct pt_regs *regs)
110 {
111         return 0;
112 }
113 static inline void perf_read_regs(struct pt_regs *regs)
114 {
115         regs->result = 0;
116 }
117
118 static inline int siar_valid(struct pt_regs *regs)
119 {
120         return 1;
121 }
122
123 static bool is_ebb_event(struct perf_event *event) { return false; }
124 static int ebb_event_check(struct perf_event *event) { return 0; }
125 static void ebb_event_add(struct perf_event *event) { }
126 static void ebb_switch_out(unsigned long mmcr0) { }
127 static unsigned long ebb_switch_in(bool ebb, struct cpu_hw_events *cpuhw)
128 {
129         return cpuhw->mmcr.mmcr0;
130 }
131
132 static inline void power_pmu_bhrb_enable(struct perf_event *event) {}
133 static inline void power_pmu_bhrb_disable(struct perf_event *event) {}
134 static void power_pmu_sched_task(struct perf_event_context *ctx, bool sched_in) {}
135 static inline void power_pmu_bhrb_read(struct perf_event *event, struct cpu_hw_events *cpuhw) {}
136 static void pmao_restore_workaround(bool ebb) { }
137 #endif /* CONFIG_PPC32 */
138
139 bool is_sier_available(void)
140 {
141         if (!ppmu)
142                 return false;
143
144         if (ppmu->flags & PPMU_HAS_SIER)
145                 return true;
146
147         return false;
148 }
149
150 /*
151  * Return PMC value corresponding to the
152  * index passed.
153  */
154 unsigned long get_pmcs_ext_regs(int idx)
155 {
156         struct cpu_hw_events *cpuhw = this_cpu_ptr(&cpu_hw_events);
157
158         return cpuhw->pmcs[idx];
159 }
160
161 static bool regs_use_siar(struct pt_regs *regs)
162 {
163         /*
164          * When we take a performance monitor exception the regs are setup
165          * using perf_read_regs() which overloads some fields, in particular
166          * regs->result to tell us whether to use SIAR.
167          *
168          * However if the regs are from another exception, eg. a syscall, then
169          * they have not been setup using perf_read_regs() and so regs->result
170          * is something random.
171          */
172         return ((TRAP(regs) == INTERRUPT_PERFMON) && regs->result);
173 }
174
175 /*
176  * Things that are specific to 64-bit implementations.
177  */
178 #ifdef CONFIG_PPC64
179
180 static inline unsigned long perf_ip_adjust(struct pt_regs *regs)
181 {
182         unsigned long mmcra = regs->dsisr;
183
184         if ((ppmu->flags & PPMU_HAS_SSLOT) && (mmcra & MMCRA_SAMPLE_ENABLE)) {
185                 unsigned long slot = (mmcra & MMCRA_SLOT) >> MMCRA_SLOT_SHIFT;
186                 if (slot > 1)
187                         return 4 * (slot - 1);
188         }
189
190         return 0;
191 }
192
193 /*
194  * The user wants a data address recorded.
195  * If we're not doing instruction sampling, give them the SDAR
196  * (sampled data address).  If we are doing instruction sampling, then
197  * only give them the SDAR if it corresponds to the instruction
198  * pointed to by SIAR; this is indicated by the [POWER6_]MMCRA_SDSYNC, the
199  * [POWER7P_]MMCRA_SDAR_VALID bit in MMCRA, or the SDAR_VALID bit in SIER.
200  */
201 static inline void perf_get_data_addr(struct perf_event *event, struct pt_regs *regs, u64 *addrp)
202 {
203         unsigned long mmcra = regs->dsisr;
204         bool sdar_valid;
205
206         if (ppmu->flags & PPMU_HAS_SIER)
207                 sdar_valid = regs->dar & SIER_SDAR_VALID;
208         else {
209                 unsigned long sdsync;
210
211                 if (ppmu->flags & PPMU_SIAR_VALID)
212                         sdsync = POWER7P_MMCRA_SDAR_VALID;
213                 else if (ppmu->flags & PPMU_ALT_SIPR)
214                         sdsync = POWER6_MMCRA_SDSYNC;
215                 else if (ppmu->flags & PPMU_NO_SIAR)
216                         sdsync = MMCRA_SAMPLE_ENABLE;
217                 else
218                         sdsync = MMCRA_SDSYNC;
219
220                 sdar_valid = mmcra & sdsync;
221         }
222
223         if (!(mmcra & MMCRA_SAMPLE_ENABLE) || sdar_valid)
224                 *addrp = mfspr(SPRN_SDAR);
225
226         if (is_kernel_addr(mfspr(SPRN_SDAR)) && event->attr.exclude_kernel)
227                 *addrp = 0;
228 }
229
230 static bool regs_sihv(struct pt_regs *regs)
231 {
232         unsigned long sihv = MMCRA_SIHV;
233
234         if (ppmu->flags & PPMU_HAS_SIER)
235                 return !!(regs->dar & SIER_SIHV);
236
237         if (ppmu->flags & PPMU_ALT_SIPR)
238                 sihv = POWER6_MMCRA_SIHV;
239
240         return !!(regs->dsisr & sihv);
241 }
242
243 static bool regs_sipr(struct pt_regs *regs)
244 {
245         unsigned long sipr = MMCRA_SIPR;
246
247         if (ppmu->flags & PPMU_HAS_SIER)
248                 return !!(regs->dar & SIER_SIPR);
249
250         if (ppmu->flags & PPMU_ALT_SIPR)
251                 sipr = POWER6_MMCRA_SIPR;
252
253         return !!(regs->dsisr & sipr);
254 }
255
256 static inline u32 perf_flags_from_msr(struct pt_regs *regs)
257 {
258         if (regs->msr & MSR_PR)
259                 return PERF_RECORD_MISC_USER;
260         if ((regs->msr & MSR_HV) && freeze_events_kernel != MMCR0_FCHV)
261                 return PERF_RECORD_MISC_HYPERVISOR;
262         return PERF_RECORD_MISC_KERNEL;
263 }
264
265 static inline u32 perf_get_misc_flags(struct pt_regs *regs)
266 {
267         bool use_siar = regs_use_siar(regs);
268         unsigned long mmcra = regs->dsisr;
269         int marked = mmcra & MMCRA_SAMPLE_ENABLE;
270
271         if (!use_siar)
272                 return perf_flags_from_msr(regs);
273
274         /*
275          * Check the address in SIAR to identify the
276          * privilege levels since the SIER[MSR_HV, MSR_PR]
277          * bits are not set for marked events in power10
278          * DD1.
279          */
280         if (marked && (ppmu->flags & PPMU_P10_DD1)) {
281                 unsigned long siar = mfspr(SPRN_SIAR);
282                 if (siar) {
283                         if (is_kernel_addr(siar))
284                                 return PERF_RECORD_MISC_KERNEL;
285                         return PERF_RECORD_MISC_USER;
286                 } else {
287                         if (is_kernel_addr(regs->nip))
288                                 return PERF_RECORD_MISC_KERNEL;
289                         return PERF_RECORD_MISC_USER;
290                 }
291         }
292
293         /*
294          * If we don't have flags in MMCRA, rather than using
295          * the MSR, we intuit the flags from the address in
296          * SIAR which should give slightly more reliable
297          * results
298          */
299         if (ppmu->flags & PPMU_NO_SIPR) {
300                 unsigned long siar = mfspr(SPRN_SIAR);
301                 if (is_kernel_addr(siar))
302                         return PERF_RECORD_MISC_KERNEL;
303                 return PERF_RECORD_MISC_USER;
304         }
305
306         /* PR has priority over HV, so order below is important */
307         if (regs_sipr(regs))
308                 return PERF_RECORD_MISC_USER;
309
310         if (regs_sihv(regs) && (freeze_events_kernel != MMCR0_FCHV))
311                 return PERF_RECORD_MISC_HYPERVISOR;
312
313         return PERF_RECORD_MISC_KERNEL;
314 }
315
316 /*
317  * Overload regs->dsisr to store MMCRA so we only need to read it once
318  * on each interrupt.
319  * Overload regs->dar to store SIER if we have it.
320  * Overload regs->result to specify whether we should use the MSR (result
321  * is zero) or the SIAR (result is non zero).
322  */
323 static inline void perf_read_regs(struct pt_regs *regs)
324 {
325         unsigned long mmcra = mfspr(SPRN_MMCRA);
326         int marked = mmcra & MMCRA_SAMPLE_ENABLE;
327         int use_siar;
328
329         regs->dsisr = mmcra;
330
331         if (ppmu->flags & PPMU_HAS_SIER)
332                 regs->dar = mfspr(SPRN_SIER);
333
334         /*
335          * If this isn't a PMU exception (eg a software event) the SIAR is
336          * not valid. Use pt_regs.
337          *
338          * If it is a marked event use the SIAR.
339          *
340          * If the PMU doesn't update the SIAR for non marked events use
341          * pt_regs.
342          *
343          * If regs is a kernel interrupt, always use SIAR. Some PMUs have an
344          * issue with regs_sipr not being in synch with SIAR in interrupt entry
345          * and return sequences, which can result in regs_sipr being true for
346          * kernel interrupts and SIAR, which has the effect of causing samples
347          * to pile up at mtmsrd MSR[EE] 0->1 or pending irq replay around
348          * interrupt entry/exit.
349          *
350          * If the PMU has HV/PR flags then check to see if they
351          * place the exception in userspace. If so, use pt_regs. In
352          * continuous sampling mode the SIAR and the PMU exception are
353          * not synchronised, so they may be many instructions apart.
354          * This can result in confusing backtraces. We still want
355          * hypervisor samples as well as samples in the kernel with
356          * interrupts off hence the userspace check.
357          */
358         if (TRAP(regs) != INTERRUPT_PERFMON)
359                 use_siar = 0;
360         else if ((ppmu->flags & PPMU_NO_SIAR))
361                 use_siar = 0;
362         else if (marked)
363                 use_siar = 1;
364         else if ((ppmu->flags & PPMU_NO_CONT_SAMPLING))
365                 use_siar = 0;
366         else if (!user_mode(regs))
367                 use_siar = 1;
368         else if (!(ppmu->flags & PPMU_NO_SIPR) && regs_sipr(regs))
369                 use_siar = 0;
370         else
371                 use_siar = 1;
372
373         regs->result = use_siar;
374 }
375
376 /*
377  * On processors like P7+ that have the SIAR-Valid bit, marked instructions
378  * must be sampled only if the SIAR-valid bit is set.
379  *
380  * For unmarked instructions and for processors that don't have the SIAR-Valid
381  * bit, assume that SIAR is valid.
382  */
383 static inline int siar_valid(struct pt_regs *regs)
384 {
385         unsigned long mmcra = regs->dsisr;
386         int marked = mmcra & MMCRA_SAMPLE_ENABLE;
387
388         if (marked) {
389                 /*
390                  * SIER[SIAR_VALID] is not set for some
391                  * marked events on power10 DD1, so drop
392                  * the check for SIER[SIAR_VALID] and return true.
393                  */
394                 if (ppmu->flags & PPMU_P10_DD1)
395                         return 0x1;
396                 else if (ppmu->flags & PPMU_HAS_SIER)
397                         return regs->dar & SIER_SIAR_VALID;
398
399                 if (ppmu->flags & PPMU_SIAR_VALID)
400                         return mmcra & POWER7P_MMCRA_SIAR_VALID;
401         }
402
403         return 1;
404 }
405
406
407 /* Reset all possible BHRB entries */
408 static void power_pmu_bhrb_reset(void)
409 {
410         asm volatile(PPC_CLRBHRB);
411 }
412
413 static void power_pmu_bhrb_enable(struct perf_event *event)
414 {
415         struct cpu_hw_events *cpuhw = this_cpu_ptr(&cpu_hw_events);
416
417         if (!ppmu->bhrb_nr)
418                 return;
419
420         /* Clear BHRB if we changed task context to avoid data leaks */
421         if (event->ctx->task && cpuhw->bhrb_context != event->ctx) {
422                 power_pmu_bhrb_reset();
423                 cpuhw->bhrb_context = event->ctx;
424         }
425         cpuhw->bhrb_users++;
426         perf_sched_cb_inc(event->ctx->pmu);
427 }
428
429 static void power_pmu_bhrb_disable(struct perf_event *event)
430 {
431         struct cpu_hw_events *cpuhw = this_cpu_ptr(&cpu_hw_events);
432
433         if (!ppmu->bhrb_nr)
434                 return;
435
436         WARN_ON_ONCE(!cpuhw->bhrb_users);
437         cpuhw->bhrb_users--;
438         perf_sched_cb_dec(event->ctx->pmu);
439
440         if (!cpuhw->disabled && !cpuhw->bhrb_users) {
441                 /* BHRB cannot be turned off when other
442                  * events are active on the PMU.
443                  */
444
445                 /* avoid stale pointer */
446                 cpuhw->bhrb_context = NULL;
447         }
448 }
449
450 /* Called from ctxsw to prevent one process's branch entries to
451  * mingle with the other process's entries during context switch.
452  */
453 static void power_pmu_sched_task(struct perf_event_context *ctx, bool sched_in)
454 {
455         if (!ppmu->bhrb_nr)
456                 return;
457
458         if (sched_in)
459                 power_pmu_bhrb_reset();
460 }
461 /* Calculate the to address for a branch */
462 static __u64 power_pmu_bhrb_to(u64 addr)
463 {
464         unsigned int instr;
465         __u64 target;
466
467         if (is_kernel_addr(addr)) {
468                 if (copy_from_kernel_nofault(&instr, (void *)addr,
469                                 sizeof(instr)))
470                         return 0;
471
472                 return branch_target(&instr);
473         }
474
475         /* Userspace: need copy instruction here then translate it */
476         if (copy_from_user_nofault(&instr, (unsigned int __user *)addr,
477                         sizeof(instr)))
478                 return 0;
479
480         target = branch_target(&instr);
481         if ((!target) || (instr & BRANCH_ABSOLUTE))
482                 return target;
483
484         /* Translate relative branch target from kernel to user address */
485         return target - (unsigned long)&instr + addr;
486 }
487
488 /* Processing BHRB entries */
489 static void power_pmu_bhrb_read(struct perf_event *event, struct cpu_hw_events *cpuhw)
490 {
491         u64 val;
492         u64 addr;
493         int r_index, u_index, pred;
494
495         r_index = 0;
496         u_index = 0;
497         while (r_index < ppmu->bhrb_nr) {
498                 /* Assembly read function */
499                 val = read_bhrb(r_index++);
500                 if (!val)
501                         /* Terminal marker: End of valid BHRB entries */
502                         break;
503                 else {
504                         addr = val & BHRB_EA;
505                         pred = val & BHRB_PREDICTION;
506
507                         if (!addr)
508                                 /* invalid entry */
509                                 continue;
510
511                         /*
512                          * BHRB rolling buffer could very much contain the kernel
513                          * addresses at this point. Check the privileges before
514                          * exporting it to userspace (avoid exposure of regions
515                          * where we could have speculative execution)
516                          * Incase of ISA v3.1, BHRB will capture only user-space
517                          * addresses, hence include a check before filtering code
518                          */
519                         if (!(ppmu->flags & PPMU_ARCH_31) &&
520                             is_kernel_addr(addr) && event->attr.exclude_kernel)
521                                 continue;
522
523                         /* Branches are read most recent first (ie. mfbhrb 0 is
524                          * the most recent branch).
525                          * There are two types of valid entries:
526                          * 1) a target entry which is the to address of a
527                          *    computed goto like a blr,bctr,btar.  The next
528                          *    entry read from the bhrb will be branch
529                          *    corresponding to this target (ie. the actual
530                          *    blr/bctr/btar instruction).
531                          * 2) a from address which is an actual branch.  If a
532                          *    target entry proceeds this, then this is the
533                          *    matching branch for that target.  If this is not
534                          *    following a target entry, then this is a branch
535                          *    where the target is given as an immediate field
536                          *    in the instruction (ie. an i or b form branch).
537                          *    In this case we need to read the instruction from
538                          *    memory to determine the target/to address.
539                          */
540
541                         if (val & BHRB_TARGET) {
542                                 /* Target branches use two entries
543                                  * (ie. computed gotos/XL form)
544                                  */
545                                 cpuhw->bhrb_entries[u_index].to = addr;
546                                 cpuhw->bhrb_entries[u_index].mispred = pred;
547                                 cpuhw->bhrb_entries[u_index].predicted = ~pred;
548
549                                 /* Get from address in next entry */
550                                 val = read_bhrb(r_index++);
551                                 addr = val & BHRB_EA;
552                                 if (val & BHRB_TARGET) {
553                                         /* Shouldn't have two targets in a
554                                            row.. Reset index and try again */
555                                         r_index--;
556                                         addr = 0;
557                                 }
558                                 cpuhw->bhrb_entries[u_index].from = addr;
559                         } else {
560                                 /* Branches to immediate field 
561                                    (ie I or B form) */
562                                 cpuhw->bhrb_entries[u_index].from = addr;
563                                 cpuhw->bhrb_entries[u_index].to =
564                                         power_pmu_bhrb_to(addr);
565                                 cpuhw->bhrb_entries[u_index].mispred = pred;
566                                 cpuhw->bhrb_entries[u_index].predicted = ~pred;
567                         }
568                         u_index++;
569
570                 }
571         }
572         cpuhw->bhrb_stack.nr = u_index;
573         cpuhw->bhrb_stack.hw_idx = -1ULL;
574         return;
575 }
576
577 static bool is_ebb_event(struct perf_event *event)
578 {
579         /*
580          * This could be a per-PMU callback, but we'd rather avoid the cost. We
581          * check that the PMU supports EBB, meaning those that don't can still
582          * use bit 63 of the event code for something else if they wish.
583          */
584         return (ppmu->flags & PPMU_ARCH_207S) &&
585                ((event->attr.config >> PERF_EVENT_CONFIG_EBB_SHIFT) & 1);
586 }
587
588 static int ebb_event_check(struct perf_event *event)
589 {
590         struct perf_event *leader = event->group_leader;
591
592         /* Event and group leader must agree on EBB */
593         if (is_ebb_event(leader) != is_ebb_event(event))
594                 return -EINVAL;
595
596         if (is_ebb_event(event)) {
597                 if (!(event->attach_state & PERF_ATTACH_TASK))
598                         return -EINVAL;
599
600                 if (!leader->attr.pinned || !leader->attr.exclusive)
601                         return -EINVAL;
602
603                 if (event->attr.freq ||
604                     event->attr.inherit ||
605                     event->attr.sample_type ||
606                     event->attr.sample_period ||
607                     event->attr.enable_on_exec)
608                         return -EINVAL;
609         }
610
611         return 0;
612 }
613
614 static void ebb_event_add(struct perf_event *event)
615 {
616         if (!is_ebb_event(event) || current->thread.used_ebb)
617                 return;
618
619         /*
620          * IFF this is the first time we've added an EBB event, set
621          * PMXE in the user MMCR0 so we can detect when it's cleared by
622          * userspace. We need this so that we can context switch while
623          * userspace is in the EBB handler (where PMXE is 0).
624          */
625         current->thread.used_ebb = 1;
626         current->thread.mmcr0 |= MMCR0_PMXE;
627 }
628
629 static void ebb_switch_out(unsigned long mmcr0)
630 {
631         if (!(mmcr0 & MMCR0_EBE))
632                 return;
633
634         current->thread.siar  = mfspr(SPRN_SIAR);
635         current->thread.sier  = mfspr(SPRN_SIER);
636         current->thread.sdar  = mfspr(SPRN_SDAR);
637         current->thread.mmcr0 = mmcr0 & MMCR0_USER_MASK;
638         current->thread.mmcr2 = mfspr(SPRN_MMCR2) & MMCR2_USER_MASK;
639         if (ppmu->flags & PPMU_ARCH_31) {
640                 current->thread.mmcr3 = mfspr(SPRN_MMCR3);
641                 current->thread.sier2 = mfspr(SPRN_SIER2);
642                 current->thread.sier3 = mfspr(SPRN_SIER3);
643         }
644 }
645
646 static unsigned long ebb_switch_in(bool ebb, struct cpu_hw_events *cpuhw)
647 {
648         unsigned long mmcr0 = cpuhw->mmcr.mmcr0;
649
650         if (!ebb)
651                 goto out;
652
653         /* Enable EBB and read/write to all 6 PMCs and BHRB for userspace */
654         mmcr0 |= MMCR0_EBE | MMCR0_BHRBA | MMCR0_PMCC_U6;
655
656         /*
657          * Add any bits from the user MMCR0, FC or PMAO. This is compatible
658          * with pmao_restore_workaround() because we may add PMAO but we never
659          * clear it here.
660          */
661         mmcr0 |= current->thread.mmcr0;
662
663         /*
664          * Be careful not to set PMXE if userspace had it cleared. This is also
665          * compatible with pmao_restore_workaround() because it has already
666          * cleared PMXE and we leave PMAO alone.
667          */
668         if (!(current->thread.mmcr0 & MMCR0_PMXE))
669                 mmcr0 &= ~MMCR0_PMXE;
670
671         mtspr(SPRN_SIAR, current->thread.siar);
672         mtspr(SPRN_SIER, current->thread.sier);
673         mtspr(SPRN_SDAR, current->thread.sdar);
674
675         /*
676          * Merge the kernel & user values of MMCR2. The semantics we implement
677          * are that the user MMCR2 can set bits, ie. cause counters to freeze,
678          * but not clear bits. If a task wants to be able to clear bits, ie.
679          * unfreeze counters, it should not set exclude_xxx in its events and
680          * instead manage the MMCR2 entirely by itself.
681          */
682         mtspr(SPRN_MMCR2, cpuhw->mmcr.mmcr2 | current->thread.mmcr2);
683
684         if (ppmu->flags & PPMU_ARCH_31) {
685                 mtspr(SPRN_MMCR3, current->thread.mmcr3);
686                 mtspr(SPRN_SIER2, current->thread.sier2);
687                 mtspr(SPRN_SIER3, current->thread.sier3);
688         }
689 out:
690         return mmcr0;
691 }
692
693 static void pmao_restore_workaround(bool ebb)
694 {
695         unsigned pmcs[6];
696
697         if (!cpu_has_feature(CPU_FTR_PMAO_BUG))
698                 return;
699
700         /*
701          * On POWER8E there is a hardware defect which affects the PMU context
702          * switch logic, ie. power_pmu_disable/enable().
703          *
704          * When a counter overflows PMXE is cleared and FC/PMAO is set in MMCR0
705          * by the hardware. Sometime later the actual PMU exception is
706          * delivered.
707          *
708          * If we context switch, or simply disable/enable, the PMU prior to the
709          * exception arriving, the exception will be lost when we clear PMAO.
710          *
711          * When we reenable the PMU, we will write the saved MMCR0 with PMAO
712          * set, and this _should_ generate an exception. However because of the
713          * defect no exception is generated when we write PMAO, and we get
714          * stuck with no counters counting but no exception delivered.
715          *
716          * The workaround is to detect this case and tweak the hardware to
717          * create another pending PMU exception.
718          *
719          * We do that by setting up PMC6 (cycles) for an imminent overflow and
720          * enabling the PMU. That causes a new exception to be generated in the
721          * chip, but we don't take it yet because we have interrupts hard
722          * disabled. We then write back the PMU state as we want it to be seen
723          * by the exception handler. When we reenable interrupts the exception
724          * handler will be called and see the correct state.
725          *
726          * The logic is the same for EBB, except that the exception is gated by
727          * us having interrupts hard disabled as well as the fact that we are
728          * not in userspace. The exception is finally delivered when we return
729          * to userspace.
730          */
731
732         /* Only if PMAO is set and PMAO_SYNC is clear */
733         if ((current->thread.mmcr0 & (MMCR0_PMAO | MMCR0_PMAO_SYNC)) != MMCR0_PMAO)
734                 return;
735
736         /* If we're doing EBB, only if BESCR[GE] is set */
737         if (ebb && !(current->thread.bescr & BESCR_GE))
738                 return;
739
740         /*
741          * We are already soft-disabled in power_pmu_enable(). We need to hard
742          * disable to actually prevent the PMU exception from firing.
743          */
744         hard_irq_disable();
745
746         /*
747          * This is a bit gross, but we know we're on POWER8E and have 6 PMCs.
748          * Using read/write_pmc() in a for loop adds 12 function calls and
749          * almost doubles our code size.
750          */
751         pmcs[0] = mfspr(SPRN_PMC1);
752         pmcs[1] = mfspr(SPRN_PMC2);
753         pmcs[2] = mfspr(SPRN_PMC3);
754         pmcs[3] = mfspr(SPRN_PMC4);
755         pmcs[4] = mfspr(SPRN_PMC5);
756         pmcs[5] = mfspr(SPRN_PMC6);
757
758         /* Ensure all freeze bits are unset */
759         mtspr(SPRN_MMCR2, 0);
760
761         /* Set up PMC6 to overflow in one cycle */
762         mtspr(SPRN_PMC6, 0x7FFFFFFE);
763
764         /* Enable exceptions and unfreeze PMC6 */
765         mtspr(SPRN_MMCR0, MMCR0_PMXE | MMCR0_PMCjCE | MMCR0_PMAO);
766
767         /* Now we need to refreeze and restore the PMCs */
768         mtspr(SPRN_MMCR0, MMCR0_FC | MMCR0_PMAO);
769
770         mtspr(SPRN_PMC1, pmcs[0]);
771         mtspr(SPRN_PMC2, pmcs[1]);
772         mtspr(SPRN_PMC3, pmcs[2]);
773         mtspr(SPRN_PMC4, pmcs[3]);
774         mtspr(SPRN_PMC5, pmcs[4]);
775         mtspr(SPRN_PMC6, pmcs[5]);
776 }
777
778 #endif /* CONFIG_PPC64 */
779
780 static void perf_event_interrupt(struct pt_regs *regs);
781
782 /*
783  * Read one performance monitor counter (PMC).
784  */
785 static unsigned long read_pmc(int idx)
786 {
787         unsigned long val;
788
789         switch (idx) {
790         case 1:
791                 val = mfspr(SPRN_PMC1);
792                 break;
793         case 2:
794                 val = mfspr(SPRN_PMC2);
795                 break;
796         case 3:
797                 val = mfspr(SPRN_PMC3);
798                 break;
799         case 4:
800                 val = mfspr(SPRN_PMC4);
801                 break;
802         case 5:
803                 val = mfspr(SPRN_PMC5);
804                 break;
805         case 6:
806                 val = mfspr(SPRN_PMC6);
807                 break;
808 #ifdef CONFIG_PPC64
809         case 7:
810                 val = mfspr(SPRN_PMC7);
811                 break;
812         case 8:
813                 val = mfspr(SPRN_PMC8);
814                 break;
815 #endif /* CONFIG_PPC64 */
816         default:
817                 printk(KERN_ERR "oops trying to read PMC%d\n", idx);
818                 val = 0;
819         }
820         return val;
821 }
822
823 /*
824  * Write one PMC.
825  */
826 static void write_pmc(int idx, unsigned long val)
827 {
828         switch (idx) {
829         case 1:
830                 mtspr(SPRN_PMC1, val);
831                 break;
832         case 2:
833                 mtspr(SPRN_PMC2, val);
834                 break;
835         case 3:
836                 mtspr(SPRN_PMC3, val);
837                 break;
838         case 4:
839                 mtspr(SPRN_PMC4, val);
840                 break;
841         case 5:
842                 mtspr(SPRN_PMC5, val);
843                 break;
844         case 6:
845                 mtspr(SPRN_PMC6, val);
846                 break;
847 #ifdef CONFIG_PPC64
848         case 7:
849                 mtspr(SPRN_PMC7, val);
850                 break;
851         case 8:
852                 mtspr(SPRN_PMC8, val);
853                 break;
854 #endif /* CONFIG_PPC64 */
855         default:
856                 printk(KERN_ERR "oops trying to write PMC%d\n", idx);
857         }
858 }
859
860 static int any_pmc_overflown(struct cpu_hw_events *cpuhw)
861 {
862         int i, idx;
863
864         for (i = 0; i < cpuhw->n_events; i++) {
865                 idx = cpuhw->event[i]->hw.idx;
866                 if ((idx) && ((int)read_pmc(idx) < 0))
867                         return idx;
868         }
869
870         return 0;
871 }
872
873 /* Called from sysrq_handle_showregs() */
874 void perf_event_print_debug(void)
875 {
876         unsigned long sdar, sier, flags;
877         u32 pmcs[MAX_HWEVENTS];
878         int i;
879
880         if (!ppmu) {
881                 pr_info("Performance monitor hardware not registered.\n");
882                 return;
883         }
884
885         if (!ppmu->n_counter)
886                 return;
887
888         local_irq_save(flags);
889
890         pr_info("CPU: %d PMU registers, ppmu = %s n_counters = %d",
891                  smp_processor_id(), ppmu->name, ppmu->n_counter);
892
893         for (i = 0; i < ppmu->n_counter; i++)
894                 pmcs[i] = read_pmc(i + 1);
895
896         for (; i < MAX_HWEVENTS; i++)
897                 pmcs[i] = 0xdeadbeef;
898
899         pr_info("PMC1:  %08x PMC2: %08x PMC3: %08x PMC4: %08x\n",
900                  pmcs[0], pmcs[1], pmcs[2], pmcs[3]);
901
902         if (ppmu->n_counter > 4)
903                 pr_info("PMC5:  %08x PMC6: %08x PMC7: %08x PMC8: %08x\n",
904                          pmcs[4], pmcs[5], pmcs[6], pmcs[7]);
905
906         pr_info("MMCR0: %016lx MMCR1: %016lx MMCRA: %016lx\n",
907                 mfspr(SPRN_MMCR0), mfspr(SPRN_MMCR1), mfspr(SPRN_MMCRA));
908
909         sdar = sier = 0;
910 #ifdef CONFIG_PPC64
911         sdar = mfspr(SPRN_SDAR);
912
913         if (ppmu->flags & PPMU_HAS_SIER)
914                 sier = mfspr(SPRN_SIER);
915
916         if (ppmu->flags & PPMU_ARCH_207S) {
917                 pr_info("MMCR2: %016lx EBBHR: %016lx\n",
918                         mfspr(SPRN_MMCR2), mfspr(SPRN_EBBHR));
919                 pr_info("EBBRR: %016lx BESCR: %016lx\n",
920                         mfspr(SPRN_EBBRR), mfspr(SPRN_BESCR));
921         }
922
923         if (ppmu->flags & PPMU_ARCH_31) {
924                 pr_info("MMCR3: %016lx SIER2: %016lx SIER3: %016lx\n",
925                         mfspr(SPRN_MMCR3), mfspr(SPRN_SIER2), mfspr(SPRN_SIER3));
926         }
927 #endif
928         pr_info("SIAR:  %016lx SDAR:  %016lx SIER:  %016lx\n",
929                 mfspr(SPRN_SIAR), sdar, sier);
930
931         local_irq_restore(flags);
932 }
933
934 /*
935  * Check if a set of events can all go on the PMU at once.
936  * If they can't, this will look at alternative codes for the events
937  * and see if any combination of alternative codes is feasible.
938  * The feasible set is returned in event_id[].
939  */
940 static int power_check_constraints(struct cpu_hw_events *cpuhw,
941                                    u64 event_id[], unsigned int cflags[],
942                                    int n_ev, struct perf_event **event)
943 {
944         unsigned long mask, value, nv;
945         unsigned long smasks[MAX_HWEVENTS], svalues[MAX_HWEVENTS];
946         int n_alt[MAX_HWEVENTS], choice[MAX_HWEVENTS];
947         int i, j;
948         unsigned long addf = ppmu->add_fields;
949         unsigned long tadd = ppmu->test_adder;
950         unsigned long grp_mask = ppmu->group_constraint_mask;
951         unsigned long grp_val = ppmu->group_constraint_val;
952
953         if (n_ev > ppmu->n_counter)
954                 return -1;
955
956         /* First see if the events will go on as-is */
957         for (i = 0; i < n_ev; ++i) {
958                 if ((cflags[i] & PPMU_LIMITED_PMC_REQD)
959                     && !ppmu->limited_pmc_event(event_id[i])) {
960                         ppmu->get_alternatives(event_id[i], cflags[i],
961                                                cpuhw->alternatives[i]);
962                         event_id[i] = cpuhw->alternatives[i][0];
963                 }
964                 if (ppmu->get_constraint(event_id[i], &cpuhw->amasks[i][0],
965                                          &cpuhw->avalues[i][0], event[i]->attr.config1))
966                         return -1;
967         }
968         value = mask = 0;
969         for (i = 0; i < n_ev; ++i) {
970                 nv = (value | cpuhw->avalues[i][0]) +
971                         (value & cpuhw->avalues[i][0] & addf);
972
973                 if (((((nv + tadd) ^ value) & mask) & (~grp_mask)) != 0)
974                         break;
975
976                 if (((((nv + tadd) ^ cpuhw->avalues[i][0]) & cpuhw->amasks[i][0])
977                         & (~grp_mask)) != 0)
978                         break;
979
980                 value = nv;
981                 mask |= cpuhw->amasks[i][0];
982         }
983         if (i == n_ev) {
984                 if ((value & mask & grp_mask) != (mask & grp_val))
985                         return -1;
986                 else
987                         return 0;       /* all OK */
988         }
989
990         /* doesn't work, gather alternatives... */
991         if (!ppmu->get_alternatives)
992                 return -1;
993         for (i = 0; i < n_ev; ++i) {
994                 choice[i] = 0;
995                 n_alt[i] = ppmu->get_alternatives(event_id[i], cflags[i],
996                                                   cpuhw->alternatives[i]);
997                 for (j = 1; j < n_alt[i]; ++j)
998                         ppmu->get_constraint(cpuhw->alternatives[i][j],
999                                              &cpuhw->amasks[i][j],
1000                                              &cpuhw->avalues[i][j],
1001                                              event[i]->attr.config1);
1002         }
1003
1004         /* enumerate all possibilities and see if any will work */
1005         i = 0;
1006         j = -1;
1007         value = mask = nv = 0;
1008         while (i < n_ev) {
1009                 if (j >= 0) {
1010                         /* we're backtracking, restore context */
1011                         value = svalues[i];
1012                         mask = smasks[i];
1013                         j = choice[i];
1014                 }
1015                 /*
1016                  * See if any alternative k for event_id i,
1017                  * where k > j, will satisfy the constraints.
1018                  */
1019                 while (++j < n_alt[i]) {
1020                         nv = (value | cpuhw->avalues[i][j]) +
1021                                 (value & cpuhw->avalues[i][j] & addf);
1022                         if ((((nv + tadd) ^ value) & mask) == 0 &&
1023                             (((nv + tadd) ^ cpuhw->avalues[i][j])
1024                              & cpuhw->amasks[i][j]) == 0)
1025                                 break;
1026                 }
1027                 if (j >= n_alt[i]) {
1028                         /*
1029                          * No feasible alternative, backtrack
1030                          * to event_id i-1 and continue enumerating its
1031                          * alternatives from where we got up to.
1032                          */
1033                         if (--i < 0)
1034                                 return -1;
1035                 } else {
1036                         /*
1037                          * Found a feasible alternative for event_id i,
1038                          * remember where we got up to with this event_id,
1039                          * go on to the next event_id, and start with
1040                          * the first alternative for it.
1041                          */
1042                         choice[i] = j;
1043                         svalues[i] = value;
1044                         smasks[i] = mask;
1045                         value = nv;
1046                         mask |= cpuhw->amasks[i][j];
1047                         ++i;
1048                         j = -1;
1049                 }
1050         }
1051
1052         /* OK, we have a feasible combination, tell the caller the solution */
1053         for (i = 0; i < n_ev; ++i)
1054                 event_id[i] = cpuhw->alternatives[i][choice[i]];
1055         return 0;
1056 }
1057
1058 /*
1059  * Check if newly-added events have consistent settings for
1060  * exclude_{user,kernel,hv} with each other and any previously
1061  * added events.
1062  */
1063 static int check_excludes(struct perf_event **ctrs, unsigned int cflags[],
1064                           int n_prev, int n_new)
1065 {
1066         int eu = 0, ek = 0, eh = 0;
1067         int i, n, first;
1068         struct perf_event *event;
1069
1070         /*
1071          * If the PMU we're on supports per event exclude settings then we
1072          * don't need to do any of this logic. NB. This assumes no PMU has both
1073          * per event exclude and limited PMCs.
1074          */
1075         if (ppmu->flags & PPMU_ARCH_207S)
1076                 return 0;
1077
1078         n = n_prev + n_new;
1079         if (n <= 1)
1080                 return 0;
1081
1082         first = 1;
1083         for (i = 0; i < n; ++i) {
1084                 if (cflags[i] & PPMU_LIMITED_PMC_OK) {
1085                         cflags[i] &= ~PPMU_LIMITED_PMC_REQD;
1086                         continue;
1087                 }
1088                 event = ctrs[i];
1089                 if (first) {
1090                         eu = event->attr.exclude_user;
1091                         ek = event->attr.exclude_kernel;
1092                         eh = event->attr.exclude_hv;
1093                         first = 0;
1094                 } else if (event->attr.exclude_user != eu ||
1095                            event->attr.exclude_kernel != ek ||
1096                            event->attr.exclude_hv != eh) {
1097                         return -EAGAIN;
1098                 }
1099         }
1100
1101         if (eu || ek || eh)
1102                 for (i = 0; i < n; ++i)
1103                         if (cflags[i] & PPMU_LIMITED_PMC_OK)
1104                                 cflags[i] |= PPMU_LIMITED_PMC_REQD;
1105
1106         return 0;
1107 }
1108
1109 static u64 check_and_compute_delta(u64 prev, u64 val)
1110 {
1111         u64 delta = (val - prev) & 0xfffffffful;
1112
1113         /*
1114          * POWER7 can roll back counter values, if the new value is smaller
1115          * than the previous value it will cause the delta and the counter to
1116          * have bogus values unless we rolled a counter over.  If a coutner is
1117          * rolled back, it will be smaller, but within 256, which is the maximum
1118          * number of events to rollback at once.  If we detect a rollback
1119          * return 0.  This can lead to a small lack of precision in the
1120          * counters.
1121          */
1122         if (prev > val && (prev - val) < 256)
1123                 delta = 0;
1124
1125         return delta;
1126 }
1127
1128 static void power_pmu_read(struct perf_event *event)
1129 {
1130         s64 val, delta, prev;
1131
1132         if (event->hw.state & PERF_HES_STOPPED)
1133                 return;
1134
1135         if (!event->hw.idx)
1136                 return;
1137
1138         if (is_ebb_event(event)) {
1139                 val = read_pmc(event->hw.idx);
1140                 local64_set(&event->hw.prev_count, val);
1141                 return;
1142         }
1143
1144         /*
1145          * Performance monitor interrupts come even when interrupts
1146          * are soft-disabled, as long as interrupts are hard-enabled.
1147          * Therefore we treat them like NMIs.
1148          */
1149         do {
1150                 prev = local64_read(&event->hw.prev_count);
1151                 barrier();
1152                 val = read_pmc(event->hw.idx);
1153                 delta = check_and_compute_delta(prev, val);
1154                 if (!delta)
1155                         return;
1156         } while (local64_cmpxchg(&event->hw.prev_count, prev, val) != prev);
1157
1158         local64_add(delta, &event->count);
1159
1160         /*
1161          * A number of places program the PMC with (0x80000000 - period_left).
1162          * We never want period_left to be less than 1 because we will program
1163          * the PMC with a value >= 0x800000000 and an edge detected PMC will
1164          * roll around to 0 before taking an exception. We have seen this
1165          * on POWER8.
1166          *
1167          * To fix this, clamp the minimum value of period_left to 1.
1168          */
1169         do {
1170                 prev = local64_read(&event->hw.period_left);
1171                 val = prev - delta;
1172                 if (val < 1)
1173                         val = 1;
1174         } while (local64_cmpxchg(&event->hw.period_left, prev, val) != prev);
1175 }
1176
1177 /*
1178  * On some machines, PMC5 and PMC6 can't be written, don't respect
1179  * the freeze conditions, and don't generate interrupts.  This tells
1180  * us if `event' is using such a PMC.
1181  */
1182 static int is_limited_pmc(int pmcnum)
1183 {
1184         return (ppmu->flags & PPMU_LIMITED_PMC5_6)
1185                 && (pmcnum == 5 || pmcnum == 6);
1186 }
1187
1188 static void freeze_limited_counters(struct cpu_hw_events *cpuhw,
1189                                     unsigned long pmc5, unsigned long pmc6)
1190 {
1191         struct perf_event *event;
1192         u64 val, prev, delta;
1193         int i;
1194
1195         for (i = 0; i < cpuhw->n_limited; ++i) {
1196                 event = cpuhw->limited_counter[i];
1197                 if (!event->hw.idx)
1198                         continue;
1199                 val = (event->hw.idx == 5) ? pmc5 : pmc6;
1200                 prev = local64_read(&event->hw.prev_count);
1201                 event->hw.idx = 0;
1202                 delta = check_and_compute_delta(prev, val);
1203                 if (delta)
1204                         local64_add(delta, &event->count);
1205         }
1206 }
1207
1208 static void thaw_limited_counters(struct cpu_hw_events *cpuhw,
1209                                   unsigned long pmc5, unsigned long pmc6)
1210 {
1211         struct perf_event *event;
1212         u64 val, prev;
1213         int i;
1214
1215         for (i = 0; i < cpuhw->n_limited; ++i) {
1216                 event = cpuhw->limited_counter[i];
1217                 event->hw.idx = cpuhw->limited_hwidx[i];
1218                 val = (event->hw.idx == 5) ? pmc5 : pmc6;
1219                 prev = local64_read(&event->hw.prev_count);
1220                 if (check_and_compute_delta(prev, val))
1221                         local64_set(&event->hw.prev_count, val);
1222                 perf_event_update_userpage(event);
1223         }
1224 }
1225
1226 /*
1227  * Since limited events don't respect the freeze conditions, we
1228  * have to read them immediately after freezing or unfreezing the
1229  * other events.  We try to keep the values from the limited
1230  * events as consistent as possible by keeping the delay (in
1231  * cycles and instructions) between freezing/unfreezing and reading
1232  * the limited events as small and consistent as possible.
1233  * Therefore, if any limited events are in use, we read them
1234  * both, and always in the same order, to minimize variability,
1235  * and do it inside the same asm that writes MMCR0.
1236  */
1237 static void write_mmcr0(struct cpu_hw_events *cpuhw, unsigned long mmcr0)
1238 {
1239         unsigned long pmc5, pmc6;
1240
1241         if (!cpuhw->n_limited) {
1242                 mtspr(SPRN_MMCR0, mmcr0);
1243                 return;
1244         }
1245
1246         /*
1247          * Write MMCR0, then read PMC5 and PMC6 immediately.
1248          * To ensure we don't get a performance monitor interrupt
1249          * between writing MMCR0 and freezing/thawing the limited
1250          * events, we first write MMCR0 with the event overflow
1251          * interrupt enable bits turned off.
1252          */
1253         asm volatile("mtspr %3,%2; mfspr %0,%4; mfspr %1,%5"
1254                      : "=&r" (pmc5), "=&r" (pmc6)
1255                      : "r" (mmcr0 & ~(MMCR0_PMC1CE | MMCR0_PMCjCE)),
1256                        "i" (SPRN_MMCR0),
1257                        "i" (SPRN_PMC5), "i" (SPRN_PMC6));
1258
1259         if (mmcr0 & MMCR0_FC)
1260                 freeze_limited_counters(cpuhw, pmc5, pmc6);
1261         else
1262                 thaw_limited_counters(cpuhw, pmc5, pmc6);
1263
1264         /*
1265          * Write the full MMCR0 including the event overflow interrupt
1266          * enable bits, if necessary.
1267          */
1268         if (mmcr0 & (MMCR0_PMC1CE | MMCR0_PMCjCE))
1269                 mtspr(SPRN_MMCR0, mmcr0);
1270 }
1271
1272 /*
1273  * Disable all events to prevent PMU interrupts and to allow
1274  * events to be added or removed.
1275  */
1276 static void power_pmu_disable(struct pmu *pmu)
1277 {
1278         struct cpu_hw_events *cpuhw;
1279         unsigned long flags, mmcr0, val, mmcra;
1280
1281         if (!ppmu)
1282                 return;
1283         local_irq_save(flags);
1284         cpuhw = this_cpu_ptr(&cpu_hw_events);
1285
1286         if (!cpuhw->disabled) {
1287                 /*
1288                  * Check if we ever enabled the PMU on this cpu.
1289                  */
1290                 if (!cpuhw->pmcs_enabled) {
1291                         ppc_enable_pmcs();
1292                         cpuhw->pmcs_enabled = 1;
1293                 }
1294
1295                 /*
1296                  * Set the 'freeze counters' bit, clear EBE/BHRBA/PMCC/PMAO/FC56
1297                  * Also clear PMXE to disable PMI's getting triggered in some
1298                  * corner cases during PMU disable.
1299                  */
1300                 val  = mmcr0 = mfspr(SPRN_MMCR0);
1301                 val |= MMCR0_FC;
1302                 val &= ~(MMCR0_EBE | MMCR0_BHRBA | MMCR0_PMCC | MMCR0_PMAO |
1303                          MMCR0_PMXE | MMCR0_FC56);
1304                 /* Set mmcr0 PMCCEXT for p10 */
1305                 if (ppmu->flags & PPMU_ARCH_31)
1306                         val |= MMCR0_PMCCEXT;
1307
1308                 /*
1309                  * The barrier is to make sure the mtspr has been
1310                  * executed and the PMU has frozen the events etc.
1311                  * before we return.
1312                  */
1313                 write_mmcr0(cpuhw, val);
1314                 mb();
1315                 isync();
1316
1317                 /*
1318                  * Some corner cases could clear the PMU counter overflow
1319                  * while a masked PMI is pending. One such case is when
1320                  * a PMI happens during interrupt replay and perf counter
1321                  * values are cleared by PMU callbacks before replay.
1322                  *
1323                  * Disable the interrupt by clearing the paca bit for PMI
1324                  * since we are disabling the PMU now. Otherwise provide a
1325                  * warning if there is PMI pending, but no counter is found
1326                  * overflown.
1327                  *
1328                  * Since power_pmu_disable runs under local_irq_save, it
1329                  * could happen that code hits a PMC overflow without PMI
1330                  * pending in paca. Hence only clear PMI pending if it was
1331                  * set.
1332                  *
1333                  * If a PMI is pending, then MSR[EE] must be disabled (because
1334                  * the masked PMI handler disabling EE). So it is safe to
1335                  * call clear_pmi_irq_pending().
1336                  */
1337                 if (pmi_irq_pending())
1338                         clear_pmi_irq_pending();
1339
1340                 val = mmcra = cpuhw->mmcr.mmcra;
1341
1342                 /*
1343                  * Disable instruction sampling if it was enabled
1344                  */
1345                 if (cpuhw->mmcr.mmcra & MMCRA_SAMPLE_ENABLE)
1346                         val &= ~MMCRA_SAMPLE_ENABLE;
1347
1348                 /* Disable BHRB via mmcra (BHRBRD) for p10 */
1349                 if (ppmu->flags & PPMU_ARCH_31)
1350                         val |= MMCRA_BHRB_DISABLE;
1351
1352                 /*
1353                  * Write SPRN_MMCRA if mmcra has either disabled
1354                  * instruction sampling or BHRB.
1355                  */
1356                 if (val != mmcra) {
1357                         mtspr(SPRN_MMCRA, mmcra);
1358                         mb();
1359                         isync();
1360                 }
1361
1362                 cpuhw->disabled = 1;
1363                 cpuhw->n_added = 0;
1364
1365                 ebb_switch_out(mmcr0);
1366
1367 #ifdef CONFIG_PPC64
1368                 /*
1369                  * These are readable by userspace, may contain kernel
1370                  * addresses and are not switched by context switch, so clear
1371                  * them now to avoid leaking anything to userspace in general
1372                  * including to another process.
1373                  */
1374                 if (ppmu->flags & PPMU_ARCH_207S) {
1375                         mtspr(SPRN_SDAR, 0);
1376                         mtspr(SPRN_SIAR, 0);
1377                 }
1378 #endif
1379         }
1380
1381         local_irq_restore(flags);
1382 }
1383
1384 /*
1385  * Re-enable all events if disable == 0.
1386  * If we were previously disabled and events were added, then
1387  * put the new config on the PMU.
1388  */
1389 static void power_pmu_enable(struct pmu *pmu)
1390 {
1391         struct perf_event *event;
1392         struct cpu_hw_events *cpuhw;
1393         unsigned long flags;
1394         long i;
1395         unsigned long val, mmcr0;
1396         s64 left;
1397         unsigned int hwc_index[MAX_HWEVENTS];
1398         int n_lim;
1399         int idx;
1400         bool ebb;
1401
1402         if (!ppmu)
1403                 return;
1404         local_irq_save(flags);
1405
1406         cpuhw = this_cpu_ptr(&cpu_hw_events);
1407         if (!cpuhw->disabled)
1408                 goto out;
1409
1410         if (cpuhw->n_events == 0) {
1411                 ppc_set_pmu_inuse(0);
1412                 goto out;
1413         }
1414
1415         cpuhw->disabled = 0;
1416
1417         /*
1418          * EBB requires an exclusive group and all events must have the EBB
1419          * flag set, or not set, so we can just check a single event. Also we
1420          * know we have at least one event.
1421          */
1422         ebb = is_ebb_event(cpuhw->event[0]);
1423
1424         /*
1425          * If we didn't change anything, or only removed events,
1426          * no need to recalculate MMCR* settings and reset the PMCs.
1427          * Just reenable the PMU with the current MMCR* settings
1428          * (possibly updated for removal of events).
1429          */
1430         if (!cpuhw->n_added) {
1431                 /*
1432                  * If there is any active event with an overflown PMC
1433                  * value, set back PACA_IRQ_PMI which would have been
1434                  * cleared in power_pmu_disable().
1435                  */
1436                 hard_irq_disable();
1437                 if (any_pmc_overflown(cpuhw))
1438                         set_pmi_irq_pending();
1439
1440                 mtspr(SPRN_MMCRA, cpuhw->mmcr.mmcra & ~MMCRA_SAMPLE_ENABLE);
1441                 mtspr(SPRN_MMCR1, cpuhw->mmcr.mmcr1);
1442                 if (ppmu->flags & PPMU_ARCH_31)
1443                         mtspr(SPRN_MMCR3, cpuhw->mmcr.mmcr3);
1444                 goto out_enable;
1445         }
1446
1447         /*
1448          * Clear all MMCR settings and recompute them for the new set of events.
1449          */
1450         memset(&cpuhw->mmcr, 0, sizeof(cpuhw->mmcr));
1451
1452         if (ppmu->compute_mmcr(cpuhw->events, cpuhw->n_events, hwc_index,
1453                                &cpuhw->mmcr, cpuhw->event, ppmu->flags)) {
1454                 /* shouldn't ever get here */
1455                 printk(KERN_ERR "oops compute_mmcr failed\n");
1456                 goto out;
1457         }
1458
1459         if (!(ppmu->flags & PPMU_ARCH_207S)) {
1460                 /*
1461                  * Add in MMCR0 freeze bits corresponding to the attr.exclude_*
1462                  * bits for the first event. We have already checked that all
1463                  * events have the same value for these bits as the first event.
1464                  */
1465                 event = cpuhw->event[0];
1466                 if (event->attr.exclude_user)
1467                         cpuhw->mmcr.mmcr0 |= MMCR0_FCP;
1468                 if (event->attr.exclude_kernel)
1469                         cpuhw->mmcr.mmcr0 |= freeze_events_kernel;
1470                 if (event->attr.exclude_hv)
1471                         cpuhw->mmcr.mmcr0 |= MMCR0_FCHV;
1472         }
1473
1474         /*
1475          * Write the new configuration to MMCR* with the freeze
1476          * bit set and set the hardware events to their initial values.
1477          * Then unfreeze the events.
1478          */
1479         ppc_set_pmu_inuse(1);
1480         mtspr(SPRN_MMCRA, cpuhw->mmcr.mmcra & ~MMCRA_SAMPLE_ENABLE);
1481         mtspr(SPRN_MMCR1, cpuhw->mmcr.mmcr1);
1482         mtspr(SPRN_MMCR0, (cpuhw->mmcr.mmcr0 & ~(MMCR0_PMC1CE | MMCR0_PMCjCE))
1483                                 | MMCR0_FC);
1484         if (ppmu->flags & PPMU_ARCH_207S)
1485                 mtspr(SPRN_MMCR2, cpuhw->mmcr.mmcr2);
1486
1487         if (ppmu->flags & PPMU_ARCH_31)
1488                 mtspr(SPRN_MMCR3, cpuhw->mmcr.mmcr3);
1489
1490         /*
1491          * Read off any pre-existing events that need to move
1492          * to another PMC.
1493          */
1494         for (i = 0; i < cpuhw->n_events; ++i) {
1495                 event = cpuhw->event[i];
1496                 if (event->hw.idx && event->hw.idx != hwc_index[i] + 1) {
1497                         power_pmu_read(event);
1498                         write_pmc(event->hw.idx, 0);
1499                         event->hw.idx = 0;
1500                 }
1501         }
1502
1503         /*
1504          * Initialize the PMCs for all the new and moved events.
1505          */
1506         cpuhw->n_limited = n_lim = 0;
1507         for (i = 0; i < cpuhw->n_events; ++i) {
1508                 event = cpuhw->event[i];
1509                 if (event->hw.idx)
1510                         continue;
1511                 idx = hwc_index[i] + 1;
1512                 if (is_limited_pmc(idx)) {
1513                         cpuhw->limited_counter[n_lim] = event;
1514                         cpuhw->limited_hwidx[n_lim] = idx;
1515                         ++n_lim;
1516                         continue;
1517                 }
1518
1519                 if (ebb)
1520                         val = local64_read(&event->hw.prev_count);
1521                 else {
1522                         val = 0;
1523                         if (event->hw.sample_period) {
1524                                 left = local64_read(&event->hw.period_left);
1525                                 if (left < 0x80000000L)
1526                                         val = 0x80000000L - left;
1527                         }
1528                         local64_set(&event->hw.prev_count, val);
1529                 }
1530
1531                 event->hw.idx = idx;
1532                 if (event->hw.state & PERF_HES_STOPPED)
1533                         val = 0;
1534                 write_pmc(idx, val);
1535
1536                 perf_event_update_userpage(event);
1537         }
1538         cpuhw->n_limited = n_lim;
1539         cpuhw->mmcr.mmcr0 |= MMCR0_PMXE | MMCR0_FCECE;
1540
1541  out_enable:
1542         pmao_restore_workaround(ebb);
1543
1544         mmcr0 = ebb_switch_in(ebb, cpuhw);
1545
1546         mb();
1547         if (cpuhw->bhrb_users)
1548                 ppmu->config_bhrb(cpuhw->bhrb_filter);
1549
1550         write_mmcr0(cpuhw, mmcr0);
1551
1552         /*
1553          * Enable instruction sampling if necessary
1554          */
1555         if (cpuhw->mmcr.mmcra & MMCRA_SAMPLE_ENABLE) {
1556                 mb();
1557                 mtspr(SPRN_MMCRA, cpuhw->mmcr.mmcra);
1558         }
1559
1560  out:
1561
1562         local_irq_restore(flags);
1563 }
1564
1565 static int collect_events(struct perf_event *group, int max_count,
1566                           struct perf_event *ctrs[], u64 *events,
1567                           unsigned int *flags)
1568 {
1569         int n = 0;
1570         struct perf_event *event;
1571
1572         if (group->pmu->task_ctx_nr == perf_hw_context) {
1573                 if (n >= max_count)
1574                         return -1;
1575                 ctrs[n] = group;
1576                 flags[n] = group->hw.event_base;
1577                 events[n++] = group->hw.config;
1578         }
1579         for_each_sibling_event(event, group) {
1580                 if (event->pmu->task_ctx_nr == perf_hw_context &&
1581                     event->state != PERF_EVENT_STATE_OFF) {
1582                         if (n >= max_count)
1583                                 return -1;
1584                         ctrs[n] = event;
1585                         flags[n] = event->hw.event_base;
1586                         events[n++] = event->hw.config;
1587                 }
1588         }
1589         return n;
1590 }
1591
1592 /*
1593  * Add an event to the PMU.
1594  * If all events are not already frozen, then we disable and
1595  * re-enable the PMU in order to get hw_perf_enable to do the
1596  * actual work of reconfiguring the PMU.
1597  */
1598 static int power_pmu_add(struct perf_event *event, int ef_flags)
1599 {
1600         struct cpu_hw_events *cpuhw;
1601         unsigned long flags;
1602         int n0;
1603         int ret = -EAGAIN;
1604
1605         local_irq_save(flags);
1606         perf_pmu_disable(event->pmu);
1607
1608         /*
1609          * Add the event to the list (if there is room)
1610          * and check whether the total set is still feasible.
1611          */
1612         cpuhw = this_cpu_ptr(&cpu_hw_events);
1613         n0 = cpuhw->n_events;
1614         if (n0 >= ppmu->n_counter)
1615                 goto out;
1616         cpuhw->event[n0] = event;
1617         cpuhw->events[n0] = event->hw.config;
1618         cpuhw->flags[n0] = event->hw.event_base;
1619
1620         /*
1621          * This event may have been disabled/stopped in record_and_restart()
1622          * because we exceeded the ->event_limit. If re-starting the event,
1623          * clear the ->hw.state (STOPPED and UPTODATE flags), so the user
1624          * notification is re-enabled.
1625          */
1626         if (!(ef_flags & PERF_EF_START))
1627                 event->hw.state = PERF_HES_STOPPED | PERF_HES_UPTODATE;
1628         else
1629                 event->hw.state = 0;
1630
1631         /*
1632          * If group events scheduling transaction was started,
1633          * skip the schedulability test here, it will be performed
1634          * at commit time(->commit_txn) as a whole
1635          */
1636         if (cpuhw->txn_flags & PERF_PMU_TXN_ADD)
1637                 goto nocheck;
1638
1639         if (check_excludes(cpuhw->event, cpuhw->flags, n0, 1))
1640                 goto out;
1641         if (power_check_constraints(cpuhw, cpuhw->events, cpuhw->flags, n0 + 1, cpuhw->event))
1642                 goto out;
1643         event->hw.config = cpuhw->events[n0];
1644
1645 nocheck:
1646         ebb_event_add(event);
1647
1648         ++cpuhw->n_events;
1649         ++cpuhw->n_added;
1650
1651         ret = 0;
1652  out:
1653         if (has_branch_stack(event)) {
1654                 u64 bhrb_filter = -1;
1655
1656                 if (ppmu->bhrb_filter_map)
1657                         bhrb_filter = ppmu->bhrb_filter_map(
1658                                 event->attr.branch_sample_type);
1659
1660                 if (bhrb_filter != -1) {
1661                         cpuhw->bhrb_filter = bhrb_filter;
1662                         power_pmu_bhrb_enable(event);
1663                 }
1664         }
1665
1666         perf_pmu_enable(event->pmu);
1667         local_irq_restore(flags);
1668         return ret;
1669 }
1670
1671 /*
1672  * Remove an event from the PMU.
1673  */
1674 static void power_pmu_del(struct perf_event *event, int ef_flags)
1675 {
1676         struct cpu_hw_events *cpuhw;
1677         long i;
1678         unsigned long flags;
1679
1680         local_irq_save(flags);
1681         perf_pmu_disable(event->pmu);
1682
1683         power_pmu_read(event);
1684
1685         cpuhw = this_cpu_ptr(&cpu_hw_events);
1686         for (i = 0; i < cpuhw->n_events; ++i) {
1687                 if (event == cpuhw->event[i]) {
1688                         while (++i < cpuhw->n_events) {
1689                                 cpuhw->event[i-1] = cpuhw->event[i];
1690                                 cpuhw->events[i-1] = cpuhw->events[i];
1691                                 cpuhw->flags[i-1] = cpuhw->flags[i];
1692                         }
1693                         --cpuhw->n_events;
1694                         ppmu->disable_pmc(event->hw.idx - 1, &cpuhw->mmcr);
1695                         if (event->hw.idx) {
1696                                 write_pmc(event->hw.idx, 0);
1697                                 event->hw.idx = 0;
1698                         }
1699                         perf_event_update_userpage(event);
1700                         break;
1701                 }
1702         }
1703         for (i = 0; i < cpuhw->n_limited; ++i)
1704                 if (event == cpuhw->limited_counter[i])
1705                         break;
1706         if (i < cpuhw->n_limited) {
1707                 while (++i < cpuhw->n_limited) {
1708                         cpuhw->limited_counter[i-1] = cpuhw->limited_counter[i];
1709                         cpuhw->limited_hwidx[i-1] = cpuhw->limited_hwidx[i];
1710                 }
1711                 --cpuhw->n_limited;
1712         }
1713         if (cpuhw->n_events == 0) {
1714                 /* disable exceptions if no events are running */
1715                 cpuhw->mmcr.mmcr0 &= ~(MMCR0_PMXE | MMCR0_FCECE);
1716         }
1717
1718         if (has_branch_stack(event))
1719                 power_pmu_bhrb_disable(event);
1720
1721         perf_pmu_enable(event->pmu);
1722         local_irq_restore(flags);
1723 }
1724
1725 /*
1726  * POWER-PMU does not support disabling individual counters, hence
1727  * program their cycle counter to their max value and ignore the interrupts.
1728  */
1729
1730 static void power_pmu_start(struct perf_event *event, int ef_flags)
1731 {
1732         unsigned long flags;
1733         s64 left;
1734         unsigned long val;
1735
1736         if (!event->hw.idx || !event->hw.sample_period)
1737                 return;
1738
1739         if (!(event->hw.state & PERF_HES_STOPPED))
1740                 return;
1741
1742         if (ef_flags & PERF_EF_RELOAD)
1743                 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1744
1745         local_irq_save(flags);
1746         perf_pmu_disable(event->pmu);
1747
1748         event->hw.state = 0;
1749         left = local64_read(&event->hw.period_left);
1750
1751         val = 0;
1752         if (left < 0x80000000L)
1753                 val = 0x80000000L - left;
1754
1755         write_pmc(event->hw.idx, val);
1756
1757         perf_event_update_userpage(event);
1758         perf_pmu_enable(event->pmu);
1759         local_irq_restore(flags);
1760 }
1761
1762 static void power_pmu_stop(struct perf_event *event, int ef_flags)
1763 {
1764         unsigned long flags;
1765
1766         if (!event->hw.idx || !event->hw.sample_period)
1767                 return;
1768
1769         if (event->hw.state & PERF_HES_STOPPED)
1770                 return;
1771
1772         local_irq_save(flags);
1773         perf_pmu_disable(event->pmu);
1774
1775         power_pmu_read(event);
1776         event->hw.state |= PERF_HES_STOPPED | PERF_HES_UPTODATE;
1777         write_pmc(event->hw.idx, 0);
1778
1779         perf_event_update_userpage(event);
1780         perf_pmu_enable(event->pmu);
1781         local_irq_restore(flags);
1782 }
1783
1784 /*
1785  * Start group events scheduling transaction
1786  * Set the flag to make pmu::enable() not perform the
1787  * schedulability test, it will be performed at commit time
1788  *
1789  * We only support PERF_PMU_TXN_ADD transactions. Save the
1790  * transaction flags but otherwise ignore non-PERF_PMU_TXN_ADD
1791  * transactions.
1792  */
1793 static void power_pmu_start_txn(struct pmu *pmu, unsigned int txn_flags)
1794 {
1795         struct cpu_hw_events *cpuhw = this_cpu_ptr(&cpu_hw_events);
1796
1797         WARN_ON_ONCE(cpuhw->txn_flags);         /* txn already in flight */
1798
1799         cpuhw->txn_flags = txn_flags;
1800         if (txn_flags & ~PERF_PMU_TXN_ADD)
1801                 return;
1802
1803         perf_pmu_disable(pmu);
1804         cpuhw->n_txn_start = cpuhw->n_events;
1805 }
1806
1807 /*
1808  * Stop group events scheduling transaction
1809  * Clear the flag and pmu::enable() will perform the
1810  * schedulability test.
1811  */
1812 static void power_pmu_cancel_txn(struct pmu *pmu)
1813 {
1814         struct cpu_hw_events *cpuhw = this_cpu_ptr(&cpu_hw_events);
1815         unsigned int txn_flags;
1816
1817         WARN_ON_ONCE(!cpuhw->txn_flags);        /* no txn in flight */
1818
1819         txn_flags = cpuhw->txn_flags;
1820         cpuhw->txn_flags = 0;
1821         if (txn_flags & ~PERF_PMU_TXN_ADD)
1822                 return;
1823
1824         perf_pmu_enable(pmu);
1825 }
1826
1827 /*
1828  * Commit group events scheduling transaction
1829  * Perform the group schedulability test as a whole
1830  * Return 0 if success
1831  */
1832 static int power_pmu_commit_txn(struct pmu *pmu)
1833 {
1834         struct cpu_hw_events *cpuhw;
1835         long i, n;
1836
1837         if (!ppmu)
1838                 return -EAGAIN;
1839
1840         cpuhw = this_cpu_ptr(&cpu_hw_events);
1841         WARN_ON_ONCE(!cpuhw->txn_flags);        /* no txn in flight */
1842
1843         if (cpuhw->txn_flags & ~PERF_PMU_TXN_ADD) {
1844                 cpuhw->txn_flags = 0;
1845                 return 0;
1846         }
1847
1848         n = cpuhw->n_events;
1849         if (check_excludes(cpuhw->event, cpuhw->flags, 0, n))
1850                 return -EAGAIN;
1851         i = power_check_constraints(cpuhw, cpuhw->events, cpuhw->flags, n, cpuhw->event);
1852         if (i < 0)
1853                 return -EAGAIN;
1854
1855         for (i = cpuhw->n_txn_start; i < n; ++i)
1856                 cpuhw->event[i]->hw.config = cpuhw->events[i];
1857
1858         cpuhw->txn_flags = 0;
1859         perf_pmu_enable(pmu);
1860         return 0;
1861 }
1862
1863 /*
1864  * Return 1 if we might be able to put event on a limited PMC,
1865  * or 0 if not.
1866  * An event can only go on a limited PMC if it counts something
1867  * that a limited PMC can count, doesn't require interrupts, and
1868  * doesn't exclude any processor mode.
1869  */
1870 static int can_go_on_limited_pmc(struct perf_event *event, u64 ev,
1871                                  unsigned int flags)
1872 {
1873         int n;
1874         u64 alt[MAX_EVENT_ALTERNATIVES];
1875
1876         if (event->attr.exclude_user
1877             || event->attr.exclude_kernel
1878             || event->attr.exclude_hv
1879             || event->attr.sample_period)
1880                 return 0;
1881
1882         if (ppmu->limited_pmc_event(ev))
1883                 return 1;
1884
1885         /*
1886          * The requested event_id isn't on a limited PMC already;
1887          * see if any alternative code goes on a limited PMC.
1888          */
1889         if (!ppmu->get_alternatives)
1890                 return 0;
1891
1892         flags |= PPMU_LIMITED_PMC_OK | PPMU_LIMITED_PMC_REQD;
1893         n = ppmu->get_alternatives(ev, flags, alt);
1894
1895         return n > 0;
1896 }
1897
1898 /*
1899  * Find an alternative event_id that goes on a normal PMC, if possible,
1900  * and return the event_id code, or 0 if there is no such alternative.
1901  * (Note: event_id code 0 is "don't count" on all machines.)
1902  */
1903 static u64 normal_pmc_alternative(u64 ev, unsigned long flags)
1904 {
1905         u64 alt[MAX_EVENT_ALTERNATIVES];
1906         int n;
1907
1908         flags &= ~(PPMU_LIMITED_PMC_OK | PPMU_LIMITED_PMC_REQD);
1909         n = ppmu->get_alternatives(ev, flags, alt);
1910         if (!n)
1911                 return 0;
1912         return alt[0];
1913 }
1914
1915 /* Number of perf_events counting hardware events */
1916 static atomic_t num_events;
1917 /* Used to avoid races in calling reserve/release_pmc_hardware */
1918 static DEFINE_MUTEX(pmc_reserve_mutex);
1919
1920 /*
1921  * Release the PMU if this is the last perf_event.
1922  */
1923 static void hw_perf_event_destroy(struct perf_event *event)
1924 {
1925         if (!atomic_add_unless(&num_events, -1, 1)) {
1926                 mutex_lock(&pmc_reserve_mutex);
1927                 if (atomic_dec_return(&num_events) == 0)
1928                         release_pmc_hardware();
1929                 mutex_unlock(&pmc_reserve_mutex);
1930         }
1931 }
1932
1933 /*
1934  * Translate a generic cache event_id config to a raw event_id code.
1935  */
1936 static int hw_perf_cache_event(u64 config, u64 *eventp)
1937 {
1938         unsigned long type, op, result;
1939         u64 ev;
1940
1941         if (!ppmu->cache_events)
1942                 return -EINVAL;
1943
1944         /* unpack config */
1945         type = config & 0xff;
1946         op = (config >> 8) & 0xff;
1947         result = (config >> 16) & 0xff;
1948
1949         if (type >= PERF_COUNT_HW_CACHE_MAX ||
1950             op >= PERF_COUNT_HW_CACHE_OP_MAX ||
1951             result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
1952                 return -EINVAL;
1953
1954         ev = (*ppmu->cache_events)[type][op][result];
1955         if (ev == 0)
1956                 return -EOPNOTSUPP;
1957         if (ev == -1)
1958                 return -EINVAL;
1959         *eventp = ev;
1960         return 0;
1961 }
1962
1963 static bool is_event_blacklisted(u64 ev)
1964 {
1965         int i;
1966
1967         for (i=0; i < ppmu->n_blacklist_ev; i++) {
1968                 if (ppmu->blacklist_ev[i] == ev)
1969                         return true;
1970         }
1971
1972         return false;
1973 }
1974
1975 static int power_pmu_event_init(struct perf_event *event)
1976 {
1977         u64 ev;
1978         unsigned long flags, irq_flags;
1979         struct perf_event *ctrs[MAX_HWEVENTS];
1980         u64 events[MAX_HWEVENTS];
1981         unsigned int cflags[MAX_HWEVENTS];
1982         int n;
1983         int err;
1984         struct cpu_hw_events *cpuhw;
1985
1986         if (!ppmu)
1987                 return -ENOENT;
1988
1989         if (has_branch_stack(event)) {
1990                 /* PMU has BHRB enabled */
1991                 if (!(ppmu->flags & PPMU_ARCH_207S))
1992                         return -EOPNOTSUPP;
1993         }
1994
1995         switch (event->attr.type) {
1996         case PERF_TYPE_HARDWARE:
1997                 ev = event->attr.config;
1998                 if (ev >= ppmu->n_generic || ppmu->generic_events[ev] == 0)
1999                         return -EOPNOTSUPP;
2000
2001                 if (ppmu->blacklist_ev && is_event_blacklisted(ev))
2002                         return -EINVAL;
2003                 ev = ppmu->generic_events[ev];
2004                 break;
2005         case PERF_TYPE_HW_CACHE:
2006                 err = hw_perf_cache_event(event->attr.config, &ev);
2007                 if (err)
2008                         return err;
2009
2010                 if (ppmu->blacklist_ev && is_event_blacklisted(ev))
2011                         return -EINVAL;
2012                 break;
2013         case PERF_TYPE_RAW:
2014                 ev = event->attr.config;
2015
2016                 if (ppmu->blacklist_ev && is_event_blacklisted(ev))
2017                         return -EINVAL;
2018                 break;
2019         default:
2020                 return -ENOENT;
2021         }
2022
2023         /*
2024          * PMU config registers have fields that are
2025          * reserved and some specific values for bit fields are reserved.
2026          * For ex., MMCRA[61:62] is Randome Sampling Mode (SM)
2027          * and value of 0b11 to this field is reserved.
2028          * Check for invalid values in attr.config.
2029          */
2030         if (ppmu->check_attr_config &&
2031             ppmu->check_attr_config(event))
2032                 return -EINVAL;
2033
2034         event->hw.config_base = ev;
2035         event->hw.idx = 0;
2036
2037         /*
2038          * If we are not running on a hypervisor, force the
2039          * exclude_hv bit to 0 so that we don't care what
2040          * the user set it to.
2041          */
2042         if (!firmware_has_feature(FW_FEATURE_LPAR))
2043                 event->attr.exclude_hv = 0;
2044
2045         /*
2046          * If this is a per-task event, then we can use
2047          * PM_RUN_* events interchangeably with their non RUN_*
2048          * equivalents, e.g. PM_RUN_CYC instead of PM_CYC.
2049          * XXX we should check if the task is an idle task.
2050          */
2051         flags = 0;
2052         if (event->attach_state & PERF_ATTACH_TASK)
2053                 flags |= PPMU_ONLY_COUNT_RUN;
2054
2055         /*
2056          * If this machine has limited events, check whether this
2057          * event_id could go on a limited event.
2058          */
2059         if (ppmu->flags & PPMU_LIMITED_PMC5_6) {
2060                 if (can_go_on_limited_pmc(event, ev, flags)) {
2061                         flags |= PPMU_LIMITED_PMC_OK;
2062                 } else if (ppmu->limited_pmc_event(ev)) {
2063                         /*
2064                          * The requested event_id is on a limited PMC,
2065                          * but we can't use a limited PMC; see if any
2066                          * alternative goes on a normal PMC.
2067                          */
2068                         ev = normal_pmc_alternative(ev, flags);
2069                         if (!ev)
2070                                 return -EINVAL;
2071                 }
2072         }
2073
2074         /* Extra checks for EBB */
2075         err = ebb_event_check(event);
2076         if (err)
2077                 return err;
2078
2079         /*
2080          * If this is in a group, check if it can go on with all the
2081          * other hardware events in the group.  We assume the event
2082          * hasn't been linked into its leader's sibling list at this point.
2083          */
2084         n = 0;
2085         if (event->group_leader != event) {
2086                 n = collect_events(event->group_leader, ppmu->n_counter - 1,
2087                                    ctrs, events, cflags);
2088                 if (n < 0)
2089                         return -EINVAL;
2090         }
2091         events[n] = ev;
2092         ctrs[n] = event;
2093         cflags[n] = flags;
2094         if (check_excludes(ctrs, cflags, n, 1))
2095                 return -EINVAL;
2096
2097         local_irq_save(irq_flags);
2098         cpuhw = this_cpu_ptr(&cpu_hw_events);
2099
2100         err = power_check_constraints(cpuhw, events, cflags, n + 1, ctrs);
2101
2102         if (has_branch_stack(event)) {
2103                 u64 bhrb_filter = -1;
2104
2105                 if (ppmu->bhrb_filter_map)
2106                         bhrb_filter = ppmu->bhrb_filter_map(
2107                                         event->attr.branch_sample_type);
2108
2109                 if (bhrb_filter == -1) {
2110                         local_irq_restore(irq_flags);
2111                         return -EOPNOTSUPP;
2112                 }
2113                 cpuhw->bhrb_filter = bhrb_filter;
2114         }
2115
2116         local_irq_restore(irq_flags);
2117         if (err)
2118                 return -EINVAL;
2119
2120         event->hw.config = events[n];
2121         event->hw.event_base = cflags[n];
2122         event->hw.last_period = event->hw.sample_period;
2123         local64_set(&event->hw.period_left, event->hw.last_period);
2124
2125         /*
2126          * For EBB events we just context switch the PMC value, we don't do any
2127          * of the sample_period logic. We use hw.prev_count for this.
2128          */
2129         if (is_ebb_event(event))
2130                 local64_set(&event->hw.prev_count, 0);
2131
2132         /*
2133          * See if we need to reserve the PMU.
2134          * If no events are currently in use, then we have to take a
2135          * mutex to ensure that we don't race with another task doing
2136          * reserve_pmc_hardware or release_pmc_hardware.
2137          */
2138         err = 0;
2139         if (!atomic_inc_not_zero(&num_events)) {
2140                 mutex_lock(&pmc_reserve_mutex);
2141                 if (atomic_read(&num_events) == 0 &&
2142                     reserve_pmc_hardware(perf_event_interrupt))
2143                         err = -EBUSY;
2144                 else
2145                         atomic_inc(&num_events);
2146                 mutex_unlock(&pmc_reserve_mutex);
2147         }
2148         event->destroy = hw_perf_event_destroy;
2149
2150         return err;
2151 }
2152
2153 static int power_pmu_event_idx(struct perf_event *event)
2154 {
2155         return event->hw.idx;
2156 }
2157
2158 ssize_t power_events_sysfs_show(struct device *dev,
2159                                 struct device_attribute *attr, char *page)
2160 {
2161         struct perf_pmu_events_attr *pmu_attr;
2162
2163         pmu_attr = container_of(attr, struct perf_pmu_events_attr, attr);
2164
2165         return sprintf(page, "event=0x%02llx\n", pmu_attr->id);
2166 }
2167
2168 static struct pmu power_pmu = {
2169         .pmu_enable     = power_pmu_enable,
2170         .pmu_disable    = power_pmu_disable,
2171         .event_init     = power_pmu_event_init,
2172         .add            = power_pmu_add,
2173         .del            = power_pmu_del,
2174         .start          = power_pmu_start,
2175         .stop           = power_pmu_stop,
2176         .read           = power_pmu_read,
2177         .start_txn      = power_pmu_start_txn,
2178         .cancel_txn     = power_pmu_cancel_txn,
2179         .commit_txn     = power_pmu_commit_txn,
2180         .event_idx      = power_pmu_event_idx,
2181         .sched_task     = power_pmu_sched_task,
2182 };
2183
2184 #define PERF_SAMPLE_ADDR_TYPE  (PERF_SAMPLE_ADDR |              \
2185                                 PERF_SAMPLE_PHYS_ADDR |         \
2186                                 PERF_SAMPLE_DATA_PAGE_SIZE)
2187 /*
2188  * A counter has overflowed; update its count and record
2189  * things if requested.  Note that interrupts are hard-disabled
2190  * here so there is no possibility of being interrupted.
2191  */
2192 static void record_and_restart(struct perf_event *event, unsigned long val,
2193                                struct pt_regs *regs)
2194 {
2195         u64 period = event->hw.sample_period;
2196         s64 prev, delta, left;
2197         int record = 0;
2198
2199         if (event->hw.state & PERF_HES_STOPPED) {
2200                 write_pmc(event->hw.idx, 0);
2201                 return;
2202         }
2203
2204         /* we don't have to worry about interrupts here */
2205         prev = local64_read(&event->hw.prev_count);
2206         delta = check_and_compute_delta(prev, val);
2207         local64_add(delta, &event->count);
2208
2209         /*
2210          * See if the total period for this event has expired,
2211          * and update for the next period.
2212          */
2213         val = 0;
2214         left = local64_read(&event->hw.period_left) - delta;
2215         if (delta == 0)
2216                 left++;
2217         if (period) {
2218                 if (left <= 0) {
2219                         left += period;
2220                         if (left <= 0)
2221                                 left = period;
2222
2223                         /*
2224                          * If address is not requested in the sample via
2225                          * PERF_SAMPLE_IP, just record that sample irrespective
2226                          * of SIAR valid check.
2227                          */
2228                         if (event->attr.sample_type & PERF_SAMPLE_IP)
2229                                 record = siar_valid(regs);
2230                         else
2231                                 record = 1;
2232
2233                         event->hw.last_period = event->hw.sample_period;
2234                 }
2235                 if (left < 0x80000000LL)
2236                         val = 0x80000000LL - left;
2237         }
2238
2239         write_pmc(event->hw.idx, val);
2240         local64_set(&event->hw.prev_count, val);
2241         local64_set(&event->hw.period_left, left);
2242         perf_event_update_userpage(event);
2243
2244         /*
2245          * Due to hardware limitation, sometimes SIAR could sample a kernel
2246          * address even when freeze on supervisor state (kernel) is set in
2247          * MMCR2. Check attr.exclude_kernel and address to drop the sample in
2248          * these cases.
2249          */
2250         if (event->attr.exclude_kernel &&
2251             (event->attr.sample_type & PERF_SAMPLE_IP) &&
2252             is_kernel_addr(mfspr(SPRN_SIAR)))
2253                 record = 0;
2254
2255         /*
2256          * Finally record data if requested.
2257          */
2258         if (record) {
2259                 struct perf_sample_data data;
2260
2261                 perf_sample_data_init(&data, ~0ULL, event->hw.last_period);
2262
2263                 if (event->attr.sample_type & PERF_SAMPLE_ADDR_TYPE)
2264                         perf_get_data_addr(event, regs, &data.addr);
2265
2266                 if (event->attr.sample_type & PERF_SAMPLE_BRANCH_STACK) {
2267                         struct cpu_hw_events *cpuhw;
2268                         cpuhw = this_cpu_ptr(&cpu_hw_events);
2269                         power_pmu_bhrb_read(event, cpuhw);
2270                         data.br_stack = &cpuhw->bhrb_stack;
2271                 }
2272
2273                 if (event->attr.sample_type & PERF_SAMPLE_DATA_SRC &&
2274                                                 ppmu->get_mem_data_src)
2275                         ppmu->get_mem_data_src(&data.data_src, ppmu->flags, regs);
2276
2277                 if (event->attr.sample_type & PERF_SAMPLE_WEIGHT_TYPE &&
2278                                                 ppmu->get_mem_weight)
2279                         ppmu->get_mem_weight(&data.weight.full, event->attr.sample_type);
2280
2281                 if (perf_event_overflow(event, &data, regs))
2282                         power_pmu_stop(event, 0);
2283         } else if (period) {
2284                 /* Account for interrupt in case of invalid SIAR */
2285                 if (perf_event_account_interrupt(event))
2286                         power_pmu_stop(event, 0);
2287         }
2288 }
2289
2290 /*
2291  * Called from generic code to get the misc flags (i.e. processor mode)
2292  * for an event_id.
2293  */
2294 unsigned long perf_misc_flags(struct pt_regs *regs)
2295 {
2296         u32 flags = perf_get_misc_flags(regs);
2297
2298         if (flags)
2299                 return flags;
2300         return user_mode(regs) ? PERF_RECORD_MISC_USER :
2301                 PERF_RECORD_MISC_KERNEL;
2302 }
2303
2304 /*
2305  * Called from generic code to get the instruction pointer
2306  * for an event_id.
2307  */
2308 unsigned long perf_instruction_pointer(struct pt_regs *regs)
2309 {
2310         unsigned long siar = mfspr(SPRN_SIAR);
2311
2312         if (regs_use_siar(regs) && siar_valid(regs) && siar)
2313                 return siar + perf_ip_adjust(regs);
2314         else
2315                 return regs->nip;
2316 }
2317
2318 static bool pmc_overflow_power7(unsigned long val)
2319 {
2320         /*
2321          * Events on POWER7 can roll back if a speculative event doesn't
2322          * eventually complete. Unfortunately in some rare cases they will
2323          * raise a performance monitor exception. We need to catch this to
2324          * ensure we reset the PMC. In all cases the PMC will be 256 or less
2325          * cycles from overflow.
2326          *
2327          * We only do this if the first pass fails to find any overflowing
2328          * PMCs because a user might set a period of less than 256 and we
2329          * don't want to mistakenly reset them.
2330          */
2331         if ((0x80000000 - val) <= 256)
2332                 return true;
2333
2334         return false;
2335 }
2336
2337 static bool pmc_overflow(unsigned long val)
2338 {
2339         if ((int)val < 0)
2340                 return true;
2341
2342         return false;
2343 }
2344
2345 /*
2346  * Performance monitor interrupt stuff
2347  */
2348 static void __perf_event_interrupt(struct pt_regs *regs)
2349 {
2350         int i, j;
2351         struct cpu_hw_events *cpuhw = this_cpu_ptr(&cpu_hw_events);
2352         struct perf_event *event;
2353         int found, active;
2354
2355         if (cpuhw->n_limited)
2356                 freeze_limited_counters(cpuhw, mfspr(SPRN_PMC5),
2357                                         mfspr(SPRN_PMC6));
2358
2359         perf_read_regs(regs);
2360
2361         /* Read all the PMCs since we'll need them a bunch of times */
2362         for (i = 0; i < ppmu->n_counter; ++i)
2363                 cpuhw->pmcs[i] = read_pmc(i + 1);
2364
2365         /* Try to find what caused the IRQ */
2366         found = 0;
2367         for (i = 0; i < ppmu->n_counter; ++i) {
2368                 if (!pmc_overflow(cpuhw->pmcs[i]))
2369                         continue;
2370                 if (is_limited_pmc(i + 1))
2371                         continue; /* these won't generate IRQs */
2372                 /*
2373                  * We've found one that's overflowed.  For active
2374                  * counters we need to log this.  For inactive
2375                  * counters, we need to reset it anyway
2376                  */
2377                 found = 1;
2378                 active = 0;
2379                 for (j = 0; j < cpuhw->n_events; ++j) {
2380                         event = cpuhw->event[j];
2381                         if (event->hw.idx == (i + 1)) {
2382                                 active = 1;
2383                                 record_and_restart(event, cpuhw->pmcs[i], regs);
2384                                 break;
2385                         }
2386                 }
2387
2388                 /*
2389                  * Clear PACA_IRQ_PMI in case it was set by
2390                  * set_pmi_irq_pending() when PMU was enabled
2391                  * after accounting for interrupts.
2392                  */
2393                 clear_pmi_irq_pending();
2394
2395                 if (!active)
2396                         /* reset non active counters that have overflowed */
2397                         write_pmc(i + 1, 0);
2398         }
2399         if (!found && pvr_version_is(PVR_POWER7)) {
2400                 /* check active counters for special buggy p7 overflow */
2401                 for (i = 0; i < cpuhw->n_events; ++i) {
2402                         event = cpuhw->event[i];
2403                         if (!event->hw.idx || is_limited_pmc(event->hw.idx))
2404                                 continue;
2405                         if (pmc_overflow_power7(cpuhw->pmcs[event->hw.idx - 1])) {
2406                                 /* event has overflowed in a buggy way*/
2407                                 found = 1;
2408                                 record_and_restart(event,
2409                                                    cpuhw->pmcs[event->hw.idx - 1],
2410                                                    regs);
2411                         }
2412                 }
2413         }
2414
2415         /*
2416          * During system wide profling or while specific CPU is monitored for an
2417          * event, some corner cases could cause PMC to overflow in idle path. This
2418          * will trigger a PMI after waking up from idle. Since counter values are _not_
2419          * saved/restored in idle path, can lead to below "Can't find PMC" message.
2420          */
2421         if (unlikely(!found) && !arch_irq_disabled_regs(regs))
2422                 printk_ratelimited(KERN_WARNING "Can't find PMC that caused IRQ\n");
2423
2424         /*
2425          * Reset MMCR0 to its normal value.  This will set PMXE and
2426          * clear FC (freeze counters) and PMAO (perf mon alert occurred)
2427          * and thus allow interrupts to occur again.
2428          * XXX might want to use MSR.PM to keep the events frozen until
2429          * we get back out of this interrupt.
2430          */
2431         write_mmcr0(cpuhw, cpuhw->mmcr.mmcr0);
2432
2433         /* Clear the cpuhw->pmcs */
2434         memset(&cpuhw->pmcs, 0, sizeof(cpuhw->pmcs));
2435
2436 }
2437
2438 static void perf_event_interrupt(struct pt_regs *regs)
2439 {
2440         u64 start_clock = sched_clock();
2441
2442         __perf_event_interrupt(regs);
2443         perf_sample_event_took(sched_clock() - start_clock);
2444 }
2445
2446 static int power_pmu_prepare_cpu(unsigned int cpu)
2447 {
2448         struct cpu_hw_events *cpuhw = &per_cpu(cpu_hw_events, cpu);
2449
2450         if (ppmu) {
2451                 memset(cpuhw, 0, sizeof(*cpuhw));
2452                 cpuhw->mmcr.mmcr0 = MMCR0_FC;
2453         }
2454         return 0;
2455 }
2456
2457 int register_power_pmu(struct power_pmu *pmu)
2458 {
2459         if (ppmu)
2460                 return -EBUSY;          /* something's already registered */
2461
2462         ppmu = pmu;
2463         pr_info("%s performance monitor hardware support registered\n",
2464                 pmu->name);
2465
2466         power_pmu.attr_groups = ppmu->attr_groups;
2467         power_pmu.capabilities |= (ppmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS);
2468
2469 #ifdef MSR_HV
2470         /*
2471          * Use FCHV to ignore kernel events if MSR.HV is set.
2472          */
2473         if (mfmsr() & MSR_HV)
2474                 freeze_events_kernel = MMCR0_FCHV;
2475 #endif /* CONFIG_PPC64 */
2476
2477         perf_pmu_register(&power_pmu, "cpu", PERF_TYPE_RAW);
2478         cpuhp_setup_state(CPUHP_PERF_POWER, "perf/powerpc:prepare",
2479                           power_pmu_prepare_cpu, NULL);
2480         return 0;
2481 }
2482
2483 #ifdef CONFIG_PPC64
2484 static int __init init_ppc64_pmu(void)
2485 {
2486         /* run through all the pmu drivers one at a time */
2487         if (!init_power5_pmu())
2488                 return 0;
2489         else if (!init_power5p_pmu())
2490                 return 0;
2491         else if (!init_power6_pmu())
2492                 return 0;
2493         else if (!init_power7_pmu())
2494                 return 0;
2495         else if (!init_power8_pmu())
2496                 return 0;
2497         else if (!init_power9_pmu())
2498                 return 0;
2499         else if (!init_power10_pmu())
2500                 return 0;
2501         else if (!init_ppc970_pmu())
2502                 return 0;
2503         else
2504                 return init_generic_compat_pmu();
2505 }
2506 early_initcall(init_ppc64_pmu);
2507 #endif