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