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