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