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